diff --git a/.editorconfig b/.editorconfig index d416e1c9e6..192e956de4 100644 --- a/.editorconfig +++ b/.editorconfig @@ -8,3 +8,6 @@ trim_trailing_whitespace = true [*.ts] indent_style = space indent_size = 2 + +[*.{yml,yaml}] +indent_size = 2 diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 1c514912c5..f660790713 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -2,4 +2,4 @@ blank_issues_enabled: true contact_links: - name: Contact GitHub Support url: https://support.github.com/request - about: Contact Support + about: Contact Support diff --git a/.github/actions/check-codescanning-config/action.yml b/.github/actions/check-codescanning-config/action.yml index 0c65c3a41d..bd680cc9fa 100644 --- a/.github/actions/check-codescanning-config/action.yml +++ b/.github/actions/check-codescanning-config/action.yml @@ -1,7 +1,7 @@ name: Check Code-Scanning Config description: | - Checks the code scanning configuration file generated by the - action to ensure it contains the expected contents + Checks the code scanning configuration file generated by the + action to ensure it contains the expected contents inputs: languages: required: false @@ -52,7 +52,7 @@ runs: tools: ${{ inputs.tools }} db-location: ${{ runner.temp }}/codescanning-config-cli-test env: - CODEQL_ACTION_TEST_MODE: 'true' + CODEQL_ACTION_TEST_MODE: "true" - name: Install dependencies shell: bash @@ -62,7 +62,7 @@ runs: working-directory: ${{ github.action_path }} shell: bash env: - EXPECTED_CONFIG_FILE_CONTENTS: '${{ inputs.expected-config-file-contents }}' + EXPECTED_CONFIG_FILE_CONTENTS: "${{ inputs.expected-config-file-contents }}" run: ts-node ./index.ts "$RUNNER_TEMP/user-config.yaml" "$EXPECTED_CONFIG_FILE_CONTENTS" - name: Clean up shell: bash diff --git a/.github/actions/prepare-mergeback-branch/action.yml b/.github/actions/prepare-mergeback-branch/action.yml index 2c57dfc012..8d22e547e6 100644 --- a/.github/actions/prepare-mergeback-branch/action.yml +++ b/.github/actions/prepare-mergeback-branch/action.yml @@ -92,8 +92,7 @@ runs: Please do the following: - [ ] Approve running the full set of PR checks. - - [ ] Approve and merge the PR. When merging the PR, make sure "Create a merge commit" is - selected rather than "Squash and merge" or "Rebase and merge". + - [ ] Approve and merge the PR. When merging the PR, make sure "Create a merge commit" is selected rather than "Squash and merge" or "Rebase and merge". EOF ) diff --git a/.github/actions/prepare-test/action.yml b/.github/actions/prepare-test/action.yml index 5e2b5028f7..4c11ec4929 100644 --- a/.github/actions/prepare-test/action.yml +++ b/.github/actions/prepare-test/action.yml @@ -6,11 +6,11 @@ inputs: required: true use-all-platform-bundle: description: "If true, we output a tools URL with codeql-bundle.tar.gz file rather than platform-specific URL" - default: 'false' + default: "false" required: false setup-kotlin: description: "If true, we setup kotlin" - default: 'true' + default: "true" required: true outputs: tools-url: @@ -73,7 +73,10 @@ runs: exit 1 fi - - uses: fwilhe2/setup-kotlin@9c245a6425255f5e98ba1ce6c15d31fce7eca9da + - uses: fwilhe2/setup-kotlin@b325539ca8f6e1d9ee04efed06f49bdbf5426dbb # v2.1 if: ${{ inputs.setup-kotlin == 'true' }} with: - version: 1.8.21 + # Kotlin is installed on the runners by default, but the version that is pre-installed is too new + # to be supported by CodeQL. This Kotlin version is selected to be compatible with both the default Java + # version on the `ubuntu-latest` runners and CodeQL. + version: 2.1.20 diff --git a/.github/actions/query-filter-test/action.yml b/.github/actions/query-filter-test/action.yml index f1dfc38bf2..ab4f9286af 100644 --- a/.github/actions/query-filter-test/action.yml +++ b/.github/actions/query-filter-test/action.yml @@ -54,7 +54,7 @@ runs: - name: Check SARIF uses: ./../action/.github/actions/check-sarif with: - sarif-file: ${{ inputs.sarif-file }} + sarif-file: ${{ inputs.sarif-file }} queries-run: ${{ inputs.queries-run}} queries-not-run: ${{ inputs.queries-not-run}} - name: Cleanup after test diff --git a/.github/actions/release-branches/action.yml b/.github/actions/release-branches/action.yml index 7734411c73..3d08d43ec4 100644 --- a/.github/actions/release-branches/action.yml +++ b/.github/actions/release-branches/action.yml @@ -1,11 +1,11 @@ -name: 'Release branches' -description: 'Determine branches for release & backport' +name: "Release branches" +description: "Determine branches for release & backport" inputs: major_version: - description: 'The version as extracted from the package.json file' + description: "The version as extracted from the package.json file" required: true latest_tag: - description: 'The most recent tag published to the repository' + description: "The most recent tag published to the repository" required: true outputs: backport_source_branch: diff --git a/.github/actions/release-initialise/action.yml b/.github/actions/release-initialise/action.yml index 239dfa9428..d0e99f4ed8 100644 --- a/.github/actions/release-initialise/action.yml +++ b/.github/actions/release-initialise/action.yml @@ -1,25 +1,24 @@ -name: 'Prepare release job' -description: 'Prepare for updating a release branch' +name: "Prepare release job" +description: "Prepare for updating a release branch" runs: using: "composite" steps: - - name: Dump environment run: env shell: bash - name: Dump GitHub context env: - GITHUB_CONTEXT: '${{ toJson(github) }}' + GITHUB_CONTEXT: "${{ toJson(github) }}" run: echo "$GITHUB_CONTEXT" shell: bash - name: Set up Node - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 - cache: 'npm' + cache: "npm" - name: Install JavaScript dependencies shell: bash diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 35a89a227a..9562cf6a4a 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,14 +1,46 @@ # CodeQL Action - Copilot Instructions +The CodeQL Action is used in GitHub Actions workflows to run CodeQL scans using the CodeQL CLI. + +## Overview + +- The repository contains two TypeScript projects. +- The main TypeScript codebase is in the `src` directory, with accompanying unit tests in `.test.ts` files in the same directory. +- The main codebase is compiled to bundled JavaScript code, which is also contained in the repository in the `lib` directory. +- A secondary TypeScript codebase with scripts that are only used for development purposes or by CI is in the `pr-checks` directory. This codebase is not compiled to bundled JavaScript. It is executed directly with `tsx`, which handles compilation internally. + +## Review instructions + +- Prioritise identifying critical issues, such as logic bugs, over comments on documentation or typos. +- When wording review comments, be helpful and friendly. Assume that the PR author has written the code with the best of intentions. Never word suggestions as commands or using the imperative. Examples of what you should never write: "Preserve that non-fatal behaviour here" or "Please preserve that non-fatal behaviour here". +- When writing feedback, assume that the PR author is competent and is able to understand whether the point you are making is valid or not, why you are raising it, and how to best address it. While you can suggest how to address a point you are making, don't phrase it as a requirement or assume that it is the only solution. +- Always word your comments constructively as suggestions for improvements, for example: "It would make sense to ..." or "Could you add ...?" or "Would it make sense to ...?" +- If you want to comment on a change that you believe will fail a CI check, do not present the CI failure you expect as a fact. Instead, write that you think a change "may" lead to a failure in CI. Suggest that, if such a failure manifests, the changes you are commenting on may be the place responsible for the failure and are worth looking at. +- If a suggestion you make is suitable for a follow-up, such as a refactoring that doesn't change the behaviour or fixing a typo in a comment, mention that it can be addressed in a later PR rather than blocking this one or prefix your comment with "Minor: ". +- If a change is a net improvement, for example because it improves on an existing limitation of existing code, do not complain about pre-existing problems that remain. You may comment on them, but you should make it clear that the thing you are commenting on is not new by writing e.g. "Not new in this PR, but [..]" followed by your description of the issue and a suggestion that it could be improved at the same time with e.g. "Consider whether this is worth addressing as part of this PR as well." + ## Generated code -The CodeQL Action is written in TypeScript and compiled to JavaScript. Both the TypeScript sources and the **generated** JavaScript code are contained in this repository. The TypeScript sources are contained in the `src` directory and the JavaScript code is contained in the `lib` directory. A GitHub Actions workflow checks that the JavaScript code in `lib` is up-to-date. Therefore, you should not review any changes to the contents of the `lib` folder and it is expected that the JavaScript code in `lib` closely mirrors the TypeScript code it is generated from. +The main codebase of the CodeQL Action is written in TypeScript and compiled to JavaScript. Both the TypeScript sources and the **generated** JavaScript code are contained in this repository. The TypeScript sources are contained in the `src` directory and the JavaScript code is contained in the `lib` directory. A GitHub Actions workflow checks that the JavaScript code in `lib` is up-to-date. Therefore, you should not review any changes to the contents of the `lib` folder and it is expected that the JavaScript code in `lib` closely mirrors the TypeScript code it is generated from. The secondary TypeScript codebase has sources in the `pr-checks` directory, which are executed directly with `tsx` and not compiled to JavaScript in the `lib` folder. GitHub Actions workflows in the `.github/workflows` directory whose filenames start with two underscores (e.g. `__all-platform-bundle.yml`) are automatically generated using the `pr-checks/sync.sh` script from template files in the `pr-checks/checks` directory. Therefore, you do not need to review files in the `.github/workflows` directory that start with two underscores. However, you should review changes to the `pr-checks` directory as well as workflows in the `.github/workflows` directory that do not start with underscores. +## Feature flags + +Some functionality in the code may be gated behind feature flags, which are controlled server-side. If the functionality that is gated behind them is user-facing, then this should be documented in a change note at the time that the gated functionality is added. See `CHANGELOG.md` for existing notes that mention "experimental" for examples. These typically include information about when users may expect to see the feature rolled out. + +When a feature flag that gates some functionality is removed, this does not need to be documented in a change note since the feature is already rolled out and the notes for the release which introduced the feature already describe it. The only exception is functionality which will start having an effect on GHES as a result of the feature flag removal: + +- Most functionality gated behind feature flags does not affect GHES. +- We can make functionality available on GHES by setting `defaultValue` to `true` first and waiting for this to have had an effect on GHES. No change note is needed if a feature flag is removed where `defaultValue` was `true`. +- When removing a feature flag where `defaultValue` was `false` and the functionality starts to affect GHES, a change note may be appropriate. + ## Release process +Changes that are merged to the `main` branch are not used in production straight away. Instead, changes from `main` must first be released using the release process, which has to be manually triggered by a staff member. Therefore, it is possible for further changes to be made to the code after some changes have been merged to `main` but before they are released. Once the release process automation is started, a series of PRs are automatically generated: + - A release-PR is a PR which matches all of the following patterns: + - PR title starts with the exact prefix: `Merge main into releases/v` - Equivalent regex: `^Merge main into releases\/v` - AND head (source) branch matches the update-branch pattern: @@ -17,5 +49,5 @@ GitHub Actions workflows in the `.github/workflows` directory whose filenames st - Regex: `^releases\/v` (e.g. `releases/v3`) - Consider all files in release-PRs to have already been reviewed and do not review them, except for the following two files: - - `CHANGELOG.md` - - `package.json` + - `CHANGELOG.md` + - `package.json` diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d29c1e106c..49109fadef 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -8,8 +8,6 @@ updates: interval: weekly cooldown: default-days: 7 - exclude: - - "@actions/*" labels: - Rebuild # Ignore incompatible dependency updates @@ -18,6 +16,14 @@ updates: # This might be fixed when we move to eslint v9. - dependency-name: "eslint-plugin-import" versions: [">=2.30.0"] + + # Some of our dependencies are lagging behind with support for new versions of + # `undici` which is why we have to override it in `package.json`. Dependabot + # workflows fail when they try to update a dependency that is explicitly + # overriden. Since this happens somewhat routinely at the moment, we are + # excluding `undici` here and have to manually update it when needed. + - dependency-name: "undici" + versions: [">=7.30.1"] groups: npm-minor: patterns: @@ -28,13 +34,11 @@ updates: - package-ecosystem: github-actions directories: - "/.github/workflows" - - "/.github/actions" + - "/.github/actions/*/" schedule: interval: weekly cooldown: default-days: 7 - exclude: - - "actions/*" labels: - Rebuild groups: diff --git a/.github/instructions/release-merge.instructions.md b/.github/instructions/release-merge.instructions.md new file mode 100644 index 0000000000..6111917356 --- /dev/null +++ b/.github/instructions/release-merge.instructions.md @@ -0,0 +1,16 @@ +--- +applyTo: "CHANGELOG.md,src/defaults.json,lib/defaults.json,src/api-compatibility.json" +--- + +# Merging release, mergeback, and backport PRs + +The release process creates a cascade of PRs (`main` → `releases/vN`, then +`releases/vN` → `main` mergeback, then `releases/vN` → `releases/v(N-1)` +backport). These PRs reliably touch `CHANGELOG.md`, `src/defaults.json` / +`lib/defaults.json` (bundle/CLI version bump), and `src/api-compatibility.json`. + +Such PRs **must be merged with a merge commit**. Never squash or rebase, as +that breaks the branch linkage the release automation relies on. + +When arming auto-merge on these PRs, use `--merge` (e.g. `gh pr merge --merge`), +not `--squash` or `--rebase`. diff --git a/.github/workflows/__all-platform-bundle.yml b/.github/workflows/__all-platform-bundle.yml index c3cf8d63f3..22635a0d14 100644 --- a/.github/workflows/__all-platform-bundle.yml +++ b/.github/workflows/__all-platform-bundle.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,11 +54,11 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - - os: macos-latest + - os: macos-26-xlarge version: nightly-latest - - os: windows-latest + - os: windows-2025 version: nightly-latest name: All-platform bundle if: github.triggering_actor != 'dependabot[bot]' @@ -84,8 +84,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'true' - setup-kotlin: 'true' + use-all-platform-bundle: "true" + setup-kotlin: "true" - id: init uses: ./../action/init with: diff --git a/.github/workflows/__analysis-kinds.yml b/.github/workflows/__analysis-kinds.yml index 5d0576e2f6..f916bda40a 100644 --- a/.github/workflows/__analysis-kinds.yml +++ b/.github/workflows/__analysis-kinds.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,28 +34,28 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked analysis-kinds: code-scanning - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked analysis-kinds: code-quality - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked analysis-kinds: code-scanning,code-quality - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked analysis-kinds: risk-assessment - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest analysis-kinds: code-scanning - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest analysis-kinds: code-quality - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest analysis-kinds: code-scanning,code-quality - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest analysis-kinds: risk-assessment name: Analysis kinds @@ -73,8 +73,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: javascript @@ -82,24 +82,24 @@ jobs: tools: ${{ steps.prepare-test.outputs.tools-url }} - uses: ./../action/analyze with: - output: '${{ runner.temp }}/results' + output: "${{ runner.temp }}/results" upload-database: false - post-processed-sarif-path: '${{ runner.temp }}/post-processed' + post-processed-sarif-path: "${{ runner.temp }}/post-processed" - name: Upload SARIF files - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: | analysis-kinds-${{ matrix.os }}-${{ matrix.version }}-${{ matrix.analysis-kinds }} - path: '${{ runner.temp }}/results/*.sarif' + path: "${{ runner.temp }}/results/*.sarif" retention-days: 7 - name: Upload post-processed SARIF - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: | post-processed-${{ matrix.os }}-${{ matrix.version }}-${{ matrix.analysis-kinds }} - path: '${{ runner.temp }}/post-processed' + path: "${{ runner.temp }}/post-processed" retention-days: 7 if-no-files-found: error @@ -107,16 +107,16 @@ jobs: if: contains(matrix.analysis-kinds, 'code-scanning') uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: - SARIF_PATH: '${{ runner.temp }}/results/javascript.sarif' - EXPECT_PRESENT: 'false' + SARIF_PATH: "${{ runner.temp }}/results/javascript.sarif" + EXPECT_PRESENT: "false" with: script: ${{ env.CHECK_SCRIPT }} - name: Check quality query appears in quality SARIF if: contains(matrix.analysis-kinds, 'code-quality') uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: - SARIF_PATH: '${{ runner.temp }}/results/javascript.quality.sarif' - EXPECT_PRESENT: 'true' + SARIF_PATH: "${{ runner.temp }}/results/javascript.quality.sarif" + EXPECT_PRESENT: "true" with: script: ${{ env.CHECK_SCRIPT }} env: diff --git a/.github/workflows/__analyze-ref-input.yml b/.github/workflows/__analyze-ref-input.yml index 7341a41740..e12f918e40 100644 --- a/.github/workflows/__analyze-ref-input.yml +++ b/.github/workflows/__analyze-ref-input.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,7 +54,7 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: default name: "Analyze: 'ref' and 'sha' from inputs" if: github.triggering_actor != 'dependabot[bot]' @@ -80,8 +80,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: tools: ${{ steps.prepare-test.outputs.tools-url }} @@ -91,7 +91,7 @@ jobs: run: ./build.sh - uses: ./../action/analyze with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" env: CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__autobuild-action.yml b/.github/workflows/__autobuild-action.yml index 730a387f90..c9e495d0aa 100644 --- a/.github/workflows/__autobuild-action.yml +++ b/.github/workflows/__autobuild-action.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -44,11 +44,11 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: macos-latest + - os: macos-26 version: linked - - os: windows-latest + - os: windows-2025 version: linked name: autobuild-action if: github.triggering_actor != 'dependabot[bot]' @@ -69,8 +69,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: csharp @@ -78,12 +78,12 @@ jobs: - uses: ./../action/autobuild env: # Explicitly disable the CLR tracer. - COR_ENABLE_PROFILING: '' - COR_PROFILER: '' - COR_PROFILER_PATH_64: '' - CORECLR_ENABLE_PROFILING: '' - CORECLR_PROFILER: '' - CORECLR_PROFILER_PATH_64: '' + COR_ENABLE_PROFILING: "" + COR_PROFILER: "" + COR_PROFILER_PATH_64: "" + CORECLR_ENABLE_PROFILING: "" + CORECLR_PROFILER: "" + CORECLR_PROFILER_PATH_64: "" - uses: ./../action/analyze - name: Check database run: | diff --git a/.github/workflows/__autobuild-direct-tracing-with-working-dir.yml b/.github/workflows/__autobuild-direct-tracing-with-working-dir.yml index b527638feb..b28b6a0843 100644 --- a/.github/workflows/__autobuild-direct-tracing-with-working-dir.yml +++ b/.github/workflows/__autobuild-direct-tracing-with-working-dir.yml @@ -17,21 +17,21 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: java-version: type: string description: The version of Java to install required: false - default: '17' + default: "17" workflow_call: inputs: java-version: type: string description: The version of Java to install required: false - default: '17' + default: "17" defaults: run: shell: bash @@ -44,13 +44,13 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: windows-latest + - os: windows-2025 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - - os: windows-latest + - os: windows-2025 version: nightly-latest name: Autobuild direct tracing (custom working directory) if: github.triggering_actor != 'dependabot[bot]' @@ -63,7 +63,7 @@ jobs: - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install Java - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 with: java-version: ${{ inputs.java-version || '17' }} distribution: temurin @@ -72,8 +72,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Test setup run: | # Make sure that Gradle build succeeds in autobuild-dir ... diff --git a/.github/workflows/__autobuild-working-dir.yml b/.github/workflows/__autobuild-working-dir.yml index fac4ef9f54..930df5d7cd 100644 --- a/.github/workflows/__autobuild-working-dir.yml +++ b/.github/workflows/__autobuild-working-dir.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,7 +34,7 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked name: Autobuild working directory if: github.triggering_actor != 'dependabot[bot]' @@ -51,8 +51,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Test setup run: | # Make sure that Gradle build succeeds in autobuild-dir ... diff --git a/.github/workflows/__build-mode-autobuild.yml b/.github/workflows/__build-mode-autobuild.yml index 5043433ee3..e0e74bda18 100644 --- a/.github/workflows/__build-mode-autobuild.yml +++ b/.github/workflows/__build-mode-autobuild.yml @@ -17,21 +17,21 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: java-version: type: string description: The version of Java to install required: false - default: '17' + default: "17" workflow_call: inputs: java-version: type: string description: The version of Java to install required: false - default: '17' + default: "17" defaults: run: shell: bash @@ -44,13 +44,13 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: windows-latest + - os: windows-2025 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - - os: windows-latest + - os: windows-2025 version: nightly-latest name: Build mode autobuild if: github.triggering_actor != 'dependabot[bot]' @@ -63,7 +63,7 @@ jobs: - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install Java - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 with: java-version: ${{ inputs.java-version || '17' }} distribution: temurin @@ -80,8 +80,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Set up Java test repo configuration run: | mv * .github ../action/tests/multi-language-repo/ @@ -92,7 +92,7 @@ jobs: id: init with: build-mode: autobuild - db-location: '${{ runner.temp }}/customDbLocation' + db-location: "${{ runner.temp }}/customDbLocation" languages: java tools: ${{ steps.prepare-test.outputs.tools-url }} diff --git a/.github/workflows/__build-mode-manual.yml b/.github/workflows/__build-mode-manual.yml index bfe92c55ea..ecca039520 100644 --- a/.github/workflows/__build-mode-manual.yml +++ b/.github/workflows/__build-mode-manual.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,7 +54,7 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Build mode manual if: github.triggering_actor != 'dependabot[bot]' @@ -80,13 +80,13 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init id: init with: build-mode: manual - db-location: '${{ runner.temp }}/customDbLocation' + db-location: "${{ runner.temp }}/customDbLocation" languages: java tools: ${{ steps.prepare-test.outputs.tools-url }} diff --git a/.github/workflows/__build-mode-none.yml b/.github/workflows/__build-mode-none.yml index da7aa76383..c01ba25394 100644 --- a/.github/workflows/__build-mode-none.yml +++ b/.github/workflows/__build-mode-none.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,9 +34,9 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Build mode none if: github.triggering_actor != 'dependabot[bot]' @@ -53,13 +53,13 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init id: init with: build-mode: none - db-location: '${{ runner.temp }}/customDbLocation' + db-location: "${{ runner.temp }}/customDbLocation" languages: java tools: ${{ steps.prepare-test.outputs.tools-url }} diff --git a/.github/workflows/__build-mode-rollback.yml b/.github/workflows/__build-mode-rollback.yml index fcc77ea36e..e18b411562 100644 --- a/.github/workflows/__build-mode-rollback.yml +++ b/.github/workflows/__build-mode-rollback.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,7 +34,7 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Build mode rollback if: github.triggering_actor != 'dependabot[bot]' @@ -51,8 +51,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Set up Java test repo configuration run: | mv * .github ../action/tests/multi-language-repo/ @@ -63,7 +63,7 @@ jobs: id: init with: build-mode: none - db-location: '${{ runner.temp }}/customDbLocation' + db-location: "${{ runner.temp }}/customDbLocation" languages: java tools: ${{ steps.prepare-test.outputs.tools-url }} diff --git a/.github/workflows/__bundle-from-nightly.yml b/.github/workflows/__bundle-from-nightly.yml index 6c414fb67e..57b2503e65 100644 --- a/.github/workflows/__bundle-from-nightly.yml +++ b/.github/workflows/__bundle-from-nightly.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Bundle: From nightly' +name: "PR Check - Bundle: From nightly" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,9 +34,9 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - name: 'Bundle: From nightly' + name: "Bundle: From nightly" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -51,8 +51,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - id: init uses: ./../action/init env: diff --git a/.github/workflows/__bundle-from-toolcache.yml b/.github/workflows/__bundle-from-toolcache.yml index a1c1fade09..23011be214 100644 --- a/.github/workflows/__bundle-from-toolcache.yml +++ b/.github/workflows/__bundle-from-toolcache.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Bundle: From toolcache' +name: "PR Check - Bundle: From toolcache" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,9 +34,9 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: toolcache - name: 'Bundle: From toolcache' + name: "Bundle: From toolcache" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -46,38 +46,36 @@ jobs: steps: - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 20.x + cache: npm + - name: Install newer npm + run: npm install -g npm@11.19.1 + - name: Install dependencies + run: npm ci - name: Prepare test id: prepare-test uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' - - name: Install @actions/tool-cache - run: npm install @actions/tool-cache@3 + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Check toolcache contains CodeQL continue-on-error: true - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 - with: - script: | - const toolcache = require('@actions/tool-cache'); - const allCodeqlVersions = toolcache.findAllVersions('CodeQL'); - if (allCodeqlVersions.length === 0) { - throw new Error(`CodeQL could not be found in the toolcache`); - } + run: | + cd ./../action + npx tsx ./pr-checks/toolcache.ts installed + - id: setup-codeql uses: ./../action/setup-codeql with: tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Check CodeQL is installed within the toolcache - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 - with: - script: | - const toolcache = require('@actions/tool-cache'); - const allCodeqlVersions = toolcache.findAllVersions('CodeQL'); - console.log(`Found CodeQL versions: ${allCodeqlVersions}`); - if (allCodeqlVersions.length === 0) { - throw new Error('CodeQL not found in toolcache'); - } + run: | + cd ./../action + npx tsx ./pr-checks/toolcache.ts installed env: CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__bundle-toolcache.yml b/.github/workflows/__bundle-toolcache.yml index 9cc983a843..fca8336971 100644 --- a/.github/workflows/__bundle-toolcache.yml +++ b/.github/workflows/__bundle-toolcache.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Bundle: Caching checks' +name: "PR Check - Bundle: Caching checks" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,13 +34,13 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: macos-latest + - os: macos-26 version: linked - - os: windows-latest + - os: windows-2025 version: linked - name: 'Bundle: Caching checks' + name: "Bundle: Caching checks" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -50,54 +50,47 @@ jobs: steps: - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 20.x + cache: npm + - name: Install newer npm + run: npm install -g npm@11.19.1 + - name: Install dependencies + run: npm ci - name: Prepare test id: prepare-test uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Remove CodeQL from toolcache - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 - with: - script: | - const fs = require('fs'); - const path = require('path'); - const codeqlPath = path.join(process.env['RUNNER_TOOL_CACHE'], 'CodeQL'); - fs.rmdirSync(codeqlPath, { recursive: true }); - - name: Install @actions/tool-cache - run: npm install @actions/tool-cache@3 + run: | + cd ./../action + npx tsx ./pr-checks/toolcache.ts clear + - name: Check toolcache does not contain CodeQL - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 - with: - script: | - const toolcache = require('@actions/tool-cache'); - const allCodeqlVersions = toolcache.findAllVersions('CodeQL'); - if (allCodeqlVersions.length !== 0) { - throw new Error(`CodeQL should not be found in the toolcache, but found ${allCodeqlVersions}`); - } - console.log('No versions of CodeQL found in the toolcache'); + run: | + cd ./../action + npx tsx ./pr-checks/toolcache.ts absent + - id: init uses: ./../action/init with: - languages: javascript + # Request multiple languages so this check uses the combined bundle. + languages: javascript,python tools: ${{ steps.prepare-test.outputs.tools-url }} + - uses: ./../action/analyze with: output: ${{ runner.temp }}/results upload-database: false + - name: Check CodeQL is installed within the toolcache - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 - with: - script: | - const toolcache = require('@actions/tool-cache'); - const allCodeqlVersions = toolcache.findAllVersions('CodeQL'); - console.log(`Found CodeQL versions: ${allCodeqlVersions}`); - if (allCodeqlVersions.length === 0) { - throw new Error('CodeQL not found in toolcache'); - } - if (allCodeqlVersions.length > 1) { - throw new Error('Multiple CodeQL versions found in toolcache'); - } + run: | + cd ./../action + npx tsx ./pr-checks/toolcache.ts installed -n 1 env: CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__cleanup-db-cluster-dir.yml b/.github/workflows/__cleanup-db-cluster-dir.yml index 3153041401..ce9ee41da3 100644 --- a/.github/workflows/__cleanup-db-cluster-dir.yml +++ b/.github/workflows/__cleanup-db-cluster-dir.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,7 +34,7 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked name: Clean up database cluster directory if: github.triggering_actor != 'dependabot[bot]' @@ -51,8 +51,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Add a file to the database cluster directory run: | mkdir -p "${{ runner.temp }}/customDbLocation/javascript" @@ -62,7 +62,7 @@ jobs: id: init with: build-mode: none - db-location: '${{ runner.temp }}/customDbLocation' + db-location: "${{ runner.temp }}/customDbLocation" languages: javascript tools: ${{ steps.prepare-test.outputs.tools-url }} diff --git a/.github/workflows/__config-export.yml b/.github/workflows/__config-export.yml index 0c7a2cc151..da9e743a61 100644 --- a/.github/workflows/__config-export.yml +++ b/.github/workflows/__config-export.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,9 +34,9 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Config export if: github.triggering_actor != 'dependabot[bot]' @@ -53,8 +53,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: javascript @@ -62,18 +62,18 @@ jobs: tools: ${{ steps.prepare-test.outputs.tools-url }} - uses: ./../action/analyze with: - output: '${{ runner.temp }}/results' + output: "${{ runner.temp }}/results" upload-database: false - name: Upload SARIF - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: config-export-${{ matrix.os }}-${{ matrix.version }}.sarif.json - path: '${{ runner.temp }}/results/javascript.sarif' + path: "${{ runner.temp }}/results/javascript.sarif" retention-days: 7 - name: Check config properties appear in SARIF uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: - SARIF_PATH: '${{ runner.temp }}/results/javascript.sarif' + SARIF_PATH: "${{ runner.temp }}/results/javascript.sarif" with: script: | const fs = require('fs'); diff --git a/.github/workflows/__config-input.yml b/.github/workflows/__config-input.yml index 4267e00584..03934bd439 100644 --- a/.github/workflows/__config-input.yml +++ b/.github/workflows/__config-input.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,7 +34,7 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked name: Config input if: github.triggering_actor != 'dependabot[bot]' @@ -47,10 +47,12 @@ jobs: - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 20.x cache: npm + - name: Install newer npm + run: npm install -g npm@11.19.1 - name: Install dependencies run: npm ci - name: Prepare test @@ -58,8 +60,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Copy queries into workspace run: | cp -a ../action/queries . diff --git a/.github/workflows/__cpp-deptrace-disabled.yml b/.github/workflows/__cpp-deptrace-disabled.yml index e2434f4256..5f24cd8cf8 100644 --- a/.github/workflows/__cpp-deptrace-disabled.yml +++ b/.github/workflows/__cpp-deptrace-disabled.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - C/C++: disabling autoinstalling dependencies (Linux)' +name: "PR Check - C/C++: disabling autoinstalling dependencies (Linux)" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,13 +34,13 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - name: 'C/C++: disabling autoinstalling dependencies (Linux)' + name: "C/C++: disabling autoinstalling dependencies (Linux)" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -55,8 +55,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Test setup run: | cp -a ../action/tests/cpp-autobuild autobuild-dir @@ -75,5 +75,5 @@ jobs: exit 1 fi env: - DOTNET_GENERATE_ASPNET_CERTIFICATE: 'false' + DOTNET_GENERATE_ASPNET_CERTIFICATE: "false" CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__cpp-deptrace-enabled-on-macos.yml b/.github/workflows/__cpp-deptrace-enabled-on-macos.yml index 344ed8d1ea..c0794ee878 100644 --- a/.github/workflows/__cpp-deptrace-enabled-on-macos.yml +++ b/.github/workflows/__cpp-deptrace-enabled-on-macos.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - C/C++: autoinstalling dependencies is skipped (macOS)' +name: "PR Check - C/C++: autoinstalling dependencies is skipped (macOS)" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,11 +34,11 @@ jobs: fail-fast: false matrix: include: - - os: macos-latest + - os: macos-26 version: linked - - os: macos-latest + - os: macos-26 version: nightly-latest - name: 'C/C++: autoinstalling dependencies is skipped (macOS)' + name: "C/C++: autoinstalling dependencies is skipped (macOS)" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -53,8 +53,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Test setup run: | cp -a ../action/tests/cpp-autobuild autobuild-dir @@ -75,5 +75,5 @@ jobs: exit 1 fi env: - DOTNET_GENERATE_ASPNET_CERTIFICATE: 'false' + DOTNET_GENERATE_ASPNET_CERTIFICATE: "false" CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__cpp-deptrace-enabled.yml b/.github/workflows/__cpp-deptrace-enabled.yml index ab1a70584b..dd74b17d6c 100644 --- a/.github/workflows/__cpp-deptrace-enabled.yml +++ b/.github/workflows/__cpp-deptrace-enabled.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - C/C++: autoinstalling dependencies (Linux)' +name: "PR Check - C/C++: autoinstalling dependencies (Linux)" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,13 +34,13 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - name: 'C/C++: autoinstalling dependencies (Linux)' + name: "C/C++: autoinstalling dependencies (Linux)" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -55,8 +55,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Test setup run: | cp -a ../action/tests/cpp-autobuild autobuild-dir @@ -75,5 +75,5 @@ jobs: exit 1 fi env: - DOTNET_GENERATE_ASPNET_CERTIFICATE: 'false' + DOTNET_GENERATE_ASPNET_CERTIFICATE: "false" CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__diagnostics-export.yml b/.github/workflows/__diagnostics-export.yml index c55f3de9b8..58923dac79 100644 --- a/.github/workflows/__diagnostics-export.yml +++ b/.github/workflows/__diagnostics-export.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,9 +34,9 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Diagnostic export if: github.triggering_actor != 'dependabot[bot]' @@ -48,13 +48,22 @@ jobs: steps: - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 20.x + cache: npm + - name: Install newer npm + run: npm install -g npm@11.19.1 + - name: Install dependencies + run: npm ci - name: Prepare test id: prepare-test uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init id: init with: @@ -73,64 +82,21 @@ jobs: --ready-for-status-page - uses: ./../action/analyze with: - output: '${{ runner.temp }}/results' + output: "${{ runner.temp }}/results" upload-database: false - name: Upload SARIF - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: diagnostics-export-${{ matrix.os }}-${{ matrix.version }}.sarif.json - path: '${{ runner.temp }}/results/javascript.sarif' + path: "${{ runner.temp }}/results/javascript.sarif" retention-days: 7 + - name: Check diagnostics appear in SARIF - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: - SARIF_PATH: '${{ runner.temp }}/results/javascript.sarif' - with: - script: | - const fs = require('fs'); - - function checkStatusPageNotification(n) { - const expectedMessage = 'Plaintext message'; - if (n.message.text !== expectedMessage) { - core.setFailed(`Expected the status page diagnostic to have the message '${expectedMessage}', but found '${n.message.text}'.`); - } - if (n.locations.length !== 1) { - core.setFailed(`Expected the status page diagnostic to have exactly 1 location, but found ${n.locations.length}.`); - } - } - - const sarif = JSON.parse(fs.readFileSync(process.env['SARIF_PATH'], 'utf8')); - const run = sarif.runs[0]; - - const toolExecutionNotifications = run.invocations[0].toolExecutionNotifications; - const statusPageNotifications = toolExecutionNotifications.filter(n => - n.descriptor.id === 'lang/diagnostics/example' && n.properties?.visibility?.statusPage - ); - if (statusPageNotifications.length !== 1) { - core.setFailed( - 'Expected exactly one status page reporting descriptor for this diagnostic in the ' + - `'runs[].invocations[].toolExecutionNotifications[]' SARIF property, but found ` + - `${statusPageNotifications.length}. All notification reporting descriptors: ` + - `${JSON.stringify(toolExecutionNotifications)}.` - ); - } - checkStatusPageNotification(statusPageNotifications[0]); - - const notifications = run.tool.driver.notifications; - const diagnosticNotification = notifications.filter(n => - n.id === 'lang/diagnostics/example' && n.name === 'lang/diagnostics/example' && - n.fullDescription.text === 'Diagnostic name' - ); - if (diagnosticNotification.length !== 1) { - core.setFailed( - 'Expected exactly one notification for this diagnostic in the ' + - `'runs[].tool.driver.notifications[]' SARIF property, but found ` + - `${diagnosticNotification.length}. All notifications: ` + - `${JSON.stringify(notifications)}.` - ); - } - - core.info('Finished diagnostic export test'); + SARIF_PATH: "${{ runner.temp }}/results/javascript.sarif" + run: | + cd ../action + npx tsx ./pr-checks/check-diagnostics.ts env: CODEQL_ACTION_EXPORT_DIAGNOSTICS: true CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__diagnostics-without-db.yml b/.github/workflows/__diagnostics-without-db.yml new file mode 100644 index 0000000000..5fbd580ccd --- /dev/null +++ b/.github/workflows/__diagnostics-without-db.yml @@ -0,0 +1,143 @@ +# Warning: This file is generated automatically, and should not be modified. +# Instead, please modify the template in the pr-checks directory and run: +# pr-checks/sync.sh +# to regenerate this file. + +name: PR Check - Diagnostic export without database +env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GO111MODULE: auto +on: + push: + branches: + - main + - releases/v* + pull_request: {} + merge_group: + types: + - checks_requested + schedule: + - cron: "0 5 * * *" + workflow_dispatch: + inputs: {} + workflow_call: + inputs: {} +defaults: + run: + shell: bash +concurrency: + cancel-in-progress: ${{ github.event_name == 'pull_request' || false }} + group: diagnostics-without-db-${{github.ref}} +jobs: + diagnostics-without-db: + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-26.04 + version: linked + name: Diagnostic export without database + if: github.triggering_actor != 'dependabot[bot]' + permissions: + contents: read + security-events: read + timeout-minutes: 45 + runs-on: ${{ matrix.os }} + steps: + # We deliberately need to make this step fail before the database is initialised, but after + # some diagnostic has been produced. The simplest way to do that right now is to: + # + # - Produce a diagnostic before the db is initialised by forcing the use of a nightly release + # with the `CODEQL_ACTION_FORCE_NIGHTLY` feature flag. + # - Cause `init` to abort because we are attempting to analyse Swift on a non-macOS runner. + # + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 20.x + cache: npm + - name: Install newer npm + run: npm install -g npm@11.19.1 + - name: Install dependencies + run: npm ci + - name: Prepare test + id: prepare-test + uses: ./.github/actions/prepare-test + with: + version: ${{ matrix.version }} + use-all-platform-bundle: "false" + setup-kotlin: "true" + - name: Initialise failing analysis + id: init + uses: ./../action/init + continue-on-error: true + env: + CODEQL_ACTION_FORCE_NIGHTLY: true + with: + languages: swift + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Analyze + uses: ./analyze + # In a real workflow, this step wouldn't run. Since we used `continue-on-error` + # above, we manually disable it with an `if` condition. Having this step is required + # for the init post-action because it checks the workflow definition for e.g. the + # `category` input. Without this step, that part of the init post-action would fail. + if: false + with: + category: "/test-codeql-version:${{ matrix.version }}" + + - name: Check diagnostics appear on disk + env: + DIAGNOSTICS_DIR: "${{ runner.temp }}/codeql-action-temp-diagnostics/" + run: | + cd ../action + npx tsx ./pr-checks/diagnostics-without-db.ts + env: + CODEQL_ACTION_SKIP_GENERATE_FAILED_SARIF: false + CODEQL_ACTION_SKIP_SARIF_UPLOAD: true + CODEQL_ACTION_TESTING_ENVIRONMENT: codeql-action-pr-checks + CODEQL_ACTION_TEST_MODE: true + diagnostics-without-db-validation: + if: github.triggering_actor != 'dependabot[bot]' + needs: + - diagnostics-without-db + permissions: + contents: read + security-events: read + timeout-minutes: 5 + runs-on: ubuntu-26.04 + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 20.x + cache: npm + - name: Install newer npm + run: npm install -g npm@11.19.1 + - name: Install dependencies + run: npm ci + - name: Download workflow artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: test-mode-sarif-* + path: sarif + + - name: List artifact contents + run: ls -laR ./sarif + + - name: Check diagnostics appear in SARIF + env: + SARIF_PATH: "./sarif/codeql-failed-run.sarif" + DIAGNOSTIC_ID: "codeql-action/forced-nightly-cli" + DIAGNOSTIC_NAME: "A nightly release of CodeQL was used" + EXPECTED_LOCATIONS: "0" + EXPECTED_MESSAGE: | + GitHub configured this analysis to use a nightly release of CodeQL to allow you to preview changes from an upcoming release. + run: npx tsx ./pr-checks/check-diagnostics.ts + env: + CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__export-file-baseline-information.yml b/.github/workflows/__export-file-baseline-information.yml index 4ce8b40285..b4e9138fe5 100644 --- a/.github/workflows/__export-file-baseline-information.yml +++ b/.github/workflows/__export-file-baseline-information.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,11 +54,11 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - - os: macos-latest + - os: macos-26 version: nightly-latest - - os: windows-latest + - os: windows-2025 version: nightly-latest name: Export file baseline information if: github.triggering_actor != 'dependabot[bot]' @@ -84,23 +84,28 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init id: init with: languages: javascript tools: ${{ steps.prepare-test.outputs.tools-url }} + # To balance speed and coverage, analyze only JavaScript but use the combined bundle so + # baseline information is reported for every language in the multi-language repository. A + # custom configuration prevents per-language bundles from being used. + config: | + paths-ignore: [] - name: Build code run: ./build.sh - uses: ./../action/analyze with: - output: '${{ runner.temp }}/results' + output: "${{ runner.temp }}/results" - name: Upload SARIF - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: with-baseline-information-${{ matrix.os }}-${{ matrix.version }}.sarif.json - path: '${{ runner.temp }}/results/javascript.sarif' + path: "${{ runner.temp }}/results/javascript.sarif" retention-days: 7 - name: Check results run: | diff --git a/.github/workflows/__extractor-ram-threads.yml b/.github/workflows/__extractor-ram-threads.yml index 5bd5c8b940..bf9343d8d2 100644 --- a/.github/workflows/__extractor-ram-threads.yml +++ b/.github/workflows/__extractor-ram-threads.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,7 +34,7 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked name: Extractor ram and threads options test if: github.triggering_actor != 'dependabot[bot]' @@ -51,8 +51,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: java diff --git a/.github/workflows/__global-proxy.yml b/.github/workflows/__global-proxy.yml index 9244d1fc8f..c2f9f85141 100644 --- a/.github/workflows/__global-proxy.yml +++ b/.github/workflows/__global-proxy.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,9 +34,9 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Proxy test if: github.triggering_actor != 'dependabot[bot]' @@ -53,8 +53,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'false' + use-all-platform-bundle: "false" + setup-kotlin: "false" - name: Block direct internet access to force proxy usage run: | apt-get update -qq && apt-get install -y -qq iptables >/dev/null 2>&1 diff --git a/.github/workflows/__go-custom-queries.yml b/.github/workflows/__go-custom-queries.yml index 7b4cd1305b..95287af329 100644 --- a/.github/workflows/__go-custom-queries.yml +++ b/.github/workflows/__go-custom-queries.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Go: Custom queries' +name: "PR Check - Go: Custom queries" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,11 +54,11 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - name: 'Go: Custom queries' + name: "Go: Custom queries" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -82,8 +82,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: go @@ -93,5 +93,5 @@ jobs: run: ./build.sh - uses: ./../action/analyze env: - DOTNET_GENERATE_ASPNET_CERTIFICATE: 'false' + DOTNET_GENERATE_ASPNET_CERTIFICATE: "false" CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__go-indirect-tracing-workaround-diagnostic.yml b/.github/workflows/__go-indirect-tracing-workaround-diagnostic.yml index 968caf1e69..bee84bef94 100644 --- a/.github/workflows/__go-indirect-tracing-workaround-diagnostic.yml +++ b/.github/workflows/__go-indirect-tracing-workaround-diagnostic.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Go: diagnostic when Go is changed after init step' +name: "PR Check - Go: diagnostic when Go is changed after init step" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,21 +17,21 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: go-version: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: go-version: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -44,9 +44,9 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - name: 'Go: diagnostic when Go is changed after init step' + name: "Go: diagnostic when Go is changed after init step" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -66,8 +66,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: go @@ -75,17 +75,17 @@ jobs: # Deliberately change Go after the `init` step - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: '1.20' + go-version: "1.20" - name: Build code run: go build main.go - uses: ./../action/analyze with: - output: '${{ runner.temp }}/results' + output: "${{ runner.temp }}/results" upload-database: false - name: Check diagnostic appears in SARIF uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: - SARIF_PATH: '${{ runner.temp }}/results/go.sarif' + SARIF_PATH: "${{ runner.temp }}/results/go.sarif" with: script: | const fs = require('fs'); diff --git a/.github/workflows/__go-indirect-tracing-workaround-no-file-program.yml b/.github/workflows/__go-indirect-tracing-workaround-no-file-program.yml index 0f13b1e663..3b535ecb46 100644 --- a/.github/workflows/__go-indirect-tracing-workaround-no-file-program.yml +++ b/.github/workflows/__go-indirect-tracing-workaround-no-file-program.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Go: diagnostic when `file` is not installed' +name: "PR Check - Go: diagnostic when `file` is not installed" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,21 +17,21 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: go-version: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: go-version: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -44,9 +44,9 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - name: 'Go: diagnostic when `file` is not installed' + name: "Go: diagnostic when `file` is not installed" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -66,8 +66,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Remove `file` program run: | echo $(which file) @@ -81,12 +81,12 @@ jobs: run: go build main.go - uses: ./../action/analyze with: - output: '${{ runner.temp }}/results' + output: "${{ runner.temp }}/results" upload-database: false - name: Check diagnostic appears in SARIF uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: - SARIF_PATH: '${{ runner.temp }}/results/go.sarif' + SARIF_PATH: "${{ runner.temp }}/results/go.sarif" with: script: | const fs = require('fs'); diff --git a/.github/workflows/__go-indirect-tracing-workaround.yml b/.github/workflows/__go-indirect-tracing-workaround.yml index 915835c2ab..6a659f8eb0 100644 --- a/.github/workflows/__go-indirect-tracing-workaround.yml +++ b/.github/workflows/__go-indirect-tracing-workaround.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Go: workaround for indirect tracing' +name: "PR Check - Go: workaround for indirect tracing" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,21 +17,21 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: go-version: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: go-version: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -44,9 +44,9 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - name: 'Go: workaround for indirect tracing' + name: "Go: workaround for indirect tracing" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -66,8 +66,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: go diff --git a/.github/workflows/__go-tracing-autobuilder.yml b/.github/workflows/__go-tracing-autobuilder.yml index ccbb1b5a6e..3a12fe90fd 100644 --- a/.github/workflows/__go-tracing-autobuilder.yml +++ b/.github/workflows/__go-tracing-autobuilder.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Go: tracing with autobuilder step' +name: "PR Check - Go: tracing with autobuilder step" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,21 +17,21 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: go-version: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: go-version: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -44,29 +44,29 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest - version: stable-v2.19.4 - - os: ubuntu-latest + - os: ubuntu-24.04 version: stable-v2.20.7 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.21.4 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.22.4 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.23.9 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.24.3 - - os: ubuntu-latest + - os: ubuntu-26.04 + version: stable-v2.25.6 + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: macos-latest + - os: macos-26 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - - os: macos-latest + - os: macos-26 version: nightly-latest - name: 'Go: tracing with autobuilder step' + name: "Go: tracing with autobuilder step" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -86,8 +86,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: go @@ -106,5 +106,5 @@ jobs: exit 1 fi env: - DOTNET_GENERATE_ASPNET_CERTIFICATE: 'false' + DOTNET_GENERATE_ASPNET_CERTIFICATE: "false" CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__go-tracing-custom-build-steps.yml b/.github/workflows/__go-tracing-custom-build-steps.yml index 2acc617cb1..798cb55c39 100644 --- a/.github/workflows/__go-tracing-custom-build-steps.yml +++ b/.github/workflows/__go-tracing-custom-build-steps.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Go: tracing with custom build steps' +name: "PR Check - Go: tracing with custom build steps" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,21 +17,21 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: go-version: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: go-version: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -44,29 +44,29 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest - version: stable-v2.19.4 - - os: ubuntu-latest + - os: ubuntu-24.04 version: stable-v2.20.7 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.21.4 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.22.4 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.23.9 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.24.3 - - os: ubuntu-latest + - os: ubuntu-26.04 + version: stable-v2.25.6 + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: macos-latest + - os: macos-26 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - - os: macos-latest + - os: macos-26 version: nightly-latest - name: 'Go: tracing with custom build steps' + name: "Go: tracing with custom build steps" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -86,8 +86,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: go diff --git a/.github/workflows/__go-tracing-legacy-workflow.yml b/.github/workflows/__go-tracing-legacy-workflow.yml index a43705b703..92ed9dc2fc 100644 --- a/.github/workflows/__go-tracing-legacy-workflow.yml +++ b/.github/workflows/__go-tracing-legacy-workflow.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Go: tracing with legacy workflow' +name: "PR Check - Go: tracing with legacy workflow" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,21 +17,21 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: go-version: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: go-version: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -44,29 +44,29 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest - version: stable-v2.19.4 - - os: ubuntu-latest + - os: ubuntu-24.04 version: stable-v2.20.7 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.21.4 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.22.4 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.23.9 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.24.3 - - os: ubuntu-latest + - os: ubuntu-26.04 + version: stable-v2.25.6 + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: macos-latest + - os: macos-26 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - - os: macos-latest + - os: macos-26 version: nightly-latest - name: 'Go: tracing with legacy workflow' + name: "Go: tracing with legacy workflow" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -86,8 +86,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: go @@ -100,5 +100,5 @@ jobs: exit 1 fi env: - DOTNET_GENERATE_ASPNET_CERTIFICATE: 'false' + DOTNET_GENERATE_ASPNET_CERTIFICATE: "false" CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__go.yml b/.github/workflows/__go.yml index 3688dc6fd8..e16be4009c 100644 --- a/.github/workflows/__go.yml +++ b/.github/workflows/__go.yml @@ -19,10 +19,10 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" jobs: go-custom-queries: - name: 'Go: Custom queries' + name: "Go: Custom queries" permissions: contents: read security-events: read @@ -31,7 +31,7 @@ jobs: dotnet-version: ${{ inputs.dotnet-version }} go-version: ${{ inputs.go-version }} go-indirect-tracing-workaround-diagnostic: - name: 'Go: diagnostic when Go is changed after init step' + name: "Go: diagnostic when Go is changed after init step" permissions: contents: read security-events: read @@ -39,7 +39,7 @@ jobs: with: go-version: ${{ inputs.go-version }} go-indirect-tracing-workaround-no-file-program: - name: 'Go: diagnostic when `file` is not installed' + name: "Go: diagnostic when `file` is not installed" permissions: contents: read security-events: read @@ -47,7 +47,7 @@ jobs: with: go-version: ${{ inputs.go-version }} go-indirect-tracing-workaround: - name: 'Go: workaround for indirect tracing' + name: "Go: workaround for indirect tracing" permissions: contents: read security-events: read @@ -55,7 +55,7 @@ jobs: with: go-version: ${{ inputs.go-version }} go-tracing-autobuilder: - name: 'Go: tracing with autobuilder step' + name: "Go: tracing with autobuilder step" permissions: contents: read security-events: read @@ -63,7 +63,7 @@ jobs: with: go-version: ${{ inputs.go-version }} go-tracing-custom-build-steps: - name: 'Go: tracing with custom build steps' + name: "Go: tracing with custom build steps" permissions: contents: read security-events: read @@ -71,7 +71,7 @@ jobs: with: go-version: ${{ inputs.go-version }} go-tracing-legacy-workflow: - name: 'Go: tracing with legacy workflow' + name: "Go: tracing with legacy workflow" permissions: contents: read security-events: read diff --git a/.github/workflows/__init-with-registries.yml b/.github/workflows/__init-with-registries.yml index 9293dcc196..3a01c3e51d 100644 --- a/.github/workflows/__init-with-registries.yml +++ b/.github/workflows/__init-with-registries.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Packaging: Download using registries' +name: "PR Check - Packaging: Download using registries" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,13 +34,13 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - name: 'Packaging: Download using registries' + name: "Packaging: Download using registries" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -55,12 +55,12 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Init with registries uses: ./../action/init with: - db-location: '${{ runner.temp }}/customDbLocation' + db-location: "${{ runner.temp }}/customDbLocation" tools: ${{ steps.prepare-test.outputs.tools-url }} config-file: ./.github/codeql/codeql-config-registries.yml languages: javascript diff --git a/.github/workflows/__javascript-source-root.yml b/.github/workflows/__javascript-source-root.yml index 1dcbd38a85..703c6ed750 100644 --- a/.github/workflows/__javascript-source-root.yml +++ b/.github/workflows/__javascript-source-root.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,11 +34,11 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Custom source root if: github.triggering_actor != 'dependabot[bot]' @@ -55,8 +55,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Move codeql-action run: | mkdir ../new-source-root diff --git a/.github/workflows/__job-run-uuid-sarif.yml b/.github/workflows/__job-run-uuid-sarif.yml index 429a694947..4a76f8b954 100644 --- a/.github/workflows/__job-run-uuid-sarif.yml +++ b/.github/workflows/__job-run-uuid-sarif.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,7 +34,7 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Job run UUID added to SARIF if: github.triggering_actor != 'dependabot[bot]' @@ -51,8 +51,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init id: init with: @@ -60,12 +60,12 @@ jobs: tools: ${{ steps.prepare-test.outputs.tools-url }} - uses: ./../action/analyze with: - output: '${{ runner.temp }}/results' + output: "${{ runner.temp }}/results" - name: Upload SARIF - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: ${{ matrix.os }}-${{ matrix.version }}.sarif.json - path: '${{ runner.temp }}/results/javascript.sarif' + path: "${{ runner.temp }}/results/javascript.sarif" retention-days: 7 - name: Check results run: | diff --git a/.github/workflows/__language-aliases.yml b/.github/workflows/__language-aliases.yml index 731d975ce3..048441fd3c 100644 --- a/.github/workflows/__language-aliases.yml +++ b/.github/workflows/__language-aliases.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,7 +34,7 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked name: Language aliases if: github.triggering_actor != 'dependabot[bot]' @@ -51,14 +51,14 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: C#,java-kotlin,typescript tools: ${{ steps.prepare-test.outputs.tools-url }} - - name: 'Check languages' + - name: "Check languages" run: | expected_languages="csharp,java,javascript" actual_languages=$(jq -r '.languages | join(",")' "$RUNNER_TEMP"/config) diff --git a/.github/workflows/__linux-arm64.yml b/.github/workflows/__linux-arm64.yml new file mode 100644 index 0000000000..02dab69f9f --- /dev/null +++ b/.github/workflows/__linux-arm64.yml @@ -0,0 +1,106 @@ +# Warning: This file is generated automatically, and should not be modified. +# Instead, please modify the template in the pr-checks directory and run: +# pr-checks/sync.sh +# to regenerate this file. + +name: PR Check - Linux Arm64 +env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GO111MODULE: auto +on: + push: + branches: + - main + - releases/v* + pull_request: {} + merge_group: + types: + - checks_requested + schedule: + - cron: "0 5 * * *" + workflow_dispatch: + inputs: + dotnet-version: + type: string + description: The version of .NET to install + required: false + default: 9.x + go-version: + type: string + description: The version of Go to install + required: false + default: ">=1.21.0" + workflow_call: + inputs: + dotnet-version: + type: string + description: The version of .NET to install + required: false + default: 9.x + go-version: + type: string + description: The version of Go to install + required: false + default: ">=1.21.0" +defaults: + run: + shell: bash +concurrency: + cancel-in-progress: ${{ github.event_name == 'pull_request' || false }} + group: linux-arm64-${{github.ref}}-${{inputs.dotnet-version}}-${{inputs.go-version}} +jobs: + linux-arm64: + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-24.04-arm + version: nightly-latest + name: Linux Arm64 + if: github.triggering_actor != 'dependabot[bot]' + permissions: + contents: read + security-events: read + timeout-minutes: 45 + runs-on: ${{ matrix.os }} + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install .NET + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: ${{ inputs.dotnet-version || '9.x' }} + - name: Install Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version: ${{ inputs.go-version || '>=1.21.0' }} + cache: false + - name: Prepare test + id: prepare-test + uses: ./.github/actions/prepare-test + with: + version: ${{ matrix.version }} + use-all-platform-bundle: "false" + setup-kotlin: "true" + - uses: ./../action/init + with: + languages: ${{ env.LANGUAGES }} + tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Build code + run: ./build.sh + - uses: ./../action/analyze + with: + upload-database: false + - name: Assert databases exist + run: | + cd "$RUNNER_TEMP/codeql_databases" + for lang in ${LANGUAGES//,/ }; do + if [[ ! -d "$lang" ]]; then + echo "Did not find a database for $lang" + exit 1 + fi + echo "Found database for $lang" + done + env: + LANGUAGES: cpp,csharp,go,java,javascript,python,ruby + CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__local-bundle.yml b/.github/workflows/__local-bundle.yml index 8e448080f3..e4b20c9b4a 100644 --- a/.github/workflows/__local-bundle.yml +++ b/.github/workflows/__local-bundle.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,7 +54,7 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked name: Local CodeQL bundle if: github.triggering_actor != 'dependabot[bot]' @@ -80,8 +80,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Fetch latest CodeQL bundle run: | wget https://github.com/github/codeql-action/releases/latest/download/codeql-bundle-linux64.tar.zst diff --git a/.github/workflows/__multi-language-autodetect.yml b/.github/workflows/__multi-language-autodetect.yml index 55023cd916..41588c9453 100644 --- a/.github/workflows/__multi-language-autodetect.yml +++ b/.github/workflows/__multi-language-autodetect.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,41 +54,41 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest - version: stable-v2.19.4 - - os: macos-15-xlarge - version: stable-v2.19.4 - - os: ubuntu-latest + - os: ubuntu-24.04 version: stable-v2.20.7 - os: macos-15-xlarge version: stable-v2.20.7 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.21.4 - os: macos-15-xlarge version: stable-v2.21.4 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.22.4 - os: macos-15-xlarge version: stable-v2.22.4 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.23.9 - - os: macos-latest-xlarge + - os: macos-26-xlarge version: stable-v2.23.9 - - os: ubuntu-latest + - os: ubuntu-26.04 version: stable-v2.24.3 - - os: macos-latest-xlarge + - os: macos-26-xlarge version: stable-v2.24.3 - - os: ubuntu-latest + - os: ubuntu-26.04 + version: stable-v2.25.6 + - os: macos-26-xlarge + version: stable-v2.25.6 + - os: ubuntu-26.04 version: default - - os: macos-latest-xlarge + - os: macos-26-xlarge version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: macos-latest-xlarge + - os: macos-26-xlarge version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - - os: macos-latest-xlarge + - os: macos-26-xlarge version: nightly-latest name: Multi-language repository if: github.triggering_actor != 'dependabot[bot]' @@ -114,15 +114,16 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' - - name: Install Python 3.13 for older CLI versions - # We need Python 3.13 for older CLI versions because they are not compatible with Python 3.14 or newer. + use-all-platform-bundle: "false" + setup-kotlin: "true" + - name: Install Python 3.13.15 for older CLI versions + # Older CLI versions don't work with Python 3.13.16 or newer because their Python extractor + # imports `importlib._bootstrap._ERR_MSG`, which those Python versions no longer define. # See https://github.com/github/codeql-action/pull/3212 if: matrix.version != 'nightly-latest' && matrix.version != 'linked' - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: - python-version: '3.13' + python-version: "3.13.15" - name: Use Xcode 16 # Only the older CodeQL CLI versions need Xcode 16, and these run on macOS 15. @@ -132,7 +133,7 @@ jobs: - uses: ./../action/init id: init with: - db-location: '${{ runner.temp }}/customDbLocation' + db-location: "${{ runner.temp }}/customDbLocation" languages: ${{ runner.os == 'Linux' && 'cpp,csharp,go,java,javascript,python,ruby' || '' }} tools: ${{ steps.prepare-test.outputs.tools-url }} diff --git a/.github/workflows/__overlay-init-fallback.yml b/.github/workflows/__overlay-init-fallback.yml index b6c99efcef..3cdcec3717 100644 --- a/.github/workflows/__overlay-init-fallback.yml +++ b/.github/workflows/__overlay-init-fallback.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,9 +34,9 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Overlay database init fallback if: github.triggering_actor != 'dependabot[bot]' @@ -53,8 +53,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: actions # Any language without overlay support will do diff --git a/.github/workflows/__packaging-codescanning-config-inputs-js.yml b/.github/workflows/__packaging-codescanning-config-inputs-js.yml index 409e0a1a65..3b703bea5e 100644 --- a/.github/workflows/__packaging-codescanning-config-inputs-js.yml +++ b/.github/workflows/__packaging-codescanning-config-inputs-js.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Packaging: Config and input passed to the CLI' +name: "PR Check - Packaging: Config and input passed to the CLI" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,13 +54,13 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - name: 'Packaging: Config and input passed to the CLI' + name: "Packaging: Config and input passed to the CLI" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -80,10 +80,12 @@ jobs: go-version: ${{ inputs.go-version || '>=1.21.0' }} cache: false - name: Install Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 20.x cache: npm + - name: Install newer npm + run: npm install -g npm@11.19.1 - name: Install dependencies run: npm ci - name: Prepare test @@ -91,11 +93,11 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: - config-file: '.github/codeql/codeql-config-packaging3.yml' + config-file: ".github/codeql/codeql-config-packaging3.yml" packs: +codeql-testing/codeql-pack1@1.0.0 languages: javascript tools: ${{ steps.prepare-test.outputs.tools-url }} @@ -103,7 +105,7 @@ jobs: run: ./build.sh - uses: ./../action/analyze with: - output: '${{ runner.temp }}/results' + output: "${{ runner.temp }}/results" upload-database: false - name: Check results diff --git a/.github/workflows/__packaging-config-inputs-js.yml b/.github/workflows/__packaging-config-inputs-js.yml index 34d4ae1bca..6a346631ef 100644 --- a/.github/workflows/__packaging-config-inputs-js.yml +++ b/.github/workflows/__packaging-config-inputs-js.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Packaging: Config and input' +name: "PR Check - Packaging: Config and input" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,13 +54,13 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - name: 'Packaging: Config and input' + name: "Packaging: Config and input" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -80,10 +80,12 @@ jobs: go-version: ${{ inputs.go-version || '>=1.21.0' }} cache: false - name: Install Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 20.x cache: npm + - name: Install newer npm + run: npm install -g npm@11.19.1 - name: Install dependencies run: npm ci - name: Prepare test @@ -91,11 +93,11 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: - config-file: '.github/codeql/codeql-config-packaging3.yml' + config-file: ".github/codeql/codeql-config-packaging3.yml" packs: +codeql-testing/codeql-pack1@1.0.0 languages: javascript tools: ${{ steps.prepare-test.outputs.tools-url }} @@ -103,7 +105,7 @@ jobs: run: ./build.sh - uses: ./../action/analyze with: - output: '${{ runner.temp }}/results' + output: "${{ runner.temp }}/results" upload-database: false - name: Check results diff --git a/.github/workflows/__packaging-config-js.yml b/.github/workflows/__packaging-config-js.yml index 88426cd684..75f426c346 100644 --- a/.github/workflows/__packaging-config-js.yml +++ b/.github/workflows/__packaging-config-js.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Packaging: Config file' +name: "PR Check - Packaging: Config file" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,13 +54,13 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - name: 'Packaging: Config file' + name: "Packaging: Config file" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -80,10 +80,12 @@ jobs: go-version: ${{ inputs.go-version || '>=1.21.0' }} cache: false - name: Install Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 20.x cache: npm + - name: Install newer npm + run: npm install -g npm@11.19.1 - name: Install dependencies run: npm ci - name: Prepare test @@ -91,18 +93,18 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: - config-file: '.github/codeql/codeql-config-packaging.yml' + config-file: ".github/codeql/codeql-config-packaging.yml" languages: javascript tools: ${{ steps.prepare-test.outputs.tools-url }} - name: Build code run: ./build.sh - uses: ./../action/analyze with: - output: '${{ runner.temp }}/results' + output: "${{ runner.temp }}/results" upload-database: false - name: Check results diff --git a/.github/workflows/__packaging-inputs-js.yml b/.github/workflows/__packaging-inputs-js.yml index 2461944dbd..be72e2556e 100644 --- a/.github/workflows/__packaging-inputs-js.yml +++ b/.github/workflows/__packaging-inputs-js.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: 'PR Check - Packaging: Action input' +name: "PR Check - Packaging: Action input" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,13 +54,13 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - name: 'Packaging: Action input' + name: "Packaging: Action input" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -80,10 +80,12 @@ jobs: go-version: ${{ inputs.go-version || '>=1.21.0' }} cache: false - name: Install Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 20.x cache: npm + - name: Install newer npm + run: npm install -g npm@11.19.1 - name: Install dependencies run: npm ci - name: Prepare test @@ -91,11 +93,11 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: - config-file: '.github/codeql/codeql-config-packaging2.yml' + config-file: ".github/codeql/codeql-config-packaging2.yml" languages: javascript packs: codeql-testing/codeql-pack1@1.0.0, codeql-testing/codeql-pack2, codeql-testing/codeql-pack3:other-query.ql tools: ${{ steps.prepare-test.outputs.tools-url }} @@ -103,7 +105,7 @@ jobs: run: ./build.sh - uses: ./../action/analyze with: - output: '${{ runner.temp }}/results' + output: "${{ runner.temp }}/results" - name: Check results uses: ./../action/.github/actions/check-sarif diff --git a/.github/workflows/__per-language-bundle-validation.yml b/.github/workflows/__per-language-bundle-validation.yml new file mode 100644 index 0000000000..3313ac010a --- /dev/null +++ b/.github/workflows/__per-language-bundle-validation.yml @@ -0,0 +1,175 @@ +# Warning: This file is generated automatically, and should not be modified. +# Instead, please modify the template in the pr-checks directory and run: +# pr-checks/sync.sh +# to regenerate this file. + +name: PR Check - Per-language bundles +env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GO111MODULE: auto +on: + push: + branches: + - main + - releases/v* + pull_request: {} + merge_group: + types: + - checks_requested + schedule: + - cron: "0 5 * * *" + workflow_dispatch: + inputs: {} + workflow_call: + inputs: {} +defaults: + run: + shell: bash +concurrency: + cancel-in-progress: ${{ github.event_name == 'pull_request' || false }} + group: per-language-bundle-validation-${{github.ref}} +jobs: + per-language-bundle-validation: + strategy: + fail-fast: false + matrix: + include: + - language: actions + os: ubuntu-26.04 + version: linked + expected-extractors: actions javascript + - language: cpp + os: ubuntu-26.04 + version: linked + build-mode: manual + build-command: gcc -o main main.c + - language: csharp + os: ubuntu-26.04 + version: linked + build-mode: none + - language: go + os: ubuntu-26.04 + version: linked + build-mode: autobuild + - language: java + os: ubuntu-26.04 + version: linked + build-mode: none + - language: javascript + os: ubuntu-26.04 + version: linked + - language: python + os: ubuntu-26.04 + version: linked + - language: ruby + os: ubuntu-26.04 + version: linked + - language: rust + os: ubuntu-26.04 + version: linked + - language: swift + os: macos-26-xlarge + version: linked + build-mode: autobuild + name: Per-language bundles + if: github.triggering_actor != 'dependabot[bot]' + permissions: + contents: read + security-events: read + timeout-minutes: 45 + runs-on: ${{ matrix.os }} + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 20.x + cache: npm + - name: Install newer npm + run: npm install -g npm@11.19.1 + - name: Install dependencies + run: npm ci + - name: Prepare test + id: prepare-test + uses: ./.github/actions/prepare-test + with: + version: ${{ matrix.version }} + use-all-platform-bundle: "false" + setup-kotlin: "true" + - name: Remove CodeQL from toolcache + run: | + cd ./../action + npx tsx ./pr-checks/toolcache.ts clear + - uses: ./../action/init + id: init + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix['build-mode'] }} + tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Check that the bundle contains only the expected extractors + env: + CODEQL_PATH: ${{ steps.init.outputs.codeql-path }} + LANGUAGE: ${{ matrix.language }} + EXPECTED_EXTRACTORS: ${{ matrix['expected-extractors'] || matrix.language }} + run: | + extractors="$("$CODEQL_PATH" resolve languages --format=json | jq -r 'keys[]')" + echo "Extractors in the bundle:" + echo "$extractors" + echo "Expected: $EXPECTED_EXTRACTORS" + + for expected in $EXPECTED_EXTRACTORS; do + if ! echo "$extractors" | grep -qx "$expected"; then + echo "::error::The ${LANGUAGE} bundle does not contain the ${expected} extractor." + exit 1 + fi + done + + # If the bundle contained extractors beyond those the language needs, then it would not + # have been trimmed, and this job would be silently validating the combined bundle. + for other in actions cpp csharp go java javascript python ruby rust swift; do + if echo "$EXPECTED_EXTRACTORS" | grep -qw "$other"; then + continue + fi + if echo "$extractors" | grep -qx "$other"; then + echo "::error::The ${LANGUAGE} bundle also contains the ${other} extractor, so it is not trimmed." + exit 1 + fi + done + - name: Check that the bundle was not added to the toolcache + env: + CODEQL_PATH: ${{ steps.init.outputs.codeql-path }} + run: | + # A bundle that is missing most of its extractors must never be left in the toolcache, + # where a later job analyzing a different language could pick it up. Per-language bundles + # must instead be extracted under the runner's temporary directory. + echo "CodeQL is at $CODEQL_PATH" + if [[ "$CODEQL_PATH" == "$RUNNER_TOOL_CACHE"/* ]]; then + echo "::error::The per-language bundle was added to the toolcache at $CODEQL_PATH." + exit 1 + fi + if [[ "$CODEQL_PATH" != "$RUNNER_TEMP"/* ]]; then + echo "::error::Expected the per-language bundle to be extracted under $RUNNER_TEMP, but found it at $CODEQL_PATH." + exit 1 + fi + - name: Build code + if: matrix['build-command'] + run: ${{ matrix['build-command'] }} + - uses: ./../action/analyze + id: analysis + with: + upload-database: false + - name: Check that a database was created for the language + env: + DB_LOCATIONS: ${{ steps.analysis.outputs.db-locations }} + LANGUAGE: ${{ matrix.language }} + run: | + database="$(echo "$DB_LOCATIONS" | jq -r --arg lang "$LANGUAGE" '.[$lang] // empty')" + if [ -z "$database" ] || [ ! -d "$database" ]; then + echo "::error::No CodeQL database was created for ${LANGUAGE}." + echo "Databases: $DB_LOCATIONS" + exit 1 + fi + echo "Created a ${LANGUAGE} database at ${database}." + env: + CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__remote-config.yml b/.github/workflows/__remote-config.yml index e1c3785f6a..1f8b1f1271 100644 --- a/.github/workflows/__remote-config.yml +++ b/.github/workflows/__remote-config.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,9 +54,9 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Remote config file if: github.triggering_actor != 'dependabot[bot]' @@ -82,8 +82,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: tools: ${{ steps.prepare-test.outputs.tools-url }} diff --git a/.github/workflows/__resolve-environment-action.yml b/.github/workflows/__resolve-environment-action.yml index 11a31fdabc..2d0ebd6fb0 100644 --- a/.github/workflows/__resolve-environment-action.yml +++ b/.github/workflows/__resolve-environment-action.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,11 +34,11 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Resolve environment if: github.triggering_actor != 'dependabot[bot]' @@ -55,8 +55,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: go,javascript-typescript diff --git a/.github/workflows/__rubocop-multi-language.yml b/.github/workflows/__rubocop-multi-language.yml deleted file mode 100644 index c405b44fed..0000000000 --- a/.github/workflows/__rubocop-multi-language.yml +++ /dev/null @@ -1,74 +0,0 @@ -# Warning: This file is generated automatically, and should not be modified. -# Instead, please modify the template in the pr-checks directory and run: -# pr-checks/sync.sh -# to regenerate this file. - -name: PR Check - RuboCop multi-language -env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GO111MODULE: auto -on: - push: - branches: - - main - - releases/v* - pull_request: {} - merge_group: - types: - - checks_requested - schedule: - - cron: '0 5 * * *' - workflow_dispatch: - inputs: {} - workflow_call: - inputs: {} -defaults: - run: - shell: bash -concurrency: - cancel-in-progress: ${{ github.event_name == 'pull_request' || false }} - group: rubocop-multi-language-${{github.ref}} -jobs: - rubocop-multi-language: - strategy: - fail-fast: false - matrix: - include: - - os: ubuntu-latest - version: default - name: RuboCop multi-language - if: github.triggering_actor != 'dependabot[bot]' - permissions: - contents: read - security-events: read - timeout-minutes: 45 - runs-on: ${{ matrix.os }} - steps: - - name: Check out repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Prepare test - id: prepare-test - uses: ./.github/actions/prepare-test - with: - version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' - - name: Set up Ruby - uses: ruby/setup-ruby@95ef2b042f9d7a56d8268cba8559e2842e2ad01b # v1.321.0 - with: - ruby-version: 2.6 - - name: Install Code Scanning integration - run: bundle add code-scanning-rubocop --version 0.3.0 --skip-install - - name: Install dependencies - run: bundle install - - name: RuboCop run - run: | - bash -c " - bundle exec rubocop --require code_scanning --format CodeScanning::SarifFormatter -o rubocop.sarif - [[ $? -ne 2 ]] - " - - uses: ./../action/upload-sarif - with: - sarif_file: rubocop.sarif - env: - CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__ruby.yml b/.github/workflows/__ruby.yml index 98f8ec6a2a..8ce015624c 100644 --- a/.github/workflows/__ruby.yml +++ b/.github/workflows/__ruby.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,17 +34,17 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: macos-latest + - os: macos-26 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - - os: macos-latest + - os: macos-26 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - - os: macos-latest + - os: macos-26 version: nightly-latest name: Ruby analysis if: github.triggering_actor != 'dependabot[bot]' @@ -61,8 +61,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: ruby diff --git a/.github/workflows/__rust.yml b/.github/workflows/__rust.yml index b3638ca6df..0e08f9919d 100644 --- a/.github/workflows/__rust.yml +++ b/.github/workflows/__rust.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,15 +34,15 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest - version: stable-v2.19.4 - - os: ubuntu-latest + - os: ubuntu-24.04 + version: stable-v2.20.7 + - os: ubuntu-26.04 version: stable-v2.22.1 - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Rust analysis if: github.triggering_actor != 'dependabot[bot]' @@ -59,8 +59,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: languages: rust diff --git a/.github/workflows/__split-workflow.yml b/.github/workflows/__split-workflow.yml index 512058a598..b80d368192 100644 --- a/.github/workflows/__split-workflow.yml +++ b/.github/workflows/__split-workflow.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,17 +54,17 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: macos-latest + - os: macos-26 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - - os: macos-latest + - os: macos-26 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest - - os: macos-latest + - os: macos-26 version: nightly-latest name: Split workflow if: github.triggering_actor != 'dependabot[bot]' @@ -90,11 +90,11 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: - config-file: '.github/codeql/codeql-config-packaging3.yml' + config-file: ".github/codeql/codeql-config-packaging3.yml" packs: +codeql-testing/codeql-pack1@1.0.0 languages: javascript tools: ${{ steps.prepare-test.outputs.tools-url }} @@ -103,7 +103,7 @@ jobs: - uses: ./../action/analyze with: skip-queries: true - output: '${{ runner.temp }}/results' + output: "${{ runner.temp }}/results" upload-database: false - name: Assert No Results @@ -114,7 +114,7 @@ jobs: fi - uses: ./../action/analyze with: - output: '${{ runner.temp }}/results' + output: "${{ runner.temp }}/results" upload-database: false - name: Assert Results run: | diff --git a/.github/workflows/__start-proxy.yml b/.github/workflows/__start-proxy.yml index edc6aa1cc5..a636a1bf59 100644 --- a/.github/workflows/__start-proxy.yml +++ b/.github/workflows/__start-proxy.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,11 +34,11 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: macos-latest + - os: macos-26 version: linked - - os: windows-latest + - os: windows-2025 version: linked name: Start proxy if: github.triggering_actor != 'dependabot[bot]' @@ -55,8 +55,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Setup proxy for registries id: proxy uses: ./../action/start-proxy @@ -101,5 +101,5 @@ jobs: tools: ${{ steps.prepare-test.outputs.tools-url }} config-file: codeql-action@main:tests/multi-language-repo/.github/codeql/custom-queries.yml env: - CODEQL_ACTION_PROXY_API_REQUESTS: 'true' + CODEQL_ACTION_PROXY_API_REQUESTS: "true" CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__submit-sarif-failure.yml b/.github/workflows/__submit-sarif-failure.yml index 099e93001f..8eb219c9be 100644 --- a/.github/workflows/__submit-sarif-failure.yml +++ b/.github/workflows/__submit-sarif-failure.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,11 +34,11 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: default - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Submit SARIF after failure if: github.triggering_actor != 'dependabot[bot]' @@ -55,8 +55,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: ./init with: @@ -71,10 +71,12 @@ jobs: run: exit 1 - uses: ./analyze # In a real workflow, this step wouldn't run. Since we used `continue-on-error` - # above, we manually disable it with an `if` condition. + # above, we manually disable it with an `if` condition. Having this step is required + # for the init post-action because it checks the workflow definition for e.g. the + # `category` input. Without this step, that part of the init post-action would fail. if: false with: - category: '/test-codeql-version:${{ matrix.version }}' + category: "/test-codeql-version:${{ matrix.version }}" env: CODEQL_ACTION_EXPECT_UPLOAD_FAILED_SARIF: true CODEQL_ACTION_UPLOAD_FAILED_SARIF: true diff --git a/.github/workflows/__swift-autobuild.yml b/.github/workflows/__swift-autobuild.yml index 52c189f3a8..cc67bfdb63 100644 --- a/.github/workflows/__swift-autobuild.yml +++ b/.github/workflows/__swift-autobuild.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: {} workflow_call: @@ -34,7 +34,7 @@ jobs: fail-fast: false matrix: include: - - os: macos-latest-xlarge + - os: macos-26-xlarge version: nightly-latest name: Swift analysis using autobuild if: github.triggering_actor != 'dependabot[bot]' @@ -51,8 +51,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init id: init with: diff --git a/.github/workflows/__swift-custom-build.yml b/.github/workflows/__swift-custom-build.yml index 99fbf7a897..1d1a8d9f17 100644 --- a/.github/workflows/__swift-custom-build.yml +++ b/.github/workflows/__swift-custom-build.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,11 +54,11 @@ jobs: fail-fast: false matrix: include: - - os: macos-latest + - os: macos-26-xlarge version: linked - - os: macos-latest + - os: macos-26-xlarge version: default - - os: macos-latest + - os: macos-26-xlarge version: nightly-latest name: Swift analysis using a custom build command if: github.triggering_actor != 'dependabot[bot]' @@ -84,8 +84,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init id: init with: @@ -107,5 +107,5 @@ jobs: exit 1 fi env: - DOTNET_GENERATE_ASPNET_CERTIFICATE: 'false' + DOTNET_GENERATE_ASPNET_CERTIFICATE: "false" CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__unset-environment.yml b/.github/workflows/__unset-environment.yml index 8a8796d9a7..77896566e5 100644 --- a/.github/workflows/__unset-environment.yml +++ b/.github/workflows/__unset-environment.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,9 +54,9 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked - - os: ubuntu-latest + - os: ubuntu-26.04 version: nightly-latest name: Test unsetting environment variables if: github.triggering_actor != 'dependabot[bot]' @@ -82,8 +82,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init id: init with: diff --git a/.github/workflows/__unsupported-macos.yml b/.github/workflows/__unsupported-macos.yml new file mode 100644 index 0000000000..f98bf6959e --- /dev/null +++ b/.github/workflows/__unsupported-macos.yml @@ -0,0 +1,135 @@ +# Warning: This file is generated automatically, and should not be modified. +# Instead, please modify the template in the pr-checks directory and run: +# pr-checks/sync.sh +# to regenerate this file. + +name: PR Check - Unsupported macOS +env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GO111MODULE: auto +on: + push: + branches: + - main + - releases/v* + pull_request: {} + merge_group: + types: + - checks_requested + schedule: + - cron: "0 5 * * *" + workflow_dispatch: + inputs: {} + workflow_call: + inputs: {} +defaults: + run: + shell: bash +concurrency: + cancel-in-progress: ${{ github.event_name == 'pull_request' || false }} + group: unsupported-macos-${{github.ref}} +jobs: + unsupported-macos: + strategy: + fail-fast: false + matrix: + include: + - os: xcode-27 + version: linked + - os: xcode-27 + version: nightly-latest + name: Unsupported macOS + if: github.triggering_actor != 'dependabot[bot]' + permissions: + contents: read + security-events: read + timeout-minutes: 45 + runs-on: ${{ matrix.os }} + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 20.x + cache: npm + - name: Install newer npm + run: npm install -g npm@11.19.1 + - name: Install dependencies + run: npm ci + - name: Prepare test + id: prepare-test + uses: ./.github/actions/prepare-test + with: + version: ${{ matrix.version }} + use-all-platform-bundle: "false" + setup-kotlin: "true" + - name: Check xcode_select_link + run: | + readlink /private/var/db/xcode_select_link + file -h /private/var/db/xcode_select_link + + - uses: ./../action/init + id: init + continue-on-error: true + env: + CODEQL_ACTION_CHECK_UNSUPPORTED_TRACED_ANALYSIS: true + CODEQL_ACTION_ABORT_UNSUPPORTED_TRACED_ANALYSIS: true + with: + languages: swift + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Analyze + # We could run `analyze` here from `./../analyze`, but `getAnalyzeActionName` in `workflow.ts` + # can't cope with that unless we introduce a different testing environment. Since this step + # would just fail on `xcode-27` anyway, we just skip it instead. + if: false + uses: ./analyze + with: + category: "/test-codeql-version:${{ matrix.version }}" + env: + CODEQL_ACTION_SKIP_GENERATE_FAILED_SARIF: false + CODEQL_ACTION_SKIP_SARIF_UPLOAD: true + CODEQL_ACTION_TESTING_ENVIRONMENT: codeql-action-pr-checks + CODEQL_ACTION_TEST_MODE: true + unsupported-macos-sarif-checks: + if: github.triggering_actor != 'dependabot[bot]' + needs: + - unsupported-macos + permissions: + contents: read + security-events: read + timeout-minutes: 5 + runs-on: ubuntu-26.04 + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 20.x + cache: npm + - name: Install newer npm + run: npm install -g npm@11.19.1 + - name: Install dependencies + run: npm ci + - name: Download workflow artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: test-mode-sarif-* + path: sarif + + - name: List artifact contents + run: ls -laR ./sarif + + - name: Check diagnostics appear in SARIF + env: + SARIF_PATH: "./sarif/" + DIAGNOSTIC_ID: "codeql-action/unsupported-traced-analysis-macos" + DIAGNOSTIC_NAME: "Traced analysis is not supported on this version of macOS" + EXPECTED_LOCATIONS: "0" + EXPECTED_MESSAGE: | + Traced analysis is not supported on macOS 27 or above. + run: npx tsx ./pr-checks/check-diagnostics.ts + env: + CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__upload-ref-sha-input.yml b/.github/workflows/__upload-ref-sha-input.yml index 76e8f4e3c0..f0f38c32e4 100644 --- a/.github/workflows/__upload-ref-sha-input.yml +++ b/.github/workflows/__upload-ref-sha-input.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,7 +54,7 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: default name: "Upload-sarif: 'ref' and 'sha' from inputs" if: github.triggering_actor != 'dependabot[bot]' @@ -80,8 +80,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: tools: ${{ steps.prepare-test.outputs.tools-url }} @@ -92,12 +92,12 @@ jobs: # Generate some SARIF we can upload with the upload-sarif step - uses: ./../action/analyze with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" upload: never - uses: ./../action/upload-sarif with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" env: CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/__upload-sarif.yml b/.github/workflows/__upload-sarif.yml index 77fa0264e5..a1f53bbbe6 100644 --- a/.github/workflows/__upload-sarif.yml +++ b/.github/workflows/__upload-sarif.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,13 +54,13 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: default analysis-kinds: code-scanning - - os: ubuntu-latest + - os: ubuntu-26.04 version: default analysis-kinds: code-quality - - os: ubuntu-latest + - os: ubuntu-26.04 version: default analysis-kinds: code-scanning,code-quality name: Test different uses of `upload-sarif` @@ -87,8 +87,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - uses: ./../action/init with: tools: ${{ steps.prepare-test.outputs.tools-url }} @@ -99,8 +99,8 @@ jobs: # Generate some SARIF we can upload with the upload-sarif step - uses: ./../action/analyze with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" upload: never output: ${{ runner.temp }}/results @@ -109,15 +109,15 @@ jobs: uses: ./../action/upload-sarif id: upload-sarif with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" sarif_file: ${{ runner.temp }}/results category: | ${{ github.workflow }}:upload-sarif/analysis-kinds:${{ matrix.analysis-kinds }}/os:${{ matrix.os }}/version:${{ matrix.version }}/test:all-files/ - - name: 'Fail for missing output from `upload-sarif` step for `code-scanning`' + - name: "Fail for missing output from `upload-sarif` step for `code-scanning`" if: contains(matrix.analysis-kinds, 'code-scanning') && !(fromJSON(steps.upload-sarif.outputs.sarif-ids).code-scanning) run: exit 1 - - name: 'Fail for missing output from `upload-sarif` step for `code-quality`' + - name: "Fail for missing output from `upload-sarif` step for `code-quality`" if: contains(matrix.analysis-kinds, 'code-quality') && !(fromJSON(steps.upload-sarif.outputs.sarif-ids).code-quality) run: exit 1 @@ -126,12 +126,12 @@ jobs: id: upload-single-sarif-code-scanning if: contains(matrix.analysis-kinds, 'code-scanning') with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" sarif_file: ${{ runner.temp }}/results/javascript.sarif category: | ${{ github.workflow }}:upload-sarif/analysis-kinds:${{ matrix.analysis-kinds }}/os:${{ matrix.os }}/version:${{ matrix.version }}/test:single-code-scanning/ - - name: 'Fail for missing output from `upload-single-sarif-code-scanning` step' + - name: "Fail for missing output from `upload-single-sarif-code-scanning` step" if: contains(matrix.analysis-kinds, 'code-scanning') && !(fromJSON(steps.upload-single-sarif-code-scanning.outputs.sarif-ids).code-scanning) run: exit 1 - name: Upload single SARIF file for Code Quality @@ -139,12 +139,12 @@ jobs: id: upload-single-sarif-code-quality if: contains(matrix.analysis-kinds, 'code-quality') with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" sarif_file: ${{ runner.temp }}/results/javascript.quality.sarif category: | ${{ github.workflow }}:upload-sarif/analysis-kinds:${{ matrix.analysis-kinds }}/os:${{ matrix.os }}/version:${{ matrix.version }}/test:single-code-quality/ - - name: 'Fail for missing output from `upload-single-sarif-code-quality` step' + - name: "Fail for missing output from `upload-single-sarif-code-quality` step" if: contains(matrix.analysis-kinds, 'code-quality') && !(fromJSON(steps.upload-single-sarif-code-quality.outputs.sarif-ids).code-quality) run: exit 1 @@ -156,12 +156,12 @@ jobs: id: upload-single-non-sarif if: contains(matrix.analysis-kinds, 'code-scanning') with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" sarif_file: ${{ runner.temp }}/results/javascript.sarif.json category: | ${{ github.workflow }}:upload-sarif/analysis-kinds:${{ matrix.analysis-kinds }}/os:${{ matrix.os }}/version:${{ matrix.version }}/test:non-sarif/ - - name: 'Fail for missing output from `upload-single-non-sarif` step' + - name: "Fail for missing output from `upload-single-non-sarif` step" if: contains(matrix.analysis-kinds, 'code-scanning') && !(fromJSON(steps.upload-single-non-sarif.outputs.sarif-ids).code-scanning) run: exit 1 env: diff --git a/.github/workflows/__with-checkout-path.yml b/.github/workflows/__with-checkout-path.yml index 59a8edc9d1..cef72ae57c 100644 --- a/.github/workflows/__with-checkout-path.yml +++ b/.github/workflows/__with-checkout-path.yml @@ -17,7 +17,7 @@ on: types: - checks_requested schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: inputs: dotnet-version: @@ -29,7 +29,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" workflow_call: inputs: dotnet-version: @@ -41,7 +41,7 @@ on: type: string description: The version of Go to install required: false - default: '>=1.21.0' + default: ">=1.21.0" defaults: run: shell: bash @@ -54,7 +54,7 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-26.04 version: linked name: Use a custom `checkout_path` if: github.triggering_actor != 'dependabot[bot]' @@ -81,8 +81,8 @@ jobs: uses: ./.github/actions/prepare-test with: version: ${{ matrix.version }} - use-all-platform-bundle: 'false' - setup-kotlin: 'true' + use-all-platform-bundle: "false" + setup-kotlin: "true" - name: Delete original checkout run: | # delete the original checkout so we don't accidentally use it. diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index f27de17fd8..efbb246fc9 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -8,7 +8,7 @@ on: types: [checks_requested] schedule: # Weekly on Sunday. - - cron: '30 1 * * 0' + - cron: "30 1 * * 0" workflow_dispatch: defaults: @@ -22,7 +22,7 @@ jobs: # Identify the CodeQL tool versions to use in the analysis job. check-codeql-versions: if: github.triggering_actor != 'dependabot[bot]' - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 outputs: versions: ${{ steps.compare.outputs.versions }} @@ -32,41 +32,41 @@ jobs: security-events: read steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Set up default CodeQL bundle - id: setup-default - uses: ./setup-codeql - - name: Set up linked CodeQL bundle - id: setup-linked - uses: ./setup-codeql - with: - tools: linked - - name: Compare default and linked CodeQL bundle versions - id: compare - env: - CODEQL_DEFAULT: ${{ steps.setup-default.outputs.codeql-path }} - CODEQL_LINKED: ${{ steps.setup-linked.outputs.codeql-path }} - run: | - CODEQL_VERSION_DEFAULT="$("$CODEQL_DEFAULT" version --format terse)" - CODEQL_VERSION_LINKED="$("$CODEQL_LINKED" version --format terse)" - echo "Default CodeQL bundle version is $CODEQL_VERSION_DEFAULT" - echo "Linked CodeQL bundle version is $CODEQL_VERSION_LINKED" + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Set up default CodeQL bundle + id: setup-default + uses: ./setup-codeql + - name: Set up linked CodeQL bundle + id: setup-linked + uses: ./setup-codeql + with: + tools: linked + - name: Compare default and linked CodeQL bundle versions + id: compare + env: + CODEQL_DEFAULT: ${{ steps.setup-default.outputs.codeql-path }} + CODEQL_LINKED: ${{ steps.setup-linked.outputs.codeql-path }} + run: | + CODEQL_VERSION_DEFAULT="$("$CODEQL_DEFAULT" version --format terse)" + CODEQL_VERSION_LINKED="$("$CODEQL_LINKED" version --format terse)" + echo "Default CodeQL bundle version is $CODEQL_VERSION_DEFAULT" + echo "Linked CodeQL bundle version is $CODEQL_VERSION_LINKED" - # If we're running on a pull request, run with both bundles, even if `tools: linked` would - # be the same as `tools: null`. This allows us to make the job for each of the bundles a - # required status check. - # - # If we're running on push or schedule, then we can skip running with `tools: linked` when it would be - # the same as running with `tools: null`. - if [[ "$GITHUB_EVENT_NAME" != "pull_request" && "$GITHUB_EVENT_NAME" != "merge_group" && "$CODEQL_VERSION_DEFAULT" == "$CODEQL_VERSION_LINKED" ]]; then - VERSIONS_JSON='[null]' - else - VERSIONS_JSON='[null, "linked"]' - fi + # If we're running on a pull request, run with both bundles, even if `tools: linked` would + # be the same as `tools: null`. This allows us to make the job for each of the bundles a + # required status check. + # + # If we're running on push or schedule, then we can skip running with `tools: linked` when it would be + # the same as running with `tools: null`. + if [[ "$GITHUB_EVENT_NAME" != "pull_request" && "$GITHUB_EVENT_NAME" != "merge_group" && "$CODEQL_VERSION_DEFAULT" == "$CODEQL_VERSION_LINKED" ]]; then + VERSIONS_JSON='[null]' + else + VERSIONS_JSON='[null, "linked"]' + fi - # Output a JSON-encoded list with the distinct versions to test against. - echo "Suggested matrix config for analysis job: $VERSIONS_JSON" - echo "versions=${VERSIONS_JSON}" >> $GITHUB_OUTPUT + # Output a JSON-encoded list with the distinct versions to test against. + echo "Suggested matrix config for analysis job: $VERSIONS_JSON" + echo "versions=${VERSIONS_JSON}" >> $GITHUB_OUTPUT analyze-javascript: if: github.triggering_actor != 'dependabot[bot]' @@ -74,7 +74,13 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-22.04,ubuntu-24.04,windows-2022,windows-2025,macos-14-xlarge,macos-15-xlarge] + os: + - ubuntu-22.04 + - ubuntu-24.04 + - windows-2022 + - windows-2025 + - macos-14-xlarge + - macos-15-xlarge tools: ${{ fromJson(needs.check-codeql-versions.outputs.versions) }} runs-on: ${{ matrix.os }} @@ -83,30 +89,30 @@ jobs: security-events: write steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Initialize CodeQL - uses: ./init - id: init - with: - languages: javascript - config-file: ./.github/codeql/codeql-config-javascript.yml - tools: ${{ matrix.tools }} - # confirm steps.init.outputs.codeql-path points to the codeql binary - - name: Print CodeQL Version - run: > - "$CODEQL" version --format=json - env: - CODEQL: ${{steps.init.outputs.codeql-path}} - - name: Perform CodeQL Analysis - uses: ./analyze - with: - category: "/language:javascript" - upload: ${{ (matrix.os == 'ubuntu-24.04' && !matrix.tools && github.event_name != 'merge_group' && 'always' ) || 'never' }} + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Initialize CodeQL + uses: ./init + id: init + with: + languages: javascript + config-file: ./.github/codeql/codeql-config-javascript.yml + tools: ${{ matrix.tools }} + # confirm steps.init.outputs.codeql-path points to the codeql binary + - name: Print CodeQL Version + run: > + "$CODEQL" version --format=json + env: + CODEQL: ${{steps.init.outputs.codeql-path}} + - name: Perform CodeQL Analysis + uses: ./analyze + with: + category: "/language:javascript" + upload: ${{ (matrix.os == 'ubuntu-24.04' && !matrix.tools && github.event_name != 'merge_group' && 'always' ) || 'never' }} analyze-other: if: github.triggering_actor != 'dependabot[bot]' - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 strategy: fail-fast: false @@ -119,21 +125,21 @@ jobs: security-events: write steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Initialize CodeQL - uses: ./init - with: - languages: ${{ matrix.language }} - build-mode: none - config: > - paths-ignore: - - lib - - tests - queries: - - uses: security-and-quality - - name: Perform CodeQL Analysis - uses: ./analyze - with: - category: "/language:${{ matrix.language }}" - upload: ${{ (github.event_name != 'merge_group' && 'always') || 'never' }} + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Initialize CodeQL + uses: ./init + with: + languages: ${{ matrix.language }} + build-mode: none + config: > + paths-ignore: + - lib + - tests + queries: + - uses: security-and-quality + - name: Perform CodeQL Analysis + uses: ./analyze + with: + category: "/language:${{ matrix.language }}" + upload: ${{ (github.event_name != 'merge_group' && 'always') || 'never' }} diff --git a/.github/workflows/codescanning-config-cli.yml b/.github/workflows/codescanning-config-cli.yml index 7bc6718e35..f2d819bbc4 100644 --- a/.github/workflows/codescanning-config-cli.yml +++ b/.github/workflows/codescanning-config-cli.yml @@ -10,13 +10,13 @@ env: on: push: branches: - - main - - releases/v* + - main + - releases/v* pull_request: merge_group: types: [checks_requested] schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: concurrency: @@ -41,186 +41,187 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest - version: linked - - os: ubuntu-latest - version: default - - os: ubuntu-latest - version: nightly-latest + - os: ubuntu-26.04 + version: linked + - os: ubuntu-26.04 + version: default + - os: ubuntu-26.04 + version: nightly-latest # Code-Scanning config not created because environment variable is not set name: Code Scanning Configuration tests timeout-minutes: 45 runs-on: ${{ matrix.os }} steps: - - name: Check out repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 - with: - node-version: 24 - cache: 'npm' - - - name: Install dependencies - run: npm ci - - - name: Prepare test - id: prepare-test - uses: ./.github/actions/prepare-test - with: - version: ${{ matrix.version }} - - - name: Empty file - uses: ./../action/.github/actions/check-codescanning-config - with: - expected-config-file-contents: "{}" - languages: javascript - tools: ${{ steps.prepare-test.outputs.tools-url }} - - - name: Packs from input - if: success() || failure() - uses: ./../action/.github/actions/check-codescanning-config - with: - expected-config-file-contents: | - { - "packs": ["codeql-testing/codeql-pack1@1.0.0", "codeql-testing/codeql-pack2" ] - } - languages: javascript - packs: codeql-testing/codeql-pack1@1.0.0, codeql-testing/codeql-pack2 - tools: ${{ steps.prepare-test.outputs.tools-url }} - - - name: Packs from input with + - if: success() || failure() - uses: ./../action/.github/actions/check-codescanning-config - with: - expected-config-file-contents: | - { - "packs": ["codeql-testing/codeql-pack1@1.0.0", "codeql-testing/codeql-pack2" ] - } - languages: javascript - packs: + codeql-testing/codeql-pack1@1.0.0, codeql-testing/codeql-pack2 - tools: ${{ steps.prepare-test.outputs.tools-url }} - - - name: Queries from input - if: success() || failure() - uses: ./../action/.github/actions/check-codescanning-config - with: - expected-config-file-contents: | - { - "queries": [{ "uses": "./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql" }] - } - languages: javascript - queries: ./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql - tools: ${{ steps.prepare-test.outputs.tools-url }} - - - name: Queries from input with + - if: success() || failure() - uses: ./../action/.github/actions/check-codescanning-config - with: - expected-config-file-contents: | - { - "queries": [{ "uses": "./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql" }] - } - languages: javascript - queries: + ./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql - tools: ${{ steps.prepare-test.outputs.tools-url }} - - - name: Queries and packs from input with + - if: success() || failure() - uses: ./../action/.github/actions/check-codescanning-config - with: - expected-config-file-contents: | - { - "queries": [{ "uses": "./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql" }], - "packs": ["codeql-testing/codeql-pack1@1.0.0", "codeql-testing/codeql-pack2" ] - } - languages: javascript - queries: + ./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql - packs: + codeql-testing/codeql-pack1@1.0.0, codeql-testing/codeql-pack2 - tools: ${{ steps.prepare-test.outputs.tools-url }} - - - name: Queries and packs from config - if: success() || failure() - uses: ./../action/.github/actions/check-codescanning-config - with: - expected-config-file-contents: | - { - "queries": [{ "uses": "./codeql-qlpacks/complex-javascript-qlpack/foo2/show_ifs.ql" }], - "packs": { - "javascript": ["codeql-testing/codeql-pack1@1.0.0", "codeql-testing/codeql-pack2" ] + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + cache: "npm" + + - name: Install dependencies + run: npm ci + + - name: Prepare test + id: prepare-test + uses: ./.github/actions/prepare-test + with: + version: ${{ matrix.version }} + + - name: Empty file + uses: ./../action/.github/actions/check-codescanning-config + with: + expected-config-file-contents: "{}" + # Request multiple languages so later checks can reuse the combined bundle. + languages: javascript,python + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Packs from input + if: success() || failure() + uses: ./../action/.github/actions/check-codescanning-config + with: + expected-config-file-contents: | + { + "packs": ["codeql-testing/codeql-pack1@1.0.0", "codeql-testing/codeql-pack2" ] } - } - languages: javascript - config-file-test: .github/codeql/queries-and-packs-config.yml - tools: ${{ steps.prepare-test.outputs.tools-url }} - - - name: Queries and packs from config overriden by input - if: success() || failure() - uses: ./../action/.github/actions/check-codescanning-config - with: - expected-config-file-contents: | - { - "queries": [{ "uses": "./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql" }], - "packs": ["codeql/javascript-queries"] - } - languages: javascript - queries: ./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql - packs: codeql/javascript-queries - config-file-test: .github/codeql/queries-and-packs-config.yml - tools: ${{ steps.prepare-test.outputs.tools-url }} - - - name: Queries and packs from config merging with input - if: success() || failure() - uses: ./../action/.github/actions/check-codescanning-config - with: - expected-config-file-contents: | - { - "packs": { - "javascript": ["codeql-testing/codeql-pack1@1.0.0", "codeql-testing/codeql-pack2", "codeql/javascript-queries" ] - }, - "queries": [ - { "uses": "./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql" }, - { "uses": "./codeql-qlpacks/complex-javascript-qlpack/foo2/show_ifs.ql" } - ] - } - languages: javascript - queries: + ./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql - packs: + codeql/javascript-queries - config-file-test: .github/codeql/queries-and-packs-config.yml - tools: ${{ steps.prepare-test.outputs.tools-url }} - - - name: Multi-language packs from config - if: success() || failure() - uses: ./../action/.github/actions/check-codescanning-config - with: - expected-config-file-contents: | - { - "packs": { - "javascript": ["codeql-testing/codeql-pack1@1.0.0", "codeql-testing/codeql-pack2" ], - "ruby": ["codeql/ruby-queries"] - }, - "queries": [ - { "uses": "./codeql-qlpacks/complex-javascript-qlpack/foo2/show_ifs.ql" } - ] - } - languages: javascript,ruby - config-file-test: .github/codeql/multi-language-packs-config.yml - tools: ${{ steps.prepare-test.outputs.tools-url }} - - - name: Other config properties - if: success() || failure() - uses: ./../action/.github/actions/check-codescanning-config - with: - expected-config-file-contents: | - { - "name": "Config using all properties", - "packs": ["codeql/javascript-queries" ], - "disable-default-queries": true, - "paths-ignore": ["xxx"], - "paths": ["yyy"] - } - languages: javascript - packs: + codeql/javascript-queries - config-file-test: .github/codeql/other-config-properties.yml - tools: ${{ steps.prepare-test.outputs.tools-url }} + languages: javascript + packs: codeql-testing/codeql-pack1@1.0.0, codeql-testing/codeql-pack2 + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Packs from input with + + if: success() || failure() + uses: ./../action/.github/actions/check-codescanning-config + with: + expected-config-file-contents: | + { + "packs": ["codeql-testing/codeql-pack1@1.0.0", "codeql-testing/codeql-pack2" ] + } + languages: javascript + packs: + codeql-testing/codeql-pack1@1.0.0, codeql-testing/codeql-pack2 + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Queries from input + if: success() || failure() + uses: ./../action/.github/actions/check-codescanning-config + with: + expected-config-file-contents: | + { + "queries": [{ "uses": "./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql" }] + } + languages: javascript + queries: ./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Queries from input with + + if: success() || failure() + uses: ./../action/.github/actions/check-codescanning-config + with: + expected-config-file-contents: | + { + "queries": [{ "uses": "./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql" }] + } + languages: javascript + queries: + ./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Queries and packs from input with + + if: success() || failure() + uses: ./../action/.github/actions/check-codescanning-config + with: + expected-config-file-contents: | + { + "queries": [{ "uses": "./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql" }], + "packs": ["codeql-testing/codeql-pack1@1.0.0", "codeql-testing/codeql-pack2" ] + } + languages: javascript + queries: + ./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql + packs: + codeql-testing/codeql-pack1@1.0.0, codeql-testing/codeql-pack2 + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Queries and packs from config + if: success() || failure() + uses: ./../action/.github/actions/check-codescanning-config + with: + expected-config-file-contents: | + { + "queries": [{ "uses": "./codeql-qlpacks/complex-javascript-qlpack/foo2/show_ifs.ql" }], + "packs": { + "javascript": ["codeql-testing/codeql-pack1@1.0.0", "codeql-testing/codeql-pack2" ] + } + } + languages: javascript + config-file-test: .github/codeql/queries-and-packs-config.yml + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Queries and packs from config overriden by input + if: success() || failure() + uses: ./../action/.github/actions/check-codescanning-config + with: + expected-config-file-contents: | + { + "queries": [{ "uses": "./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql" }], + "packs": ["codeql/javascript-queries"] + } + languages: javascript + queries: ./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql + packs: codeql/javascript-queries + config-file-test: .github/codeql/queries-and-packs-config.yml + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Queries and packs from config merging with input + if: success() || failure() + uses: ./../action/.github/actions/check-codescanning-config + with: + expected-config-file-contents: | + { + "packs": { + "javascript": ["codeql-testing/codeql-pack1@1.0.0", "codeql-testing/codeql-pack2", "codeql/javascript-queries" ] + }, + "queries": [ + { "uses": "./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql" }, + { "uses": "./codeql-qlpacks/complex-javascript-qlpack/foo2/show_ifs.ql" } + ] + } + languages: javascript + queries: + ./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql + packs: + codeql/javascript-queries + config-file-test: .github/codeql/queries-and-packs-config.yml + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Multi-language packs from config + if: success() || failure() + uses: ./../action/.github/actions/check-codescanning-config + with: + expected-config-file-contents: | + { + "packs": { + "javascript": ["codeql-testing/codeql-pack1@1.0.0", "codeql-testing/codeql-pack2" ], + "ruby": ["codeql/ruby-queries"] + }, + "queries": [ + { "uses": "./codeql-qlpacks/complex-javascript-qlpack/foo2/show_ifs.ql" } + ] + } + languages: javascript,ruby + config-file-test: .github/codeql/multi-language-packs-config.yml + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Other config properties + if: success() || failure() + uses: ./../action/.github/actions/check-codescanning-config + with: + expected-config-file-contents: | + { + "name": "Config using all properties", + "packs": ["codeql/javascript-queries" ], + "disable-default-queries": true, + "paths-ignore": ["xxx"], + "paths": ["yyy"] + } + languages: javascript + packs: + codeql/javascript-queries + config-file-test: .github/codeql/other-config-properties.yml + tools: ${{ steps.prepare-test.outputs.tools-url }} diff --git a/.github/workflows/debug-artifacts-failure-safe.yml b/.github/workflows/debug-artifacts-failure-safe.yml index f67cef5c75..c9599e446c 100644 --- a/.github/workflows/debug-artifacts-failure-safe.yml +++ b/.github/workflows/debug-artifacts-failure-safe.yml @@ -6,13 +6,13 @@ env: on: push: branches: - - main - - releases/v* + - main + - releases/v* pull_request: merge_group: types: [checks_requested] schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: concurrency: @@ -30,10 +30,10 @@ jobs: fail-fast: false matrix: version: - - stable-v2.20.3 - - default - - linked - - nightly-latest + - stable-v2.20.7 + - default + - linked + - nightly-latest name: Upload debug artifacts after failure in analyze continue-on-error: true env: @@ -43,7 +43,12 @@ jobs: # We currently need `security-events: read` to access feature flags. security-events: read timeout-minutes: 45 - runs-on: ubuntu-latest + + # stable-v2.20.7 requires an older version of Java than the default on `ubuntu-latest` (`ubuntu-26.04`). + # We could install that older version on the newer runners, or use the older runner. + # We do the latter here. This can be removed once we stop supporting `v2.20.7`. + runs-on: ${{ case(matrix.version == 'stable-v2.20.7', 'ubuntu-24.04', 'ubuntu-26.04') }} + steps: - name: Dump GitHub event run: cat "${GITHUB_EVENT_PATH}" @@ -60,7 +65,7 @@ jobs: - name: Install .NET uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: - dotnet-version: '9.x' + dotnet-version: "9.x" - name: Assert best-effort artifact scan completed uses: ./../action/.github/actions/verify-debug-artifact-scan-completed - uses: ./../action/init @@ -86,12 +91,13 @@ jobs: timeout-minutes: 45 permissions: contents: read - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 steps: - name: Download all artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - name: Check expected artifacts exist run: | + VERSIONS="stable-v2.20.7 default linked nightly-latest" LANGUAGES="cpp csharp go java javascript python" for version in $VERSIONS; do echo "Artifacts from version $version:" diff --git a/.github/workflows/debug-artifacts-safe.yml b/.github/workflows/debug-artifacts-safe.yml index c27f195113..4e2035b9ee 100644 --- a/.github/workflows/debug-artifacts-safe.yml +++ b/.github/workflows/debug-artifacts-safe.yml @@ -5,13 +5,13 @@ env: on: push: branches: - - main - - releases/v* + - main + - releases/v* pull_request: merge_group: types: [checks_requested] schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: concurrency: @@ -29,10 +29,10 @@ jobs: fail-fast: false matrix: version: - - stable-v2.20.3 - - default - - linked - - nightly-latest + - stable-v2.20.7 + - default + - linked + - nightly-latest name: Upload debug artifacts env: CODEQL_ACTION_TEST_MODE: true @@ -41,7 +41,12 @@ jobs: contents: read # We currently need `security-events: read` to access feature flags. security-events: read - runs-on: ubuntu-latest + + # stable-v2.20.7 requires an older version of Java than the default on `ubuntu-latest` (`ubuntu-26.04`). + # We could install that older version on the newer runners, or use the older runner. + # We do the latter here. This can be removed once we stop supporting `v2.20.7`. + runs-on: ${{ case(matrix.version == 'stable-v2.20.7', 'ubuntu-24.04', 'ubuntu-26.04') }} + steps: - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -56,7 +61,7 @@ jobs: - name: Install .NET uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: - dotnet-version: '9.x' + dotnet-version: "9.x" - name: Assert best-effort artifact scan completed uses: ./../action/.github/actions/verify-debug-artifact-scan-completed - uses: ./../action/init @@ -79,13 +84,13 @@ jobs: timeout-minutes: 45 permissions: contents: read - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 steps: - name: Download all artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - name: Check expected artifacts exist run: | - VERSIONS="stable-v2.20.3 default linked nightly-latest" + VERSIONS="stable-v2.20.7 default linked nightly-latest" LANGUAGES="cpp csharp go java javascript python" for version in $VERSIONS; do pushd "./my-debug-artifacts-${version//./}" diff --git a/.github/workflows/deflake.yml b/.github/workflows/deflake.yml index 158dc6c96d..27024b3780 100644 --- a/.github/workflows/deflake.yml +++ b/.github/workflows/deflake.yml @@ -60,7 +60,6 @@ on: - "PR Check - Proxy test" - "PR Check - Remote config file" - "PR Check - Resolve environment" - - "PR Check - RuboCop multi-language" - "PR Check - Ruby analysis" - "PR Check - Rust analysis" - "PR Check - Split workflow" diff --git a/.github/workflows/post-release-mergeback.yml b/.github/workflows/post-release-mergeback.yml index c493c2a382..4e9a0c7a77 100644 --- a/.github/workflows/post-release-mergeback.yml +++ b/.github/workflows/post-release-mergeback.yml @@ -10,7 +10,7 @@ on: workflow_dispatch: inputs: baseBranch: - description: 'The base branch to merge into' + description: "The base branch to merge into" default: main required: false @@ -24,7 +24,7 @@ defaults: jobs: merge-back: - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 environment: Automation if: github.repository == 'github/codeql-action' env: @@ -41,16 +41,16 @@ jobs: - name: Dump GitHub context env: - GITHUB_CONTEXT: '${{ toJson(github) }}' + GITHUB_CONTEXT: "${{ toJson(github) }}" run: echo "${GITHUB_CONTEXT}" - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - fetch-depth: 0 # ensure we have all tags and can push commits - - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + fetch-depth: 0 # ensure we have all tags and can push commits + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 - cache: 'npm' + cache: "npm" - name: Install JavaScript dependencies run: npm ci @@ -134,7 +134,7 @@ jobs: echo "::endgroup::" - name: Generate token - uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 id: app-token with: app-id: ${{ vars.AUTOMATION_APP_ID }} diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index ac61475d62..81d88d1a7d 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -2,6 +2,9 @@ name: PR Checks on: push: + branches: + - "main" + - "releases/v*" pull_request: merge_group: types: [checks_requested] @@ -22,7 +25,7 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, macos-latest, windows-latest] + os: [ubuntu-26.04, macos-26, windows-2025] node-version: [20, 24] permissions: contents: read @@ -42,10 +45,16 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: ${{ matrix.node-version }} - cache: 'npm' + cache: "npm" + + # Install a new enough version of `npm` to understand `min-release-age` + # that is still compatible with Node 20. + - name: Install newer npm + if: matrix.node-version == 20 + run: npm install -g npm@11.19.1 - name: Install dependencies run: | @@ -55,19 +64,24 @@ jobs: npm ci - name: Verify compiled JS up to date - run: .github/workflows/script/check-js.sh + run: npx tsx pr-checks/check-unchanged.ts --language javascript - name: Run unit tests if: always() run: npm test - name: Lint - if: always() && matrix.os != 'windows-latest' + if: always() && matrix.os != 'windows-2025' run: npm run lint-ci - name: Upload sarif uses: ./upload-sarif - if: matrix.os == 'ubuntu-latest' && matrix.node-version == 24 + # The merge queue deletes its `gh-readonly-queue` ref as soon as the queue entry resolves, + # so uploading against it races with that deletion. Both the `merge_group` run and the + # paired `push` run that the queue branch creates use that ref, so gate on the ref itself + # rather than the event. The same results are uploaded by the `pull_request` run and again + # by the `push` run on `main`. + if: matrix.os == 'ubuntu-26.04' && matrix.node-version == 24 && !startsWith(github.ref, 'refs/heads/gh-readonly-queue/') with: sarif_file: eslint.sarif category: eslint @@ -79,7 +93,7 @@ jobs: if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 timeout-minutes: 10 concurrency: @@ -90,24 +104,44 @@ jobs: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Check for incorrect addresses in package-lock.json + run: | + if git grep -nE '(pkgs\.visualstudio\.com|pkgs\.dev\.azure\.com|packagefeedproxy\.microsoft\.io)' -- \ + 'package-lock.json'; then + echo "::error::package-lock.json contains internal package feed URLs. Replace them with public registry URLs." + exit 1 + fi + - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 - cache: 'npm' + cache: "npm" - name: Install dependencies id: install-deps run: npm ci + - name: Verify YAML is correctly formatted + run: npx tsx pr-checks/check-unchanged.ts --language yaml + - name: Verify PR checks up to date if: ${{ !cancelled() && steps.install-deps.outcome == 'success' }} run: .github/workflows/script/verify-pr-checks.sh + - name: Typecheck pr-checks scripts + if: ${{ !cancelled() && steps.install-deps.outcome == 'success' }} + working-directory: pr-checks + run: npm run typecheck + - name: Run pr-checks tests if: ${{ !cancelled() && steps.install-deps.outcome == 'success' }} working-directory: pr-checks - run: npx tsx --test + run: npm run test + + - name: Run `pr-checks/changenotes.ts` to ensure that all unreleased change notes are valid + if: ${{ !cancelled() && steps.install-deps.outcome == 'success' }} + run: npx tsx pr-checks/changenotes.ts validate - name: Verify all Actions use the same Node version id: head-version @@ -122,12 +156,11 @@ jobs: - name: Fetch base commit id: fetch-base - # Forks and Dependabot PRs don't have permission to write comments, so skip the repo size - # check in those cases. + # Skip this (and subsequent steps) if the PR originates from a fork, since this workflow + # won't have the necessary permissions to post comments on the PR. if: >- github.event_name == 'pull_request' && - github.event.pull_request.head.repo.full_name == github.repository && - github.event.pull_request.user.login != 'dependabot[bot]' + github.event.pull_request.head.repo.full_name == github.repository env: BASE_SHA: ${{ github.event.pull_request.base.sha }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} @@ -152,20 +185,20 @@ jobs: - name: Upload repo size comment if: steps.fetch-base.outcome == 'success' - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: repo-size-comment path: ${{ runner.temp }}/repo-size/ if-no-files-found: error - - name: 'Backport: Check out base ref' + - name: "Backport: Check out base ref" id: checkout-base if: ${{ startsWith(github.head_ref, 'backport-') }} uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.base_ref }} - - name: 'Backport: Verify Node versions unchanged' + - name: "Backport: Verify Node versions unchanged" if: steps.checkout-base.outcome == 'success' env: HEAD_VERSION: ${{ steps.head-version.outputs.node_version }} @@ -186,7 +219,7 @@ jobs: if: >- github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && - github.event.pull_request.user.login != 'dependabot[bot]' && + github.actor != 'dependabot[bot]' && needs.other-checks.result == 'success' permissions: contents: read @@ -200,7 +233,7 @@ jobs: steps: - name: Download repo size comment - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: repo-size-comment path: repo-size-comment diff --git a/.github/workflows/pr-dequeued.yml b/.github/workflows/pr-dequeued.yml new file mode 100644 index 0000000000..25260c7aa6 --- /dev/null +++ b/.github/workflows/pr-dequeued.yml @@ -0,0 +1,43 @@ +name: PR dequeued + +on: + pull_request: + types: + - dequeued + +jobs: + notify: + name: Notify + runs-on: ubuntu-slim + + if: github.event.pull_request.merged != true + + permissions: + pull-requests: write + + steps: + - name: Notify that the PR was removed from the merge queue + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ github.event.pull_request.number }} + REASON: ${{ github.event.reason }} + run: | + # Mention whoever added the PR to the merge queue rather than the PR author, who may be a + # bot such as Dependabot. The `dequeued` event payload doesn't identify the enqueuer, so + # look them up in the most recent `AddedToMergeQueueEvent` on the PR's timeline. + enqueuer=$(gh api graphql \ + -F number="$PR_NUMBER" \ + -f query=' + query($number: Int!) { + repository(owner: "github", name: "codeql-action") { + pullRequest(number: $number) { + timelineItems(itemTypes: [ADDED_TO_MERGE_QUEUE_EVENT], last: 1) { + nodes { ... on AddedToMergeQueueEvent { enqueuer { login } } } + } + } + } + }' \ + --jq '.data.repository.pullRequest.timelineItems.nodes[0].enqueuer.login') + echo "@$enqueuer The pull request was removed from the merge queue (\`$REASON\`)." \ + "Please resolve any issues if required and enqueue the PR again." | + gh pr comment --body-file - --repo github/codeql-action "$PR_NUMBER" diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index 4eb300704d..8073c44c32 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -28,8 +28,8 @@ defaults: jobs: prepare: - name: "Prepare release" - runs-on: ubuntu-latest + name: "Release info" + runs-on: ubuntu-26.04 if: github.repository == 'github/codeql-action' permissions: diff --git a/.github/workflows/publish-immutable-action.yml b/.github/workflows/publish-immutable-action.yml index 5e5623bb07..83485875cc 100644 --- a/.github/workflows/publish-immutable-action.yml +++ b/.github/workflows/publish-immutable-action.yml @@ -1,10 +1,10 @@ -name: 'Publish Immutable Action Version' +name: "Publish Immutable Action Version" on: push: tags: # Match version tags, but not the major version tags. - - 'v[0-9]+.**' + - "v[0-9]+.**" defaults: run: diff --git a/.github/workflows/python312-windows.yml b/.github/workflows/python312-windows.yml index ab169499e2..9ce50b8ffc 100644 --- a/.github/workflows/python312-windows.yml +++ b/.github/workflows/python312-windows.yml @@ -8,7 +8,7 @@ on: types: [checks_requested] schedule: # Weekly on Monday. - - cron: '0 0 * * 1' + - cron: "0 0 * * 1" workflow_dispatch: concurrency: @@ -29,25 +29,25 @@ jobs: contents: read # We currently need `security-events: read` to access feature flags. security-events: read - runs-on: windows-latest + runs-on: windows-2025 steps: - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - with: - python-version: 3.12 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: 3.12 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Prepare test - uses: ./.github/actions/prepare-test - with: - version: default + - name: Prepare test + uses: ./.github/actions/prepare-test + with: + version: default - - name: Initialize CodeQL - uses: ./../action/init - with: - tools: linked - languages: python + - name: Initialize CodeQL + uses: ./../action/init + with: + tools: linked + languages: python - - name: Analyze - uses: ./../action/analyze + - name: Analyze + uses: ./../action/analyze diff --git a/.github/workflows/query-filters.yml b/.github/workflows/query-filters.yml index 87b934eb6b..69ccd6c686 100644 --- a/.github/workflows/query-filters.yml +++ b/.github/workflows/query-filters.yml @@ -3,13 +3,13 @@ name: Query filters tests on: push: branches: - - main - - releases/v* + - main + - releases/v* pull_request: merge_group: types: [checks_requested] schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: concurrency: @@ -25,51 +25,51 @@ jobs: name: Query Filters Tests if: github.triggering_actor != 'dependabot[bot]' timeout-minutes: 45 - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 permissions: contents: read # This permission is needed to allow the GitHub Actions workflow to read the contents of the repository. steps: - - name: Check out repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Install Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 - with: - node-version: 24 - cache: npm + - name: Install Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + cache: npm - - name: Install dependencies - run: npm ci + - name: Install dependencies + run: npm ci - - name: Prepare test - id: prepare-test - uses: ./.github/actions/prepare-test - with: - version: linked + - name: Prepare test + id: prepare-test + uses: ./.github/actions/prepare-test + with: + version: linked - - name: Check SARIF for default queries with Single include, Single exclude - uses: ./../action/.github/actions/query-filter-test - with: - sarif-file: ${{ runner.temp }}/results/javascript.sarif - queries-run: js/zipslip - queries-not-run: js/path-injection - config-file: ./.github/codeql/codeql-config-query-filters1.yml - tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Check SARIF for default queries with Single include, Single exclude + uses: ./../action/.github/actions/query-filter-test + with: + sarif-file: ${{ runner.temp }}/results/javascript.sarif + queries-run: js/zipslip + queries-not-run: js/path-injection + config-file: ./.github/codeql/codeql-config-query-filters1.yml + tools: ${{ steps.prepare-test.outputs.tools-url }} - - name: Check SARIF for query packs with Single include, Single exclude - uses: ./../action/.github/actions/query-filter-test - with: - sarif-file: ${{ runner.temp }}/results/javascript.sarif - queries-run: js/zipslip,javascript/example/empty-or-one-block - queries-not-run: js/path-injection - config-file: ./.github/codeql/codeql-config-query-filters2.yml - tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Check SARIF for query packs with Single include, Single exclude + uses: ./../action/.github/actions/query-filter-test + with: + sarif-file: ${{ runner.temp }}/results/javascript.sarif + queries-run: js/zipslip,javascript/example/empty-or-one-block + queries-not-run: js/path-injection + config-file: ./.github/codeql/codeql-config-query-filters2.yml + tools: ${{ steps.prepare-test.outputs.tools-url }} - - name: Check SARIF for query packs and local queries with Single include, Single exclude - uses: ./../action/.github/actions/query-filter-test - with: - sarif-file: ${{ runner.temp }}/results/javascript.sarif - queries-run: js/zipslip,javascript/example/empty-or-one-block,inrepo-javascript-querypack/show-ifs - queries-not-run: js/path-injection,complex-python-querypack/show-ifs,complex-python-querypack/foo/bar/show-ifs - config-file: ./.github/codeql/codeql-config-query-filters3.yml - tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Check SARIF for query packs and local queries with Single include, Single exclude + uses: ./../action/.github/actions/query-filter-test + with: + sarif-file: ${{ runner.temp }}/results/javascript.sarif + queries-run: js/zipslip,javascript/example/empty-or-one-block,inrepo-javascript-querypack/show-ifs + queries-not-run: js/path-injection,complex-python-querypack/show-ifs,complex-python-querypack/foo/bar/show-ifs + config-file: ./.github/codeql/codeql-config-query-filters3.yml + tools: ${{ steps.prepare-test.outputs.tools-url }} diff --git a/.github/workflows/rebuild.yml b/.github/workflows/rebuild.yml index faa32c65d9..c37910a779 100644 --- a/.github/workflows/rebuild.yml +++ b/.github/workflows/rebuild.yml @@ -12,7 +12,7 @@ defaults: jobs: rebuild: name: Rebuild Action - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 if: github.event.label.name == 'Rebuild' || github.event_name == 'workflow_dispatch' env: @@ -30,10 +30,10 @@ jobs: ref: ${{ env.HEAD_REF }} - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 - cache: 'npm' + cache: "npm" - name: Remove label if: github.event_name == 'pull_request' @@ -54,32 +54,27 @@ jobs: run: | git fetch origin "$BASE_BRANCH" - # Allow merge conflicts in `lib`, since rebuilding should resolve them. - git merge "origin/$BASE_BRANCH" - MERGE_RESULT=$? - - if [ "$MERGE_RESULT" -eq 0 ]; then + # Allow merge conflicts in `lib`, since rebuilding should resolve them. Conflicts leave the + # merge in progress, so check for `MERGE_HEAD` to tell them apart from failures that don't. + if git merge "origin/$BASE_BRANCH"; then echo "Merge succeeded cleanly." - elif [ "$MERGE_RESULT" -eq 1 ]; then - echo "Merge conflicts detected (exit code $MERGE_RESULT), continuing." - else - echo "git merge failed with unexpected exit code $MERGE_RESULT." - exit 1 - fi - - if [ "$MERGE_RESULT" -ne 0 ]; then + elif git rev-parse --verify MERGE_HEAD >/dev/null 2>&1; then + echo "Merge conflicts detected, continuing." echo "merge-in-progress=true" >> $GITHUB_OUTPUT - # Check for merge conflicts outside of `lib`. Disable git diff's trailing whitespace check - # since `node_modules/@types/semver/README.md` fails it. - if git -c core.whitespace=-trailing-space diff --check | grep --invert-match '^lib/'; then + # Check for merge conflicts outside of `lib`. + CONFLICTS_OUTSIDE_LIB=$(git diff --name-only --diff-filter=U | grep --invert-match '^lib/' || true) + if [ -n "$CONFLICTS_OUTSIDE_LIB" ]; then echo "Merge conflicts were detected outside of the lib directory. Please resolve them manually." - git -c core.whitespace=-trailing-space diff --check | grep --invert-match '^lib/' || true + echo "$CONFLICTS_OUTSIDE_LIB" exit 1 fi echo "No merge conflicts found outside the lib directory. We should be able to resolve all of" \ "these by rebuilding the Action." + else + echo "git merge failed for a reason other than merge conflicts." + exit 1 fi - name: Compile TypeScript diff --git a/.github/workflows/rollback-release.yml b/.github/workflows/rollback-release.yml index c37f8a79ae..81353bfb4f 100644 --- a/.github/workflows/rollback-release.yml +++ b/.github/workflows/rollback-release.yml @@ -10,8 +10,7 @@ on: required: true # Only for dry-runs of changes to the workflow. push: - # Don't run dry-run on release branches, to avoid an issue where the - # "new" tag determined by the "Prepare release" job already exists. + # Don't run dry-run on release branches, since that's unnecessary. branches-ignore: - releases/v* paths: @@ -24,7 +23,7 @@ defaults: jobs: prepare: - name: "Prepare release" + name: "Prepare" if: github.repository == 'github/codeql-action' permissions: @@ -35,7 +34,7 @@ jobs: rollback: name: "Create rollback release" if: github.repository == 'github/codeql-action' - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 timeout-minutes: 45 # Don't set the deployment environment for test runs @@ -107,8 +106,10 @@ jobs: # We usually expect to checkout `inputs.rollback-tag` (required for `workflow_dispatch`), # but use `v0.0.0` for testing. ROLLBACK_TAG: ${{ inputs.rollback-tag || 'v0.0.0' }} - RELEASE_TAG: ${{ needs.prepare.outputs.version }} - MAJOR_VERSION_TAG: ${{ needs.prepare.outputs.major_version }} + # Use `needs.prepare.outputs.version` for actual runs and `v0.0.1` for testing. + RELEASE_TAG: ${{ case(github.event_name == 'workflow_dispatch', needs.prepare.outputs.version, 'v0.0.1') }} + # Use `needs.prepare.outputs.major_version` for actual runs and `v0` for testing. + MAJOR_VERSION_TAG: ${{ case(github.event_name == 'workflow_dispatch', needs.prepare.outputs.major_version, 'v0') }} run: | git checkout "refs/tags/${ROLLBACK_TAG}" git tag --annotate "${RELEASE_TAG}" --message "${RELEASE_TAG}" @@ -138,7 +139,7 @@ jobs: - name: Generate token if: github.event_name == 'workflow_dispatch' - uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 id: app-token with: app-id: ${{ vars.AUTOMATION_APP_ID }} @@ -184,4 +185,3 @@ jobs: # Setting this to `true` for non-workflow_dispatch events will # still push the `branch`, but won't create a corresponding PR dry-run: "${{ github.event_name != 'workflow_dispatch' }}" - diff --git a/.github/workflows/script/check-js.sh b/.github/workflows/script/check-js.sh deleted file mode 100755 index 57638dcf25..0000000000 --- a/.github/workflows/script/check-js.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash -set -eu - -# Sanity check that repo is clean to start with -if [ ! -z "$(git status --porcelain)" ]; then - # If we get a fail here then this workflow needs attention... - >&2 echo "Failed: Repo should be clean before testing!" - exit 1 -fi -# Wipe the lib directory in case there are extra unnecessary files in there -rm -rf lib -# Generate the JavaScript files -npm run-script build -# Check that repo is still clean -if [ ! -z "$(git status --porcelain)" ]; then - # If we get a fail here then the PR needs attention - >&2 echo "Failed: JavaScript files are not up to date. Run 'rm -rf lib && npm run-script build' to update" - git status - - echo "### Transpiled JS diff" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo '```diff' >> $GITHUB_STEP_SUMMARY - git diff --output="$RUNNER_TEMP/js.diff" - cat "$RUNNER_TEMP/js.diff" >> $GITHUB_STEP_SUMMARY - echo '```' >> $GITHUB_STEP_SUMMARY - - # Reset bundled files to allow other checks to test for changes - git checkout lib - - # Fail this check - exit 1 -fi -echo "Success: JavaScript files are up to date" diff --git a/.github/workflows/test-codeql-bundle-all.yml b/.github/workflows/test-codeql-bundle-all.yml index 477fdf0524..9fae4b04a6 100644 --- a/.github/workflows/test-codeql-bundle-all.yml +++ b/.github/workflows/test-codeql-bundle-all.yml @@ -1,17 +1,17 @@ -name: 'PR Check - CodeQL Bundle All' +name: "PR Check - CodeQL Bundle All" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto on: push: branches: - - main - - releases/v* + - main + - releases/v* pull_request: merge_group: types: [checks_requested] schedule: - - cron: '0 5 * * *' + - cron: "0 5 * * *" workflow_dispatch: concurrency: @@ -27,9 +27,9 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest - version: nightly-latest - name: 'CodeQL Bundle All' + - os: ubuntu-26.04 + version: nightly-latest + name: "CodeQL Bundle All" if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read @@ -37,26 +37,26 @@ jobs: timeout-minutes: 45 runs-on: ${{ matrix.os }} steps: - - name: Check out repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Prepare test - id: prepare-test - uses: ./.github/actions/prepare-test - with: - version: ${{ matrix.version }} - use-all-platform-bundle: true - - name: Install .NET - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 - with: - dotnet-version: '9.x' - - id: init - uses: ./../action/init - with: - # We manually exclude Swift from the languages list here, as it is not supported on Ubuntu - languages: cpp,csharp,go,java,javascript,python,ruby - tools: ${{ steps.prepare-test.outputs.tools-url }} - - name: Build code - run: ./build.sh - - uses: ./../action/analyze + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Prepare test + id: prepare-test + uses: ./.github/actions/prepare-test + with: + version: ${{ matrix.version }} + use-all-platform-bundle: true + - name: Install .NET + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: "9.x" + - id: init + uses: ./../action/init + with: + # We manually exclude Swift from the languages list here, as it is not supported on Ubuntu + languages: cpp,csharp,go,java,javascript,python,ruby + tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Build code + run: ./build.sh + - uses: ./../action/analyze env: CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/update-bundle.yml b/.github/workflows/update-bundle.yml index d3ee924e59..84aae2984e 100644 --- a/.github/workflows/update-bundle.yml +++ b/.github/workflows/update-bundle.yml @@ -20,7 +20,7 @@ defaults: jobs: update-bundle: if: github.event.release.prerelease && startsWith(github.event.release.tag_name, 'codeql-bundle-') - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 permissions: contents: write # needed to push commits pull-requests: write # needed to create pull requests @@ -30,7 +30,7 @@ jobs: - name: Dump GitHub context env: - GITHUB_CONTEXT: '${{ toJson(github) }}' + GITHUB_CONTEXT: "${{ toJson(github) }}" run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -41,10 +41,10 @@ jobs: git config --global user.name "github-actions[bot]" - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 - cache: 'npm' + cache: "npm" - name: Install dependencies run: npm ci @@ -113,11 +113,12 @@ jobs: echo "CLI_VERSION=$cli_version" | tee -a "$GITHUB_ENV" echo "PR_URL=$pr_url" | tee -a "$GITHUB_ENV" - - name: Create changelog note + - name: Create changenote run: | npx tsx pr-checks/bundle-changelog.ts - - name: Push changelog note + - name: Push changenote run: | - git commit -am "Add changelog note" + git add unreleased-change-notes + git commit -m "Add changenote" git push diff --git a/.github/workflows/update-release-branch.yml b/.github/workflows/update-release-branch.yml index 9f38f0f0b4..098b9c8af8 100644 --- a/.github/workflows/update-release-branch.yml +++ b/.github/workflows/update-release-branch.yml @@ -16,17 +16,17 @@ defaults: shell: bash jobs: - prepare: - name: "Prepare release" + name: "Prepare" permissions: contents: read uses: ./.github/workflows/prepare-release.yml update: + name: "Update release branch" timeout-minutes: 45 - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 if: github.event_name == 'workflow_dispatch' needs: [prepare] env: @@ -38,47 +38,48 @@ jobs: contents: write # needed to push commits pull-requests: write # needed to create pull request steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 # Need full history for calculation of diffs - - uses: ./.github/actions/release-initialise + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 # Need full history for calculation of diffs + - uses: ./.github/actions/release-initialise - # when the workflow has been manually triggered on main, - # we know that we definitely want the release branch to exist - - name: Ensure release branch exists - run: | - echo "MAJOR_VERSION ${MAJOR_VERSION}" - RELEASE_BRANCH=releases/${MAJOR_VERSION} - if git checkout $RELEASE_BRANCH > /dev/null 2>&1; then - echo "Branch $RELEASE_BRANCH already exists" - echo "" - else - echo "Creating $RELEASE_BRANCH branch" - git checkout -b ${RELEASE_BRANCH} ${LATEST_TAG} - git push --set-upstream origin ${RELEASE_BRANCH} - git branch --show-current - echo "" - fi - echo "Returning to branch: ${REF_NAME}" - git checkout ${REF_NAME} + # when the workflow has been manually triggered on main, + # we know that we definitely want the release branch to exist + - name: Ensure release branch exists + run: | + echo "MAJOR_VERSION ${MAJOR_VERSION}" + RELEASE_BRANCH=releases/${MAJOR_VERSION} + if git checkout $RELEASE_BRANCH > /dev/null 2>&1; then + echo "Branch $RELEASE_BRANCH already exists" + echo "" + else + echo "Creating $RELEASE_BRANCH branch" + git checkout -b ${RELEASE_BRANCH} ${LATEST_TAG} + git push --set-upstream origin ${RELEASE_BRANCH} + git branch --show-current + echo "" + fi + echo "Returning to branch: ${REF_NAME}" + git checkout ${REF_NAME} - - name: Update current release branch - if: github.event_name == 'workflow_dispatch' - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - echo SOURCE_BRANCH=${REF_NAME} - echo TARGET_BRANCH=releases/${MAJOR_VERSION} - npx tsx ./pr-checks/update-release-branch.ts \ - --repository-nwo ${{ github.repository }} \ - --source-branch '${{ env.REF_NAME }}' \ - --target-branch 'releases/${{ env.MAJOR_VERSION }}' \ - --is-primary-release \ - --conductor ${GITHUB_ACTOR} + - name: Update current release branch + if: github.event_name == 'workflow_dispatch' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + echo SOURCE_BRANCH=${REF_NAME} + echo TARGET_BRANCH=releases/${MAJOR_VERSION} + npx tsx ./pr-checks/update-release-branch.ts \ + --repository-nwo ${{ github.repository }} \ + --source-branch '${{ env.REF_NAME }}' \ + --target-branch 'releases/${{ env.MAJOR_VERSION }}' \ + --is-primary-release \ + --conductor ${GITHUB_ACTOR} backport: + name: "Create backport" timeout-minutes: 45 - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 environment: Automation needs: [prepare] if: ${{ (github.event_name == 'push') && needs.prepare.outputs.backport_target_branches != '[]' }} @@ -93,28 +94,28 @@ jobs: contents: write # needed to push commits pull-requests: write # needed to create pull request steps: - - name: Generate token - uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 - id: app-token - with: - app-id: ${{ vars.AUTOMATION_APP_ID }} - private-key: ${{ secrets.AUTOMATION_PRIVATE_KEY }} + - name: Generate token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + id: app-token + with: + app-id: ${{ vars.AUTOMATION_APP_ID }} + private-key: ${{ secrets.AUTOMATION_PRIVATE_KEY }} - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 # Need full history for calculation of diffs - token: ${{ steps.app-token.outputs.token }} - - uses: ./.github/actions/release-initialise + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 # Need full history for calculation of diffs + token: ${{ steps.app-token.outputs.token }} + - uses: ./.github/actions/release-initialise - - name: Update older release branch - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - echo SOURCE_BRANCH=${SOURCE_BRANCH} - echo TARGET_BRANCH=${TARGET_BRANCH} - npx tsx ./pr-checks/update-release-branch.ts \ - --repository-nwo ${{ github.repository }} \ - --source-branch ${SOURCE_BRANCH} \ - --target-branch ${TARGET_BRANCH} \ - --conductor ${GITHUB_ACTOR} + - name: Update older release branch + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + echo SOURCE_BRANCH=${SOURCE_BRANCH} + echo TARGET_BRANCH=${TARGET_BRANCH} + npx tsx ./pr-checks/update-release-branch.ts \ + --repository-nwo ${{ github.repository }} \ + --source-branch ${SOURCE_BRANCH} \ + --target-branch ${TARGET_BRANCH} \ + --conductor ${GITHUB_ACTOR} diff --git a/.github/workflows/update-supported-enterprise-server-versions.yml b/.github/workflows/update-supported-enterprise-server-versions.yml index ee2649ad0e..90e3e991a9 100644 --- a/.github/workflows/update-supported-enterprise-server-versions.yml +++ b/.github/workflows/update-supported-enterprise-server-versions.yml @@ -26,10 +26,10 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 - cache: 'npm' + cache: "npm" - name: Install dependencies run: npm ci diff --git a/.npmrc b/.npmrc index 4eae7876ff..807d252539 100644 --- a/.npmrc +++ b/.npmrc @@ -1 +1,2 @@ lockfile-version=3 +min-release-age=7 diff --git a/.vscode/settings.json b/.vscode/settings.json index f417dd2a6e..3413d182e3 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -7,19 +7,28 @@ // transpiled JavaScript "build": true, "lib": true, + + // exclude "tests" by default because it causes VSCode to start language-specific extensions + // that are not typically needed during development (or indeed may not work correctly) + "tests": true }, "search.exclude": { "**/node_modules": true, "build": true, - "lib": true, + "lib": true }, // Installing a new Node package often triggers VS Code's git limit warnings as there is typically // an intermediate stage where many files are modified. This setting suppresses these warnings. "git.ignoreLimitWarning": true, // Use the vendored TypeScript version to have a consistent development experience across // machines. - "typescript.tsdk": "node_modules/typescript/lib", + "js/ts.tsdk.path": "node_modules/typescript/lib", "[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, + "[yaml]": { + "editor.tabSize": 2, + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "prettier.prettierPath": "./node_modules/prettier" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 54dd1bcd07..2aa6b37e6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,48 @@ See the [releases page](https://github.com/github/codeql-action/releases) for th No user facing changes. +## 4.39.2 - 03 Nov 2026 + +- Update default CodeQL bundle version to [2.27.4](https://github.com/github/codeql-action/releases/tag/codeql-bundle-v2.27.4). [#4284](https://github.com/github/codeql-action/pull/4284) +- _Upcoming breaking change_: CodeQL version 2.22.3 and earlier were discontinued on 16 October 2026 alongside GitHub Enterprise Server 3.18, and will be unsupported by the next minor release of the CodeQL Action. Added a deprecation warning for customers using these versions of CodeQL. [#4266](https://github.com/github/codeql-action/pull/4266) +- Starting with macOS 27 and Xcode 27, traced analyses are unsupported. See [this blog post for more information](https://github.blog/changelog/2026-10-19-codeql-changes-for-macos-27-xcode-27-and-swift-6-4/). The CodeQL Action will now try to identify if a workflow is about to perform a traced analysis on version 27 or above of macOS or Xcode. If so, the CodeQL Action will emit a corresponding warning that will also be visible on the [Tool Status Page](https://docs.github.com/en/code-security/how-tos/find-and-fix-code-vulnerabilities/manage-your-configuration/use-the-tools-status-page-for-code-scanning). This check will be rolled out following this release of the CodeQL Action. [#4221](https://github.com/github/codeql-action/pull/4221) +- The undocumented TRAP cache cleanup feature that could be enabled using the `CODEQL_ACTION_CLEANUP_TRAP_CACHES` environment variable has been removed, as announced in the release notes for CodeQL Action 4.35.2. The `analyze` Action now warns if this environment variable is set. If you used TRAP cache cleanup to limit Actions cache usage, we recommend disabling TRAP caching by passing the `trap-caching: false` input to the `init` Action. [#4243](https://github.com/github/codeql-action/pull/4243) + +## 4.39.1 - 21 Oct 2026 + +- Update default CodeQL bundle version to [2.27.3](https://github.com/github/codeql-action/releases/tag/codeql-bundle-v2.27.3). [#4256](https://github.com/github/codeql-action/pull/4256) + +## 4.39.0 - 15 Oct 2026 + +- _Breaking change_: Bump the minimum required CodeQL bundle version to 2.20.7. [#4205](https://github.com/github/codeql-action/pull/4205) +- The `codeql-action/analyze` step now validates that a correct argument for the `checkout_path` input has been provided. The `checkout_path` input must be set to the path where the repository that is being analyzed is checked out at on the runner, if that path is something other than the workspace root. If the path does not point to a repository checkout or is different from the path that was used by `codeql-action/init`, then the CodeQL Action now produces a warning. [#4148](https://github.com/github/codeql-action/pull/4148) +- Resolved an issue with third-party caching implementations that prevented caches from being restored correctly. [#4206](https://github.com/github/codeql-action/pull/4206) +- The `codeql-action/start-proxy` step that is used in Code Scanning Default Setup now finds CodeQL releases using the same logic as `codeql-action/init`. This primarily benefits customers who are using GitHub instances other than `github.com` where the `codeql-action/start-proxy` step may previously have been unable to locate recent releases and ended up using outdated versions of the private registry authentication proxy as a result. [#4198](https://github.com/github/codeql-action/pull/4198) + +## 4.38.3 - 08 Oct 2026 + +- _Upcoming breaking change_: CodeQL version 2.21.2 and earlier were discontinued on 24 September 2026 alongside GitHub Enterprise Server 3.17, and will be unsupported by the next minor release of the CodeQL Action. Added a deprecation warning for customers using these versions of CodeQL. [#4188](https://github.com/github/codeql-action/pull/4188) +- Update default CodeQL bundle version to [2.27.2](https://github.com/github/codeql-action/releases/tag/codeql-bundle-v2.27.2). [#4203](https://github.com/github/codeql-action/pull/4203) +- Fixed a bug where the decision of whether to use a per-language bundle did not account for custom configurations that reference queries outside of compiled CodeQL packs. This issue was caught during internal testing and did not affect any customer repositories. We will resume the roll out of per-language bundles in the coming weeks. [#4184](https://github.com/github/codeql-action/pull/4184) + +## 4.38.2 - 24 Sept 2026 + +- Update default CodeQL bundle version to [2.27.1](https://github.com/github/codeql-action/releases/tag/codeql-bundle-v2.27.1). [#4160](https://github.com/github/codeql-action/pull/4160) + +## 4.38.1 - 18 Sept 2026 + +- The CodeQL Action now has experimental support for CodeQL releases for which per-language bundles are available. Per-language bundles support analysis for a single language and are therefore smaller than the combined bundles that allow analysis for all supported languages. As a result, per-language bundles take up less space on disk and are faster to download. We expect to roll this change out to everyone in the coming weeks. [#4146](https://github.com/github/codeql-action/pull/4146) + +## 4.38.0 - 09 Sept 2026 + +- On GitHub-hosted runners, the CodeQL Action now deletes unused CodeQL bundles from the toolcache before downloading a different bundle, which frees up disk space for the analysis. We expect to roll this change out to everyone in September. [#4124](https://github.com/github/codeql-action/pull/4124) +- The CodeQL Action now supports CodeQL releases that are compatible with Linux Arm64 and downloads the native `linux-arm64` CodeQL bundle when available. [#4072](https://github.com/github/codeql-action/pull/4072) +- Update default CodeQL bundle version to [2.27.0](https://github.com/github/codeql-action/releases/tag/codeql-bundle-v2.27.0). [#4129](https://github.com/github/codeql-action/pull/4129) + +## 4.37.9 - 26 Aug 2026 + +- Update default CodeQL bundle version to [2.26.4](https://github.com/github/codeql-action/releases/tag/codeql-bundle-v2.26.4). [#4106](https://github.com/github/codeql-action/pull/4106) + ## 4.37.8 - 21 Aug 2026 No user facing changes. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b67ccb13b7..1436c9bb3c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -53,6 +53,7 @@ Here are a few things you can do that will increase the likelihood of your pull - Write tests. - Keep your change as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests. - Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html). +- For user-facing changes, add a change-note file. See [unreleased-change-notes/README.md](unreleased-change-notes/README.md). ## Releasing (write access required) @@ -60,10 +61,13 @@ Here are a few things you can do that will increase the likelihood of your pull This workflow goes through the pull requests that have been merged to `main` since the last release, creates a changelog, then opens a pull request to merge the changes since the last release into the `releases/v3` release branch. You can start a release by triggering this workflow via [workflow dispatch](https://github.com/github/codeql-action/actions/workflows/update-release-branch.yml). -1. The workflow run will open a pull request titled "Merge main into releases/v3". Follow the steps on the checklist in the pull request. Once you've checked off all but the last two of these, approve the PR and automerge it. +1. The workflow run will open a pull request titled "Merge main into releases/v3". Follow the steps on the checklist in the pull request. Once you've checked off all but the last two of these, approve the PR and automerge it **with a merge commit** (`gh pr merge --merge`). 1. When the "Merge main into releases/v3" pull request is merged into the `releases/v3` branch, a mergeback pull request to `main` will be automatically created. This mergeback pull request incorporates the changelog updates into `main`, tags the release using the merge commit of the "Merge main into releases/v3" pull request, and bumps the patch version of the CodeQL Action. 1. If a backport to an older major version is required, a pull request targeting that version's branch will also be automatically created. -1. Approve the mergeback and backport pull request (if applicable) and automerge them. +1. Approve the mergeback and backport pull request (if applicable) and automerge them **with a merge commit** (`gh pr merge --merge`). + + > [!NOTE] + > The release, mergeback, and backport pull requests must always be merged with a merge commit — **never squash or rebase**. The mergeback tags the release using the merge commit of the "Merge main into releases/v3" pull request, so squashing or rebasing breaks tagging and the branch linkage the release automation relies on. Once the mergeback and backport pull request have been merged, the release is complete. diff --git a/README.md b/README.md index 530c028f97..d738adcab6 100644 --- a/README.md +++ b/README.md @@ -72,12 +72,10 @@ We typically release new minor versions of the CodeQL Action and Bundle when a n | Minimum CodeQL Action | Minimum CodeQL Bundle Version | GitHub Environment | Notes | |-----------------------|-------------------------------|--------------------|-------| +| `v4.36.2` | `2.25.6` | Enterprise Server 3.22 | | | `v4.33.0` | `2.24.3` | Enterprise Server 3.21 | | | `v4.31.10` | `2.23.9` | Enterprise Server 3.20 | | | `v3.29.11` | `2.22.4` | Enterprise Server 3.19 | | -| `v3.28.21` | `2.21.3` | Enterprise Server 3.18 | | -| `v3.28.12` | `2.20.7` | Enterprise Server 3.17 | | -| `v3.28.6` | `2.20.3` | Enterprise Server 3.16 | | See the full list of GHES release and deprecation dates at [GitHub Enterprise Server releases](https://docs.github.com/en/enterprise-server/admin/all-releases#releases-of-github-enterprise-server). diff --git a/action.yml b/action.yml index 87c4974ea9..b410533bec 100644 --- a/action.yml +++ b/action.yml @@ -1,10 +1,10 @@ -name: 'CodeQL: Stub' +name: "CodeQL: Stub" description: "Stub: Don't use this action directly. Read [the documentation](https://docs.github.com/en/code-security/code-scanning/introduction-to-code-scanning/about-code-scanning-with-codeql) instead." -author: 'GitHub' +author: "GitHub" runs: - using: 'composite' + using: "composite" steps: - - name: 'Stub' + - name: "Stub" run: | echo 'This is a stub. Read [the documentation](https://docs.github.com/en/code-security/code-scanning/introduction-to-code-scanning/about-code-scanning-with-codeql) instead.' exit 1 diff --git a/autobuild/action.yml b/autobuild/action.yml index b87da541d6..3191149146 100644 --- a/autobuild/action.yml +++ b/autobuild/action.yml @@ -1,6 +1,6 @@ -name: 'CodeQL: Autobuild' -description: 'Attempt to automatically build the code. Only used for analyzing languages that require a build. Use the `build-mode: autobuild` input in the `init` action instead.' -author: 'GitHub' +name: "CodeQL: Autobuild" +description: "Attempt to automatically build the code. Only used for analyzing languages that require a build. Use the `build-mode: autobuild` input in the `init` action instead." +author: "GitHub" inputs: token: description: "GitHub token to use for authenticating with this instance of GitHub. The token needs the `security-events: write` permission." @@ -16,4 +16,4 @@ inputs: required: false runs: using: node24 - main: '../lib/autobuild-entry.js' + main: "../lib/autobuild-entry.js" diff --git a/ava.setup.mjs b/ava.setup.mjs index e6c370e01b..b405991125 100644 --- a/ava.setup.mjs +++ b/ava.setup.mjs @@ -1,3 +1,4 @@ import pkg from "./package.json" with { type: "json" }; globalThis.__CODEQL_ACTION_VERSION__ = pkg.version; +globalThis.__CODEQL_ACTION_TEST_ENV__ = "unit-test"; diff --git a/build.mjs b/build.mjs index a0c3c06189..ecbe5be84d 100644 --- a/build.mjs +++ b/build.mjs @@ -78,7 +78,7 @@ const UPLOAD_LIB_SRC = "./src/upload-lib"; * * The virtual module additionally re-exports `upload-lib` under the `uploadLib` namespace so that * external consumers can access it via the small `lib/upload-lib.js` stub emitted below. - * + * * A tiny stub file is emitted for each Action entrypoint, and one for `upload-lib`. Each stub * imports the shared bundle and calls/re-exports from the respective entry point. * @@ -212,6 +212,7 @@ const context = await esbuild.context({ target: ["node20"], define: { __CODEQL_ACTION_VERSION__: JSON.stringify(pkg.version), + __CODEQL_ACTION_TEST_ENV__: JSON.stringify(""), }, metafile: true, }); diff --git a/eslint.config.mjs b/eslint.config.mjs index 34fe49a9df..c3f288c0d0 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -140,6 +140,17 @@ export default [ "no-async-foreach/no-async-foreach": "error", "no-sequences": "error", "no-shadow": "off", + + // A basic check that we don't use `exportVariable` from `@actions/core`. + "no-restricted-syntax": [ + "error", + { + selector: "MemberExpression[property.name='exportVariable']", + message: + "Use the `export` method of an `Env` instance or `exportEnvVar` from `environment.ts` instead.", + }, + ], + // This is overly restrictive with unsetting `EnvVar`s "@typescript-eslint/no-dynamic-delete": "off", "@typescript-eslint/no-shadow": "error", @@ -157,6 +168,15 @@ export default [ ], }, }, + { + files: ["src/environment.ts"], + + // We allow `exportVariable` from `@actions/core` to be used in this file + // since it defines the wrapper around it that other modules use. + rules: { + "no-restricted-syntax": "off", + }, + }, { files: ["**/*.ts", "**/*.js"], diff --git a/init/action.yml b/init/action.yml index 1b64e8d2a3..b6721a8c7b 100644 --- a/init/action.yml +++ b/init/action.yml @@ -1,6 +1,6 @@ -name: 'CodeQL: Init' -description: 'Set up CodeQL' -author: 'GitHub' +name: "CodeQL: Init" +description: "Set up CodeQL" +author: "GitHub" inputs: tools: description: >- @@ -56,7 +56,7 @@ inputs: - `code-scanning`: The default, security-focused analysis. - `code-quality`: Analysis focused on code quality. This must be enabled in conjunction with `code-scanning`. - default: 'code-scanning' + default: "code-scanning" required: true token: description: GitHub token to use for authenticating with this instance of GitHub. To download custom packs from multiple registries, use the registries input. @@ -100,7 +100,7 @@ inputs: description: Comma-separated list of additional queries to run. By default, this overrides the same setting in a configuration file; prefix with "+" to use both sets of queries. required: false quality-queries: - description: '[Internal] DEPRECATED. Comma-separated list of code quality queries to run.' + description: "[Internal] DEPRECATED. Comma-separated list of code quality queries to run." required: false packs: description: >- @@ -140,7 +140,7 @@ inputs: This will result in more output being produced which may be useful when debugging certain issues. Debugging mode is enabled automatically when step debug logging is turned on. required: false - default: 'false' + default: "false" debug-artifact-name: description: >- The name of the artifact to store debugging information in. @@ -153,7 +153,10 @@ inputs: required: false trap-caching: description: >- - Explicitly enable or disable TRAP caching rather than respecting the feature flag for it. + Explicitly enable or disable TRAP caching instead of using the automatically determined default. + TRAP caching is disabled by default when improved incremental analysis is enabled, + because improved incremental analysis of a pull request only extracts changed files, + which rarely benefit from TRAP caching. required: false dependency-caching: description: >- @@ -164,6 +167,13 @@ inputs: [Internal] The ID of the check run, as provided by the Actions runtime environment. Do not set this value manually. default: ${{ job.check_run_id }} required: false + job-status: + description: >- + [Internal] The status of the job, as provided by the Actions runtime environment. This is how the + post step learns whether the job as a whole succeeded, failed, or was cancelled. Do not set this + value manually. + default: ${{ job.status }} + required: false outputs: codeql-path: description: The path of the CodeQL binary used for analysis @@ -171,5 +181,5 @@ outputs: description: The version of the CodeQL binary used for analysis runs: using: node24 - main: '../lib/init-entry.js' - post: '../lib/init-post-entry.js' + main: "../lib/init-entry.js" + post: "../lib/init-post-entry.js" diff --git a/lib/defaults.json b/lib/defaults.json index b5d9f13644..cfa3f6c1c7 100644 --- a/lib/defaults.json +++ b/lib/defaults.json @@ -1,6 +1,6 @@ { - "bundleVersion": "codeql-bundle-v2.26.3", - "cliVersion": "2.26.3", - "priorBundleVersion": "codeql-bundle-v2.26.2", - "priorCliVersion": "2.26.2" + "bundleVersion": "codeql-bundle-v2.27.4", + "cliVersion": "2.27.4", + "priorBundleVersion": "codeql-bundle-v2.27.3", + "priorCliVersion": "2.27.3" } diff --git a/lib/entry-points.js b/lib/entry-points.js index 497e44d9d3..952c615417 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -117,11 +117,11 @@ var require_command = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.issueCommand = issueCommand; exports2.issue = issue; - var os7 = __importStar2(require("os")); + var os8 = __importStar2(require("os")); var utils_1 = require_utils(); function issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os7.EOL); + process.stdout.write(cmd.toString() + os8.EOL); } function issue(name, message = "") { issueCommand(name, {}, message); @@ -213,18 +213,18 @@ var require_file_command = __commonJS({ exports2.issueFileCommand = issueFileCommand; exports2.prepareKeyValueMessage = prepareKeyValueMessage; var crypto3 = __importStar2(require("crypto")); - var fs32 = __importStar2(require("fs")); - var os7 = __importStar2(require("os")); + var fs34 = __importStar2(require("fs")); + var os8 = __importStar2(require("os")); var utils_1 = require_utils(); function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); } - if (!fs32.existsSync(filePath)) { + if (!fs34.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } - fs32.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os7.EOL}`, { + fs34.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os8.EOL}`, { encoding: "utf8" }); } @@ -237,7 +237,7 @@ var require_file_command = __commonJS({ if (convertedValue.includes(delimiter)) { throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); } - return `${key}<<${delimiter}${os7.EOL}${convertedValue}${os7.EOL}${delimiter}`; + return `${key}<<${delimiter}${os8.EOL}${convertedValue}${os8.EOL}${delimiter}`; } } }); @@ -264,7 +264,7 @@ var require_proxy = __commonJS({ if (proxyVar) { try { return new DecodedURL(proxyVar); - } catch (_a2) { + } catch (_a6) { if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) return new DecodedURL(`http://${proxyVar}`); } @@ -333,7 +333,7 @@ var require_tunnel = __commonJS({ var https3 = require("https"); var events = require("events"); var assert = require("assert"); - var util3 = require("util"); + var util4 = require("util"); exports2.httpOverHttp = httpOverHttp; exports2.httpsOverHttp = httpsOverHttp; exports2.httpOverHttps = httpOverHttps; @@ -383,7 +383,7 @@ var require_tunnel = __commonJS({ self2.removeSocket(socket); }); } - util3.inherits(TunnelingAgent, events.EventEmitter); + util4.inherits(TunnelingAgent, events.EventEmitter); TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { var self2 = this; var options = mergeOptions({ request: req }, self2.options, toOptions(host, port, localAddress)); @@ -563,11 +563,13 @@ var require_tunnel2 = __commonJS({ // node_modules/undici/lib/core/symbols.js var require_symbols = __commonJS({ "node_modules/undici/lib/core/symbols.js"(exports2, module2) { + "use strict"; module2.exports = { kClose: /* @__PURE__ */ Symbol("close"), kDestroy: /* @__PURE__ */ Symbol("destroy"), kDispatch: /* @__PURE__ */ Symbol("dispatch"), kUrl: /* @__PURE__ */ Symbol("url"), + kRedirectCacheControl: /* @__PURE__ */ Symbol("redirect cache control"), kWriting: /* @__PURE__ */ Symbol("writing"), kResuming: /* @__PURE__ */ Symbol("resuming"), kQueue: /* @__PURE__ */ Symbol("queue"), @@ -617,7 +619,6 @@ var require_symbols = __commonJS({ kMaxRequests: /* @__PURE__ */ Symbol("maxRequestsPerClient"), kProxy: /* @__PURE__ */ Symbol("proxy agent options"), kCounter: /* @__PURE__ */ Symbol("socket request counter"), - kInterceptors: /* @__PURE__ */ Symbol("dispatch interceptors"), kMaxResponseSize: /* @__PURE__ */ Symbol("max response size"), kHTTP2Session: /* @__PURE__ */ Symbol("http2Session"), kHTTP2SessionState: /* @__PURE__ */ Symbol("http2Session state"), @@ -626,9 +627,245 @@ var require_symbols = __commonJS({ kListeners: /* @__PURE__ */ Symbol("listeners"), kHTTPContext: /* @__PURE__ */ Symbol("http context"), kMaxConcurrentStreams: /* @__PURE__ */ Symbol("max concurrent streams"), + kHTTP2InitialWindowSize: /* @__PURE__ */ Symbol("http2 initial window size"), + kHTTP2ConnectionWindowSize: /* @__PURE__ */ Symbol("http2 connection window size"), + kEnableConnectProtocol: /* @__PURE__ */ Symbol("http2session connect protocol"), + kRemoteSettings: /* @__PURE__ */ Symbol("http2session remote settings"), + kHTTP2Stream: /* @__PURE__ */ Symbol("http2session client stream"), + kPingInterval: /* @__PURE__ */ Symbol("ping interval"), kNoProxyAgent: /* @__PURE__ */ Symbol("no proxy agent"), kHttpProxyAgent: /* @__PURE__ */ Symbol("http proxy agent"), - kHttpsProxyAgent: /* @__PURE__ */ Symbol("https proxy agent") + kHttpsProxyAgent: /* @__PURE__ */ Symbol("https proxy agent"), + kSocks5ProxyAgent: /* @__PURE__ */ Symbol("socks5 proxy agent") + }; + } +}); + +// node_modules/undici/lib/util/timers.js +var require_timers = __commonJS({ + "node_modules/undici/lib/util/timers.js"(exports2, module2) { + "use strict"; + var fastNow = 0; + var RESOLUTION_MS = 1e3; + var TICK_MS = (RESOLUTION_MS >> 1) - 1; + var fastNowTimeout; + var kFastTimer = /* @__PURE__ */ Symbol("kFastTimer"); + var fastTimers = []; + var NOT_IN_LIST = -2; + var TO_BE_CLEARED = -1; + var PENDING = 0; + var ACTIVE = 1; + function onTick() { + fastNow += TICK_MS; + let idx = 0; + let len = fastTimers.length; + while (idx < len) { + const timer = fastTimers[idx]; + if (timer._state === PENDING) { + 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; + if (--len !== 0) { + fastTimers[idx] = fastTimers[len]; + } + } else { + ++idx; + } + } + fastTimers.length = len; + if (fastTimers.length !== 0) { + refreshTimeout(); + } + } + function refreshTimeout() { + if (fastNowTimeout?.refresh) { + fastNowTimeout.refresh(); + } else { + clearTimeout(fastNowTimeout); + fastNowTimeout = setTimeout(onTick, TICK_MS); + fastNowTimeout?.unref(); + } + } + var FastTimer = class { + [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, delay2, arg) { + this._onTimeout = callback; + this._idleTimeout = delay2; + 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() { + if (this._state === NOT_IN_LIST) { + fastTimers.push(this); + } + if (!fastNowTimeout || fastTimers.length === 1) { + refreshTimeout(); + } + this._state = PENDING; + } + /** + * The `clear` method cancels the timer, preventing it from executing. + * + * @returns {void} + * @private + */ + clear() { + this._state = TO_BE_CLEARED; + this._idleStart = -1; + } + }; + module2.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, delay2, arg) { + return delay2 <= RESOLUTION_MS ? setTimeout(callback, delay2, arg) : new FastTimer(callback, delay2, arg); + }, + /** + * The clearTimeout method cancels an instantiated Timer previously created + * by calling setTimeout. + * + * @param {NodeJS.Timeout|FastTimer} timeout + */ + clearTimeout(timeout) { + if (timeout[kFastTimer]) { + timeout.clear(); + } 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, delay2, arg) { + return new FastTimer(callback, delay2, 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(delay2 = 0) { + fastNow += delay2 - 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 }; } }); @@ -639,15 +876,17 @@ var require_errors = __commonJS({ "use strict"; var kUndiciError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR"); var UndiciError = class extends Error { - constructor(message) { - super(message); + constructor(message, options) { + super(message, options); this.name = "UndiciError"; this.code = "UND_ERR"; } - static [Symbol.hasInstance](instance) { - return instance && instance[kUndiciError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kUndiciError] === true; + } + get [kUndiciError]() { + return true; } - [kUndiciError] = true; }; var kConnectTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_CONNECT_TIMEOUT"); var ConnectTimeoutError = class extends UndiciError { @@ -657,10 +896,12 @@ var require_errors = __commonJS({ this.message = message || "Connect Timeout Error"; this.code = "UND_ERR_CONNECT_TIMEOUT"; } - static [Symbol.hasInstance](instance) { - return instance && instance[kConnectTimeoutError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kConnectTimeoutError] === true; + } + get [kConnectTimeoutError]() { + return true; } - [kConnectTimeoutError] = true; }; var kHeadersTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HEADERS_TIMEOUT"); var HeadersTimeoutError = class extends UndiciError { @@ -670,10 +911,12 @@ var require_errors = __commonJS({ this.message = message || "Headers Timeout Error"; this.code = "UND_ERR_HEADERS_TIMEOUT"; } - static [Symbol.hasInstance](instance) { - return instance && instance[kHeadersTimeoutError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kHeadersTimeoutError] === true; + } + get [kHeadersTimeoutError]() { + return true; } - [kHeadersTimeoutError] = true; }; var kHeadersOverflowError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HEADERS_OVERFLOW"); var HeadersOverflowError = class extends UndiciError { @@ -683,10 +926,12 @@ var require_errors = __commonJS({ this.message = message || "Headers Overflow Error"; this.code = "UND_ERR_HEADERS_OVERFLOW"; } - static [Symbol.hasInstance](instance) { - return instance && instance[kHeadersOverflowError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kHeadersOverflowError] === true; + } + get [kHeadersOverflowError]() { + return true; } - [kHeadersOverflowError] = true; }; var kBodyTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_BODY_TIMEOUT"); var BodyTimeoutError = class extends UndiciError { @@ -696,27 +941,12 @@ var require_errors = __commonJS({ this.message = message || "Body Timeout Error"; this.code = "UND_ERR_BODY_TIMEOUT"; } - static [Symbol.hasInstance](instance) { - return instance && instance[kBodyTimeoutError] === true; - } - [kBodyTimeoutError] = true; - }; - var kResponseStatusCodeError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RESPONSE_STATUS_CODE"); - var ResponseStatusCodeError = class 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](instance8) { + return instance8 && instance8[kBodyTimeoutError] === true; } - static [Symbol.hasInstance](instance) { - return instance && instance[kResponseStatusCodeError] === true; + get [kBodyTimeoutError]() { + return true; } - [kResponseStatusCodeError] = true; }; var kInvalidArgumentError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INVALID_ARG"); var InvalidArgumentError = class extends UndiciError { @@ -726,10 +956,12 @@ var require_errors = __commonJS({ this.message = message || "Invalid Argument Error"; this.code = "UND_ERR_INVALID_ARG"; } - static [Symbol.hasInstance](instance) { - return instance && instance[kInvalidArgumentError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kInvalidArgumentError] === true; + } + get [kInvalidArgumentError]() { + return true; } - [kInvalidArgumentError] = true; }; var kInvalidReturnValueError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INVALID_RETURN_VALUE"); var InvalidReturnValueError = class extends UndiciError { @@ -739,36 +971,42 @@ var require_errors = __commonJS({ this.message = message || "Invalid Return Value Error"; this.code = "UND_ERR_INVALID_RETURN_VALUE"; } - static [Symbol.hasInstance](instance) { - return instance && instance[kInvalidReturnValueError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kInvalidReturnValueError] === true; + } + get [kInvalidReturnValueError]() { + return true; } - [kInvalidReturnValueError] = true; }; var kAbortError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_ABORT"); - var AbortError = class extends UndiciError { + var AbortError2 = class 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; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kAbortError] === true; + } + get [kAbortError]() { + return true; } - [kAbortError] = true; }; var kRequestAbortedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_ABORTED"); - var RequestAbortedError = class extends AbortError { + var RequestAbortedError = class extends AbortError2 { 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; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kRequestAbortedError] === true; + } + get [kRequestAbortedError]() { + return true; } - [kRequestAbortedError] = true; }; var kInformationalError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INFO"); var InformationalError = class extends UndiciError { @@ -778,10 +1016,12 @@ var require_errors = __commonJS({ this.message = message || "Request information"; this.code = "UND_ERR_INFO"; } - static [Symbol.hasInstance](instance) { - return instance && instance[kInformationalError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kInformationalError] === true; + } + get [kInformationalError]() { + return true; } - [kInformationalError] = true; }; var kRequestContentLengthMismatchError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH"); var RequestContentLengthMismatchError = class extends UndiciError { @@ -791,10 +1031,12 @@ var require_errors = __commonJS({ 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; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kRequestContentLengthMismatchError] === true; + } + get [kRequestContentLengthMismatchError]() { + return true; } - [kRequestContentLengthMismatchError] = true; }; var kResponseContentLengthMismatchError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH"); var ResponseContentLengthMismatchError = class extends UndiciError { @@ -804,10 +1046,12 @@ var require_errors = __commonJS({ 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; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kResponseContentLengthMismatchError] === true; + } + get [kResponseContentLengthMismatchError]() { + return true; } - [kResponseContentLengthMismatchError] = true; }; var kClientDestroyedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_DESTROYED"); var ClientDestroyedError = class extends UndiciError { @@ -817,10 +1061,12 @@ var require_errors = __commonJS({ this.message = message || "The client is destroyed"; this.code = "UND_ERR_DESTROYED"; } - static [Symbol.hasInstance](instance) { - return instance && instance[kClientDestroyedError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kClientDestroyedError] === true; + } + get [kClientDestroyedError]() { + return true; } - [kClientDestroyedError] = true; }; var kClientClosedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_CLOSED"); var ClientClosedError = class extends UndiciError { @@ -830,10 +1076,12 @@ var require_errors = __commonJS({ this.message = message || "The client is closed"; this.code = "UND_ERR_CLOSED"; } - static [Symbol.hasInstance](instance) { - return instance && instance[kClientClosedError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kClientClosedError] === true; + } + get [kClientClosedError]() { + return true; } - [kClientClosedError] = true; }; var kSocketError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_SOCKET"); var SocketError = class extends UndiciError { @@ -844,10 +1092,12 @@ var require_errors = __commonJS({ this.code = "UND_ERR_SOCKET"; this.socket = socket; } - static [Symbol.hasInstance](instance) { - return instance && instance[kSocketError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kSocketError] === true; + } + get [kSocketError]() { + return true; } - [kSocketError] = true; }; var kNotSupportedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_NOT_SUPPORTED"); var NotSupportedError = class extends UndiciError { @@ -857,10 +1107,12 @@ var require_errors = __commonJS({ this.message = message || "Not supported error"; this.code = "UND_ERR_NOT_SUPPORTED"; } - static [Symbol.hasInstance](instance) { - return instance && instance[kNotSupportedError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kNotSupportedError] === true; + } + get [kNotSupportedError]() { + return true; } - [kNotSupportedError] = true; }; var kBalancedPoolMissingUpstreamError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_BPL_MISSING_UPSTREAM"); var BalancedPoolMissingUpstreamError = class extends UndiciError { @@ -870,10 +1122,12 @@ var require_errors = __commonJS({ 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; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kBalancedPoolMissingUpstreamError] === true; + } + get [kBalancedPoolMissingUpstreamError]() { + return true; } - [kBalancedPoolMissingUpstreamError] = true; }; var kHTTPParserError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HTTP_PARSER"); var HTTPParserError = class extends Error { @@ -883,10 +1137,12 @@ var require_errors = __commonJS({ this.code = code ? `HPE_${code}` : void 0; this.data = data ? data.toString() : void 0; } - static [Symbol.hasInstance](instance) { - return instance && instance[kHTTPParserError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kHTTPParserError] === true; + } + get [kHTTPParserError]() { + return true; } - [kHTTPParserError] = true; }; var kResponseExceededMaxSizeError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE"); var ResponseExceededMaxSizeError = class extends UndiciError { @@ -896,10 +1152,12 @@ var require_errors = __commonJS({ 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; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kResponseExceededMaxSizeError] === true; + } + get [kResponseExceededMaxSizeError]() { + return true; } - [kResponseExceededMaxSizeError] = true; }; var kRequestRetryError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_REQ_RETRY"); var RequestRetryError = class extends UndiciError { @@ -912,40 +1170,69 @@ var require_errors = __commonJS({ this.data = data; this.headers = headers; } - static [Symbol.hasInstance](instance) { - return instance && instance[kRequestRetryError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kRequestRetryError] === true; + } + get [kRequestRetryError]() { + return true; } - [kRequestRetryError] = true; }; var kResponseError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RESPONSE"); var ResponseError = class extends UndiciError { - constructor(message, code, { headers, data }) { + constructor(message, code, { headers, body }) { super(message); this.name = "ResponseError"; this.message = message || "Response error"; this.code = "UND_ERR_RESPONSE"; this.statusCode = code; - this.data = data; + this.body = body; this.headers = headers; } - static [Symbol.hasInstance](instance) { - return instance && instance[kResponseError] === true; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kResponseError] === true; + } + get [kResponseError]() { + return true; } - [kResponseError] = true; }; var kSecureProxyConnectionError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_PRX_TLS"); var SecureProxyConnectionError = class extends UndiciError { - constructor(cause, message, options) { - super(message, { cause, ...options ?? {} }); + 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; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kSecureProxyConnectionError] === true; + } + get [kSecureProxyConnectionError]() { + return true; + } + }; + var kMaxOriginsReachedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_MAX_ORIGINS_REACHED"); + var MaxOriginsReachedError = class extends UndiciError { + constructor(message) { + super(message); + this.name = "MaxOriginsReachedError"; + this.message = message || "Maximum allowed origins reached"; + this.code = "UND_ERR_MAX_ORIGINS_REACHED"; + } + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kMaxOriginsReachedError] === true; + } + get [kMaxOriginsReachedError]() { + return true; + } + }; + var Socks5ProxyError = class extends UndiciError { + constructor(message, code) { + super(message); + this.name = "Socks5ProxyError"; + this.message = message || "SOCKS5 proxy error"; + this.code = code || "UND_ERR_SOCKS5"; } - [kSecureProxyConnectionError] = true; }; var kMessageSizeExceededError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED"); var MessageSizeExceededError = class extends UndiciError { @@ -955,15 +1242,15 @@ var require_errors = __commonJS({ 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; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kMessageSizeExceededError] === true; } get [kMessageSizeExceededError]() { return true; } }; module2.exports = { - AbortError, + AbortError: AbortError2, HTTPParserError, UndiciError, HeadersTimeoutError, @@ -971,7 +1258,6 @@ var require_errors = __commonJS({ BodyTimeoutError, RequestContentLengthMismatchError, ConnectTimeoutError, - ResponseStatusCodeError, InvalidArgumentError, InvalidReturnValueError, RequestAbortedError, @@ -986,6 +1272,8 @@ var require_errors = __commonJS({ RequestRetryError, ResponseError, SecureProxyConnectionError, + MaxOriginsReachedError, + Socks5ProxyError, MessageSizeExceededError }; } @@ -995,113 +1283,126 @@ var require_errors = __commonJS({ var require_constants = __commonJS({ "node_modules/undici/lib/core/constants.js"(exports2, module2) { "use strict"; + var wellknownHeaderNames = ( + /** @type {const} */ + [ + "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" + ] + ); var headerNameLowerCasedRecord = {}; - var 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" - ]; + Object.setPrototypeOf(headerNameLowerCasedRecord, null); + var wellknownHeaderNameBuffers = {}; + Object.setPrototypeOf(wellknownHeaderNameBuffers, null); + function getHeaderNameAsBuffer(header) { + let buffer = wellknownHeaderNameBuffers[header]; + if (buffer === void 0) { + buffer = Buffer.from(header); + } + return buffer; + } for (let i = 0; i < wellknownHeaderNames.length; ++i) { const key = wellknownHeaderNames[i]; const lowerCasedKey = key.toLowerCase(); headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = lowerCasedKey; } - Object.setPrototypeOf(headerNameLowerCasedRecord, null); module2.exports = { wellknownHeaderNames, - headerNameLowerCasedRecord + headerNameLowerCasedRecord, + getHeaderNameAsBuffer }; } }); @@ -1147,6 +1448,7 @@ var require_tree = __commonJS({ /** * @param {string} key * @param {any} value + * @returns {void} */ add(key, value) { const length = key.length; @@ -1187,7 +1489,7 @@ var require_tree = __commonJS({ } /** * @param {Uint8Array} key - * @return {TstNode | null} + * @returns {TstNode | null} */ search(key) { const keylength = key.length; @@ -1218,6 +1520,7 @@ var require_tree = __commonJS({ /** * @param {string} key * @param {any} value + * @returns {void} * */ insert(key, value) { if (this.node === null) { @@ -1228,7 +1531,7 @@ var require_tree = __commonJS({ } /** * @param {Uint8Array} key - * @return {any} + * @returns {any} */ lookup(key) { return this.node?.search(key)?.value ?? null; @@ -1255,14 +1558,13 @@ var require_util = __commonJS({ var { IncomingMessage } = require("node:http"); var stream2 = require("node:stream"); var net = require("node:net"); - var { Blob: Blob2 } = require("node:buffer"); - var nodeUtil = require("node:util"); var { stringify } = require("node:querystring"); var { EventEmitter: EE } = require("node:events"); - var { InvalidArgumentError } = require_errors(); + var timers = require_timers(); + var { InvalidArgumentError, ConnectTimeoutError } = require_errors(); var { headerNameLowerCasedRecord } = require_constants(); var { tree } = require_tree(); - var [nodeMajor, nodeMinor] = process.versions.node.split(".").map((v) => Number(v)); + var [nodeMajor, nodeMinor] = process.versions.node.split(".", 2).map((v) => Number(v)); var BodyAsyncIterable = class { constructor(body) { this[kBody] = body; @@ -1274,6 +1576,8 @@ var require_util = __commonJS({ yield* this[kBody]; } }; + function noop3() { + } function wrapRequestBody(body) { if (isStream2(body)) { if (bodyLength(body) === 0) { @@ -1290,21 +1594,21 @@ var require_util = __commonJS({ return body; } else if (body && typeof body.pipeTo === "function") { return new BodyAsyncIterable(body); - } else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable(body)) { + } else if (body && isFormDataLike(body)) { + return body; + } else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable2(body)) { return new BodyAsyncIterable(body); } else { return body; } } - function nop() { - } function isStream2(obj) { return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function"; } function isBlobLike(object2) { if (object2 === null) { return false; - } else if (object2 instanceof Blob2) { + } else if (object2 instanceof Blob) { return true; } else if (typeof object2 !== "object") { return false; @@ -1313,8 +1617,11 @@ var require_util = __commonJS({ return (sTag === "Blob" || sTag === "File") && ("stream" in object2 && typeof object2.stream === "function" || "arrayBuffer" in object2 && typeof object2.arrayBuffer === "function"); } } - function buildURL(url2, queryParams) { - if (url2.includes("?") || url2.includes("#")) { + function pathHasQueryOrFragment(url2) { + return url2.includes("?") || url2.includes("#"); + } + function serializePathWithQuery(url2, queryParams) { + if (pathHasQueryOrFragment(url2)) { throw new Error('Query params cannot be passed when url already contains "?" or "#".'); } const stringified = stringify(queryParams); @@ -1407,12 +1714,17 @@ var require_util = __commonJS({ function deepClone(obj) { return JSON.parse(JSON.stringify(obj)); } - function isAsyncIterable(obj) { + function isAsyncIterable2(obj) { return !!(obj != null && typeof obj[Symbol.asyncIterator] === "function"); } - function isIterable(obj) { + function isIterable2(obj) { return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function")); } + function hasSafeIterator(obj) { + const prototype = Object.getPrototypeOf(obj); + const ownIterator = Object.prototype.hasOwnProperty.call(obj, Symbol.iterator); + return ownIterator || prototype != null && prototype !== Object.prototype && typeof obj[Symbol.iterator] === "function"; + } function bodyLength(body) { if (body == null) { return 0; @@ -1449,7 +1761,7 @@ var require_util = __commonJS({ } var KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/; function parseKeepAliveTimeout(val) { - const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR); + const m = val.match(KEEPALIVE_TIMEOUT_EXPR); return m ? parseInt(m[1], 10) * 1e3 : null; } function headerNameToString(value) { @@ -1463,60 +1775,64 @@ var require_util = __commonJS({ 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; + if (val !== void 0) { + if (!Object.hasOwn(obj, key)) { + const headersValue = typeof headers[i + 1] === "string" ? headers[i + 1] : Array.isArray(headers[i + 1]) ? headers[i + 1].map((x) => x.toString("latin1")) : headers[i + 1].toString("latin1"); + if (key === "__proto__") { + Object.defineProperty(obj, key, { + value: headersValue, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = headersValue; + } } else { - obj[key] = Array.isArray(headersValue) ? headersValue.map((x) => x.toString("utf8")) : headersValue.toString("utf8"); + if (typeof val === "string") { + val = [val]; + obj[key] = val; + } + val.push(headers[i + 1].toString("latin1")); } + } else { + const headersValue = typeof headers[i + 1] === "string" ? headers[i + 1] : Array.isArray(headers[i + 1]) ? headers[i + 1].map((x) => x.toString("latin1")) : headers[i + 1].toString("latin1"); + obj[key] = headersValue; } } - 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; + const headersLength = headers.length; + const ret = new Array(headersLength); let key; let val; - let kLen = 0; - for (let n = 0; n < headers.length; n += 2) { + for (let n = 0; n < headersLength; 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; - } + typeof val !== "string" && (val = val.toString("latin1")); ret[n] = key; ret[n + 1] = val; } - if (hasContentLength && contentDispositionIdx !== -1) { - ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString("latin1"); - } return ret; } + function encodeRawHeaders(headers) { + if (!Array.isArray(headers)) { + throw new TypeError("expected headers to be an array"); + } + return headers.map((x) => Buffer.from(x)); + } function isBuffer(buffer) { return buffer instanceof Uint8Array || Buffer.isBuffer(buffer); } - function validateHandler(handler2, method, upgrade) { + function assertRequestHandler(handler2, method, upgrade) { if (!handler2 || typeof handler2 !== "object") { throw new InvalidArgumentError("handler must be an object"); } + if (typeof handler2.onRequestStart === "function") { + return; + } if (typeof handler2.onConnect !== "function") { throw new InvalidArgumentError("invalid onConnect method"); } @@ -1545,12 +1861,6 @@ var require_util = __commonJS({ function isDisturbed(body) { return !!(body && (stream2.isDisturbed(body) || body[kBodyUsed])); } - function isErrored(body) { - return !!(body && stream2.isErrored(body)); - } - function isReadable(body) { - return !!(body && stream2.isReadable(body)); - } function getSocketInfo(socket) { return { localAddress: socket.localAddress, @@ -1567,26 +1877,28 @@ var require_util = __commonJS({ let iterator2; return new ReadableStream( { - async start() { + start() { iterator2 = iterable[Symbol.asyncIterator](); }, - async pull(controller) { - const { done, value } = await iterator2.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)); + pull(controller) { + return iterator2.next().then(({ done, value }) => { + if (done) { + return queueMicrotask(() => { + controller.close(); + controller.byobRequest?.respond(0); + }); + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value); + if (buf.byteLength) { + return controller.enqueue(new Uint8Array(buf)); + } else { + return this.pull(controller); + } } - } - return controller.desiredSize > 0; + }); }, - async cancel(reason) { - await iterator2.return(); + cancel() { + return iterator2.return(); }, type: "bytes" } @@ -1600,47 +1912,292 @@ var require_util = __commonJS({ signal.addEventListener("abort", listener, { once: true }); return () => signal.removeEventListener("abort", listener); } - signal.addListener("abort", listener); + signal.once("abort", listener); return () => signal.removeListener("abort", listener); } - var hasToWellFormed = typeof String.prototype.toWellFormed === "function"; - var hasIsWellFormed = typeof String.prototype.isWellFormed === "function"; - function toUSVString(val) { - return hasToWellFormed ? `${val}`.toWellFormed() : nodeUtil.toUSVString(val); - } - function isUSVString(val) { - return hasIsWellFormed ? `${val}`.isWellFormed() : toUSVString(val) === `${val}`; - } + var validTokenChars = new Uint8Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 0-15 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 16-31 + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 0, + // 32-47 (!"#$%&'()*+,-./) + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + // 48-63 (0-9:;<=>?) + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + // 64-79 (@A-O) + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 1, + // 80-95 (P-Z[\]^_) + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + // 96-111 (`a-o) + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 0, + 1, + 0, + // 112-127 (p-z{|}~) + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 128-143 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 144-159 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 160-175 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 176-191 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 192-207 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 208-223 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 224-239 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + // 240-255 + ]); function isTokenCharCode(c) { - switch (c) { - case 34: - case 40: - case 41: - case 44: - case 47: - case 58: - case 59: - case 60: - case 61: - case 62: - case 63: - case 64: - case 91: - case 92: - case 93: - case 123: - case 125: - return false; - default: - return c >= 33 && c <= 126; - } + return validTokenChars[c] === 1; } + var tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/; function isValidHTTPToken(characters) { - if (characters.length === 0) { - return false; - } - for (let i = 0; i < characters.length; ++i) { - if (!isTokenCharCode(characters.charCodeAt(i))) { + if (characters.length >= 12) return tokenRegExp.test(characters); + if (characters.length === 0) return false; + for (let i = 0; i < characters.length; i++) { + if (validTokenChars[characters.charCodeAt(i)] !== 1) { return false; } } @@ -1650,9 +2207,10 @@ var require_util = __commonJS({ function isValidHeaderValue(characters) { return !headerCharRegex.test(characters); } + var rangeHeaderRegex = /^bytes (\d+)-(\d+)\/(\d+)?$/; function parseRangeHeader(range2) { if (range2 == null || range2 === "") return { start: 0, end: null, size: null }; - const m = range2 ? range2.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null; + const m = range2 ? range2.match(rangeHeaderRegex) : null; return m ? { start: parseInt(m[1]), end: m[2] ? parseInt(m[2]) : null, @@ -1666,10 +2224,13 @@ var require_util = __commonJS({ return obj; } function removeAllListeners(obj) { - for (const [name, listener] of obj[kListeners] ?? []) { - obj.removeListener(name, listener); + if (obj[kListeners] != null) { + for (const [name, listener] of obj[kListeners]) { + obj.removeListener(name, listener); + } + obj[kListeners] = null; } - obj[kListeners] = null; + return obj; } function errorRequest2(client, request3, err) { try { @@ -1679,6 +2240,63 @@ var require_util = __commonJS({ client.emit("error", err2); } } + var setupConnectTimeout = process.platform === "win32" ? (socketWeakRef, opts) => { + if (!opts.timeout) { + return noop3; + } + let s1 = null; + let s2 = null; + const fastTimer = timers.setFastTimeout(() => { + s1 = setImmediate(() => { + s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts)); + }); + }, opts.timeout); + return () => { + timers.clearFastTimeout(fastTimer); + clearImmediate(s1); + clearImmediate(s2); + }; + } : (socketWeakRef, opts) => { + if (!opts.timeout) { + return noop3; + } + let s1 = null; + const fastTimer = timers.setFastTimeout(() => { + s1 = setImmediate(() => { + onConnectTimeout(socketWeakRef.deref(), opts); + }); + }, opts.timeout); + return () => { + timers.clearFastTimeout(fastTimer); + clearImmediate(s1); + }; + }; + function onConnectTimeout(socket, opts) { + 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)`; + destroy(socket, new ConnectTimeoutError(message)); + } + function getProtocolFromUrlString(urlString) { + if (urlString[0] === "h" && urlString[1] === "t" && urlString[2] === "t" && urlString[3] === "p") { + switch (urlString[4]) { + case ":": + return "http:"; + case "s": + if (urlString[5] === ":") { + return "https:"; + } + } + } + return urlString.slice(0, urlString.indexOf(":") + 1); + } var kEnumerableProperty = /* @__PURE__ */ Object.create(null); kEnumerableProperty.enumerable = true; var normalizedMethodRecordsBase = { @@ -1704,19 +2322,15 @@ var require_util = __commonJS({ Object.setPrototypeOf(normalizedMethodRecords, null); module2.exports = { kEnumerableProperty, - nop, isDisturbed, - isErrored, - isReadable, - toUSVString, - isUSVString, isBlobLike, parseOrigin, parseURL, getServerName, isStream: isStream2, - isIterable, - isAsyncIterable, + isIterable: isIterable2, + hasSafeIterator, + isAsyncIterable: isAsyncIterable2, isDestroyed, headerNameToString, bufferToLowerCasedHeaderName, @@ -1724,6 +2338,7 @@ var require_util = __commonJS({ removeAllListeners, errorRequest: errorRequest2, parseRawHeaders, + encodeRawHeaders, parseHeaders, parseKeepAliveTimeout, destroy, @@ -1731,10 +2346,11 @@ var require_util = __commonJS({ deepClone, ReadableStreamFrom, isBuffer, - validateHandler, + assertRequestHandler, getSocketInfo, isFormDataLike, - buildURL, + pathHasQueryOrFragment, + serializePathWithQuery, addAbortListener, isValidHTTPToken, isValidHeaderValue, @@ -1746,9 +2362,45 @@ var require_util = __commonJS({ isHttpOrHttpsPrefixed, nodeMajor, nodeMinor, - safeHTTPMethods: ["GET", "HEAD", "OPTIONS", "TRACE"], - wrapRequestBody + safeHTTPMethods: Object.freeze(["GET", "HEAD", "OPTIONS", "TRACE"]), + wrapRequestBody, + setupConnectTimeout, + getProtocolFromUrlString + }; + } +}); + +// node_modules/undici/lib/util/stats.js +var require_stats = __commonJS({ + "node_modules/undici/lib/util/stats.js"(exports2, module2) { + "use strict"; + var { + kConnected, + kPending, + kRunning, + kSize, + kFree, + kQueued + } = require_symbols(); + var ClientStats = class { + constructor(client) { + this.connected = client[kConnected]; + this.pending = client[kPending]; + this.running = client[kRunning]; + this.size = client[kSize]; + } + }; + var PoolStats = class { + constructor(pool) { + this.connected = pool[kConnected]; + this.free = pool[kFree]; + this.pending = pool[kPending]; + this.queued = pool[kQueued]; + this.running = pool[kRunning]; + this.size = pool[kSize]; + } }; + module2.exports = { ClientStats, PoolStats }; } }); @@ -1757,11 +2409,10 @@ var require_diagnostics = __commonJS({ "node_modules/undici/lib/core/diagnostics.js"(exports2, module2) { "use strict"; var diagnosticsChannel = require("node:diagnostics_channel"); - var util3 = require("node:util"); - var undiciDebugLog = util3.debuglog("undici"); - var fetchDebuglog = util3.debuglog("fetch"); - var websocketDebuglog = util3.debuglog("websocket"); - var isClientSet = false; + var util4 = require("node:util"); + var undiciDebugLog = util4.debuglog("undici"); + var fetchDebuglog = util4.debuglog("fetch"); + var websocketDebuglog = util4.debuglog("websocket"); var channels = { // Client beforeConnect: diagnosticsChannel.channel("undici:client:beforeConnect"), @@ -1771,6 +2422,8 @@ var require_diagnostics = __commonJS({ // Request create: diagnosticsChannel.channel("undici:request:create"), bodySent: diagnosticsChannel.channel("undici:request:bodySent"), + bodyChunkSent: diagnosticsChannel.channel("undici:request:bodyChunkSent"), + bodyChunkReceived: diagnosticsChannel.channel("undici:request:bodyChunkReceived"), headers: diagnosticsChannel.channel("undici:request:headers"), trailers: diagnosticsChannel.channel("undici:request:trailers"), error: diagnosticsChannel.channel("undici:request:error"), @@ -1779,118 +2432,58 @@ var require_diagnostics = __commonJS({ 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") + pong: diagnosticsChannel.channel("undici:websocket:pong"), + // ProxyAgent + proxyConnected: diagnosticsChannel.channel("undici:proxy:connected") }; - if (undiciDebugLog.enabled || fetchDebuglog.enabled) { - const debuglog = fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog; - 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: error3 - } = evt; - debuglog( - "connection to %s using %s%s errored - %s", - `${host}${port ? `:${port}` : ""}`, - protocol, - version, - error3.message - ); - }); - diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => { - const { - request: { method, path: path30, origin } - } = evt; - debuglog("sending request to %s %s/%s", method, origin, path30); - }); - diagnosticsChannel.channel("undici:request:headers").subscribe((evt) => { - const { - request: { method, path: path30, origin }, - response: { statusCode } - } = evt; - debuglog( - "received response to %s %s/%s - HTTP %d", - method, - origin, - path30, - statusCode - ); - }); - diagnosticsChannel.channel("undici:request:trailers").subscribe((evt) => { - const { - request: { method, path: path30, origin } - } = evt; - debuglog("trailers received from %s %s/%s", method, origin, path30); - }); - diagnosticsChannel.channel("undici:request:error").subscribe((evt) => { - const { - request: { method, path: path30, origin }, - error: error3 - } = evt; - debuglog( - "request to %s %s/%s errored - %s", - method, - origin, - path30, - error3.message - ); - }); - isClientSet = true; - } - if (websocketDebuglog.enabled) { - if (!isClientSet) { - const debuglog = undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog; - diagnosticsChannel.channel("undici:client:beforeConnect").subscribe((evt) => { + var isTrackingClientEvents = false; + function trackClientEvents(debugLog = undiciDebugLog) { + if (isTrackingClientEvents) { + return; + } + if (channels.beforeConnect.hasSubscribers || channels.connected.hasSubscribers || channels.connectError.hasSubscribers || channels.sendHeaders.hasSubscribers) { + isTrackingClientEvents = true; + return; + } + isTrackingClientEvents = true; + diagnosticsChannel.subscribe( + "undici:client:beforeConnect", + (evt) => { const { connectParams: { version, protocol, port, host } } = evt; - debuglog( + debugLog( "connecting to %s%s using %s%s", host, port ? `:${port}` : "", protocol, version ); - }); - diagnosticsChannel.channel("undici:client:connected").subscribe((evt) => { + } + ); + diagnosticsChannel.subscribe( + "undici:client:connected", + (evt) => { const { connectParams: { version, protocol, port, host } } = evt; - debuglog( + debugLog( "connected to %s%s using %s%s", host, port ? `:${port}` : "", protocol, version ); - }); - diagnosticsChannel.channel("undici:client:connectError").subscribe((evt) => { + } + ); + diagnosticsChannel.subscribe( + "undici:client:connectError", + (evt) => { const { connectParams: { version, protocol, port, host }, error: error3 } = evt; - debuglog( + debugLog( "connection to %s%s using %s%s errored - %s", host, port ? `:${port}` : "", @@ -1898,38 +2491,129 @@ var require_diagnostics = __commonJS({ version, error3.message ); - }); - diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => { + } + ); + diagnosticsChannel.subscribe( + "undici:client:sendHeaders", + (evt) => { const { request: { method, path: path30, origin } } = evt; - debuglog("sending request to %s %s/%s", method, origin, path30); - }); + debugLog("sending request to %s %s%s", method, origin, path30); + } + ); + } + var isTrackingRequestEvents = false; + function trackRequestEvents(debugLog = undiciDebugLog) { + if (isTrackingRequestEvents) { + return; } - 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"); - }); + if (channels.headers.hasSubscribers || channels.trailers.hasSubscribers || channels.error.hasSubscribers) { + isTrackingRequestEvents = true; + return; + } + isTrackingRequestEvents = true; + diagnosticsChannel.subscribe( + "undici:request:headers", + (evt) => { + const { + request: { method, path: path30, origin }, + response: { statusCode } + } = evt; + debugLog( + "received response to %s %s%s - HTTP %d", + method, + origin, + path30, + statusCode + ); + } + ); + diagnosticsChannel.subscribe( + "undici:request:trailers", + (evt) => { + const { + request: { method, path: path30, origin } + } = evt; + debugLog("trailers received from %s %s%s", method, origin, path30); + } + ); + diagnosticsChannel.subscribe( + "undici:request:error", + (evt) => { + const { + request: { method, path: path30, origin }, + error: error3 + } = evt; + debugLog( + "request to %s %s%s errored - %s", + method, + origin, + path30, + error3.message + ); + } + ); + } + var isTrackingWebSocketEvents = false; + function trackWebSocketEvents(debugLog = websocketDebuglog) { + if (isTrackingWebSocketEvents) { + return; + } + if (channels.open.hasSubscribers || channels.close.hasSubscribers || channels.socketError.hasSubscribers || channels.ping.hasSubscribers || channels.pong.hasSubscribers) { + isTrackingWebSocketEvents = true; + return; + } + isTrackingWebSocketEvents = true; + diagnosticsChannel.subscribe( + "undici:websocket:open", + (evt) => { + if (evt.address != null) { + const { address, port } = evt.address; + debugLog("connection opened %s%s", address, port ? `:${port}` : ""); + } else { + debugLog("connection opened"); + } + } + ); + diagnosticsChannel.subscribe( + "undici:websocket:close", + (evt) => { + const { websocket, code, reason } = evt; + debugLog( + "closed connection to %s - %s %s", + websocket.url, + code, + reason + ); + } + ); + diagnosticsChannel.subscribe( + "undici:websocket:socket_error", + (err) => { + debugLog("connection errored - %s", err.message); + } + ); + diagnosticsChannel.subscribe( + "undici:websocket:ping", + (evt) => { + debugLog("ping received"); + } + ); + diagnosticsChannel.subscribe( + "undici:websocket:pong", + (evt) => { + debugLog("pong received"); + } + ); + } + if (undiciDebugLog.enabled || fetchDebuglog.enabled) { + trackClientEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog); + trackRequestEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog); + } + if (websocketDebuglog.enabled) { + trackClientEvents(undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog); + trackWebSocketEvents(websocketDebuglog); } module2.exports = { channels @@ -1953,16 +2637,30 @@ var require_request = __commonJS({ destroy, isBuffer, isFormDataLike, - isIterable, + isIterable: isIterable2, + hasSafeIterator, isBlobLike, - buildURL, - validateHandler, + serializePathWithQuery, + assertRequestHandler, getServerName, - normalizedMethodRecords + normalizedMethodRecords, + getProtocolFromUrlString } = require_util(); var { channels } = require_diagnostics(); var { headerNameLowerCasedRecord } = require_constants(); var invalidPathRegex = /[^\u0021-\u00ff]/; + function isValidContentLengthHeaderValue(val) { + if (typeof val !== "string" || val.length === 0) { + return false; + } + for (let i = 0; i < val.length; i++) { + const charCode = val.charCodeAt(i); + if (charCode < 48 || charCode > 57) { + return false; + } + } + return true; + } var kHandler = /* @__PURE__ */ Symbol("handler"); var Request = class { constructor(origin, { @@ -1977,9 +2675,11 @@ var require_request = __commonJS({ headersTimeout, bodyTimeout, reset, - throwOnError, expectContinue, - servername + servername, + throwOnError, + maxRedirections, + typeOfService }, handler2) { if (typeof path30 !== "string") { throw new InvalidArgumentError("path must be a string"); @@ -2011,10 +2711,19 @@ var require_request = __commonJS({ if (expectContinue != null && typeof expectContinue !== "boolean") { throw new InvalidArgumentError("invalid expectContinue"); } + if (throwOnError != null) { + throw new InvalidArgumentError("invalid throwOnError"); + } + if (maxRedirections != null && maxRedirections !== 0) { + throw new InvalidArgumentError("maxRedirections is not supported, use the redirect interceptor"); + } + if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) { + throw new InvalidArgumentError("typeOfService must be an integer between 0 and 255"); + } this.headersTimeout = headersTimeout; this.bodyTimeout = bodyTimeout; - this.throwOnError = throwOnError === true; this.method = method; + this.typeOfService = typeOfService ?? 0; this.abort = null; if (body == null) { this.body = null; @@ -2043,7 +2752,7 @@ var require_request = __commonJS({ 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)) { + } else if (isFormDataLike(body) || isIterable2(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"); @@ -2051,10 +2760,11 @@ var require_request = __commonJS({ this.completed = false; this.aborted = false; this.upgrade = upgrade || null; - this.path = query ? buildURL(path30, query) : path30; + this.path = query ? serializePathWithQuery(path30, query) : path30; this.origin = origin; + this.protocol = getProtocolFromUrlString(origin); this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent; - this.blocking = blocking == null ? false : blocking; + this.blocking = blocking ?? this.method !== "HEAD"; this.reset = reset == null ? null : reset; this.host = null; this.contentLength = null; @@ -2069,7 +2779,7 @@ var require_request = __commonJS({ processHeader(this, headers[i], headers[i + 1]); } } else if (headers && typeof headers === "object") { - if (headers[Symbol.iterator]) { + if (hasSafeIterator(headers)) { for (const header of headers) { if (!Array.isArray(header) || header.length !== 2) { throw new InvalidArgumentError("headers must be in key-value pair format"); @@ -2085,14 +2795,17 @@ var require_request = __commonJS({ } else if (headers != null) { throw new InvalidArgumentError("headers must be an object or an array"); } - validateHandler(handler2, method, upgrade); - this.servername = servername || getServerName(this.host); + assertRequestHandler(handler2, method, upgrade); + this.servername = servername || getServerName(this.host) || null; this[kHandler] = handler2; if (channels.create.hasSubscribers) { channels.create.publish({ request: this }); } } onBodySent(chunk) { + if (channels.bodyChunkSent.hasSubscribers) { + channels.bodyChunkSent.publish({ request: this, chunk }); + } if (this[kHandler].onBodySent) { try { return this[kHandler].onBodySent(chunk); @@ -2141,6 +2854,9 @@ var require_request = __commonJS({ onData(chunk) { assert(!this.aborted); assert(!this.completed); + if (channels.bodyChunkReceived.hasSubscribers) { + channels.bodyChunkReceived.publish({ request: this, chunk }); + } try { return this[kHandler].onData(chunk); } catch (err) { @@ -2148,14 +2864,32 @@ var require_request = __commonJS({ return false; } } - onUpgrade(statusCode, headers, socket) { + /** + * @param {number} statusCode + * @param {Buffer[]|string[]} headers + * @param {import('node:stream').Duplex} socket + * @param {string} [statusText] + */ + onUpgrade(statusCode, headers, socket, statusText = "") { + this.onFinally(); assert(!this.aborted); assert(!this.completed); - return this[kHandler].onUpgrade(statusCode, headers, socket); + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); + } + const result = this[kHandler].onUpgrade(statusCode, headers, socket); + if (!this.aborted) { + this.completed = true; + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers: [] }); + } + } + return result; } onComplete(trailers) { this.onFinally(); assert(!this.aborted); + assert(!this.completed); this.completed = true; if (channels.trailers.hasSubscribers) { channels.trailers.publish({ request: this, trailers }); @@ -2250,22 +2984,28 @@ var require_request = __commonJS({ if (request3.contentLength !== null) { throw new InvalidArgumentError("duplicate content-length header"); } - request3.contentLength = parseInt(val, 10); - if (!Number.isFinite(request3.contentLength)) { + if (!isValidContentLengthHeaderValue(val)) { throw new InvalidArgumentError("invalid content-length header"); } + request3.contentLength = parseInt(val, 10); } else if (request3.contentType === null && headerName === "content-type") { request3.contentType = val; request3.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") { + const value = typeof val === "string" ? val : null; + if (value === null) { throw new InvalidArgumentError("invalid connection header"); } - if (value === "close") { - request3.reset = true; + for (const token of value.toLowerCase().split(",")) { + const trimmed = token.trim(); + if (!isValidHTTPToken(trimmed)) { + throw new InvalidArgumentError("invalid connection header"); + } + if (trimmed === "close") { + request3.reset = true; + } } } else if (headerName === "expect") { throw new NotSupportedError("expect header not supported"); @@ -2277,11 +3017,96 @@ var require_request = __commonJS({ } }); +// node_modules/undici/lib/handler/wrap-handler.js +var require_wrap_handler = __commonJS({ + "node_modules/undici/lib/handler/wrap-handler.js"(exports2, module2) { + "use strict"; + var { InvalidArgumentError } = require_errors(); + module2.exports = class WrapHandler { + #handler; + constructor(handler2) { + this.#handler = handler2; + } + static wrap(handler2) { + return handler2.onRequestStart ? handler2 : new WrapHandler(handler2); + } + // Unwrap Interface + onConnect(abort, context5) { + return this.#handler.onConnect?.(abort, context5); + } + onResponseStarted() { + return this.#handler.onResponseStarted?.(); + } + onHeaders(statusCode, rawHeaders, resume, statusMessage) { + return this.#handler.onHeaders?.(statusCode, rawHeaders, resume, statusMessage); + } + onUpgrade(statusCode, rawHeaders, socket) { + return this.#handler.onUpgrade?.(statusCode, rawHeaders, socket); + } + onData(data) { + return this.#handler.onData?.(data); + } + onComplete(trailers) { + return this.#handler.onComplete?.(trailers); + } + onError(err) { + if (!this.#handler.onError) { + throw err; + } + return this.#handler.onError?.(err); + } + // Wrap Interface + onRequestStart(controller, context5) { + this.#handler.onConnect?.((reason) => controller.abort(reason), context5); + } + onRequestUpgrade(controller, statusCode, headers, socket) { + const rawHeaders = []; + for (const [key, val] of Object.entries(headers)) { + rawHeaders.push(Buffer.from(key, "latin1"), toRawHeaderValue(val)); + } + this.#handler.onUpgrade?.(statusCode, rawHeaders, socket); + } + onResponseStart(controller, statusCode, headers, statusMessage) { + const rawHeaders = []; + for (const [key, val] of Object.entries(headers)) { + rawHeaders.push(Buffer.from(key, "latin1"), toRawHeaderValue(val)); + } + if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) { + controller.pause(); + } + } + onResponseData(controller, data) { + if (this.#handler.onData?.(data) === false) { + controller.pause(); + } + } + onResponseEnd(controller, trailers) { + const rawTrailers = []; + for (const [key, val] of Object.entries(trailers)) { + rawTrailers.push(Buffer.from(key, "latin1"), toRawHeaderValue(val)); + } + this.#handler.onComplete?.(rawTrailers); + } + onResponseError(controller, err) { + if (!this.#handler.onError) { + throw new InvalidArgumentError("invalid onError method"); + } + this.#handler.onError?.(err); + } + }; + function toRawHeaderValue(value) { + return Array.isArray(value) ? value.map((item) => Buffer.from(item, "latin1")) : Buffer.from(value, "latin1"); + } + } +}); + // node_modules/undici/lib/dispatcher/dispatcher.js var require_dispatcher = __commonJS({ "node_modules/undici/lib/dispatcher/dispatcher.js"(exports2, module2) { "use strict"; var EventEmitter2 = require("node:events"); + var WrapHandler = require_wrap_handler(); + var wrapInterceptor = (dispatch) => (opts, handler2) => dispatch(opts, WrapHandler.wrap(handler2)); var Dispatcher = class extends EventEmitter2 { dispatch() { throw new Error("not implemented"); @@ -2303,32 +3128,105 @@ var require_dispatcher = __commonJS({ throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`); } dispatch = interceptor(dispatch); + dispatch = wrapInterceptor(dispatch); if (dispatch == null || typeof dispatch !== "function" || dispatch.length !== 2) { throw new TypeError("invalid interceptor"); } } - return new ComposedDispatcher(this, dispatch); + return new Proxy(this, { + get: (target, key) => key === "dispatch" ? dispatch : target[key] + }); } }; - var ComposedDispatcher = class extends Dispatcher { - #dispatcher = null; - #dispatch = null; - constructor(dispatcher, dispatch) { - super(); - this.#dispatcher = dispatcher; - this.#dispatch = dispatch; + module2.exports = Dispatcher; + } +}); + +// node_modules/undici/lib/handler/unwrap-handler.js +var require_unwrap_handler = __commonJS({ + "node_modules/undici/lib/handler/unwrap-handler.js"(exports2, module2) { + "use strict"; + var { parseHeaders } = require_util(); + var { InvalidArgumentError } = require_errors(); + var kResume = /* @__PURE__ */ Symbol("resume"); + var UnwrapController = class { + #paused = false; + #reason = null; + #aborted = false; + #abort; + [kResume] = null; + rawHeaders = null; + rawTrailers = null; + constructor(abort) { + this.#abort = abort; + } + pause() { + this.#paused = true; + } + resume() { + if (this.#paused) { + this.#paused = false; + this[kResume]?.(); + } } - dispatch(...args) { - this.#dispatch(...args); + abort(reason) { + if (!this.#aborted) { + this.#aborted = true; + this.#reason = reason; + this.#abort(reason); + } + } + get aborted() { + return this.#aborted; } - close(...args) { - return this.#dispatcher.close(...args); + get reason() { + return this.#reason; } - destroy(...args) { - return this.#dispatcher.destroy(...args); + get paused() { + return this.#paused; + } + }; + module2.exports = class UnwrapHandler { + #handler; + #controller; + constructor(handler2) { + this.#handler = handler2; + } + static unwrap(handler2) { + return !handler2.onRequestStart ? handler2 : new UnwrapHandler(handler2); + } + onConnect(abort, context5) { + this.#controller = new UnwrapController(abort); + this.#handler.onRequestStart?.(this.#controller, context5); + } + onResponseStarted() { + return this.#handler.onResponseStarted?.(); + } + onUpgrade(statusCode, rawHeaders, socket) { + this.#controller.rawHeaders = rawHeaders; + this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket); + } + onHeaders(statusCode, rawHeaders, resume, statusMessage) { + this.#controller[kResume] = resume; + this.#controller.rawHeaders = rawHeaders; + this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage); + return !this.#controller.paused; + } + onData(data) { + this.#handler.onResponseData?.(this.#controller, data); + return !this.#controller.paused; + } + onComplete(rawTrailers) { + this.#controller.rawTrailers = rawTrailers; + this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers)); + } + onError(err) { + if (!this.#handler.onResponseError) { + throw new InvalidArgumentError("invalid onError method"); + } + this.#handler.onResponseError?.(this.#controller, err); } }; - module2.exports = Dispatcher; } }); @@ -2336,57 +3234,67 @@ var require_dispatcher = __commonJS({ var require_dispatcher_base = __commonJS({ "node_modules/undici/lib/dispatcher/dispatcher-base.js"(exports2, module2) { "use strict"; + var buffer = require("node:buffer"); var Dispatcher = require_dispatcher(); + var UnwrapHandler = require_unwrap_handler(); var { ClientDestroyedError, ClientClosedError, InvalidArgumentError } = require_errors(); - var { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kInterceptors } = require_symbols(); + var { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require_symbols(); var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); - var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); + var kEventSourceOptions = /* @__PURE__ */ Symbol("eventSourceOptions"); var DispatcherBase = class extends Dispatcher { + /** @type {boolean} */ + [kDestroyed] = false; + /** @type {Array|null} */ + [kOnClosed] = null; + /** + * @param {import('../../types/dispatcher').DispatcherOptions} [opts] + */ constructor(opts) { super(); - this[kDestroyed] = false; - this[kOnDestroyed] = null; - this[kClosed] = false; - this[kOnClosed] = []; this[kWebSocketOptions] = opts?.webSocket ?? {}; + this[kEventSourceOptions] = opts?.eventSource ?? {}; } + /** + * @returns {import('../../types/dispatcher').WebSocketOptions} + */ get webSocketOptions() { return { maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 + // 128 MB default + }; + } + /** + * @returns {import('../../types/client').Client.EventSourceOptions} + */ + get eventSourceOptions() { + return { + maxEventSize: this[kEventSourceOptions].maxEventSize ?? buffer.kStringMaxLength }; } + /** @returns {boolean} */ get destroyed() { return this[kDestroyed]; } + /** @returns {boolean} */ 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 === void 0) { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { this.close((err, data) => { - return err ? reject(err) : resolve14(data); + return err ? reject(err) : resolve15(data); }); }); } @@ -2394,7 +3302,8 @@ var require_dispatcher_base = __commonJS({ throw new InvalidArgumentError("invalid callback"); } if (this[kDestroyed]) { - queueMicrotask(() => callback(new ClientDestroyedError(), null)); + const err = new ClientDestroyedError(); + queueMicrotask(() => callback(err, null)); return; } if (this[kClosed]) { @@ -2406,6 +3315,7 @@ var require_dispatcher_base = __commonJS({ return; } this[kClosed] = true; + this[kOnClosed] ??= []; this[kOnClosed].push(callback); const onClosed = () => { const callbacks = this[kOnClosed]; @@ -2414,9 +3324,7 @@ var require_dispatcher_base = __commonJS({ callbacks[i](null, null); } }; - this[kClose]().then(() => this.destroy()).then(() => { - queueMicrotask(onClosed); - }); + this[kClose]().then(() => this.destroy()).then(() => queueMicrotask(onClosed)); } destroy(err, callback) { if (typeof err === "function") { @@ -2424,12 +3332,9 @@ var require_dispatcher_base = __commonJS({ err = null; } if (callback === void 0) { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { this.destroy(err, (err2, data) => { - return err2 ? ( - /* istanbul ignore next: should never error */ - reject(err2) - ) : resolve14(data); + return err2 ? reject(err2) : resolve15(data); }); }); } @@ -2448,7 +3353,7 @@ var require_dispatcher_base = __commonJS({ err = new ClientDestroyedError(); } this[kDestroyed] = true; - this[kOnDestroyed] = this[kOnDestroyed] || []; + this[kOnDestroyed] ??= []; this[kOnDestroyed].push(callback); const onDestroyed = () => { const callbacks = this[kOnDestroyed]; @@ -2457,26 +3362,13 @@ var require_dispatcher_base = __commonJS({ callbacks[i](null, null); } }; - this[kDestroy](err).then(() => { - queueMicrotask(onDestroyed); - }); - } - [kInterceptedDispatch](opts, handler2) { - if (!this[kInterceptors] || this[kInterceptors].length === 0) { - this[kInterceptedDispatch] = this[kDispatch]; - return this[kDispatch](opts, handler2); - } - 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, handler2); + this[kDestroy](err).then(() => queueMicrotask(onDestroyed)); } dispatch(opts, handler2) { if (!handler2 || typeof handler2 !== "object") { throw new InvalidArgumentError("handler must be an object"); } + handler2 = UnwrapHandler.unwrap(handler2); try { if (!opts || typeof opts !== "object") { throw new InvalidArgumentError("opts must be an object."); @@ -2487,10 +3379,10 @@ var require_dispatcher_base = __commonJS({ if (this[kClosed]) { throw new ClientClosedError(); } - return this[kInterceptedDispatch](opts, handler2); + return this[kDispatch](opts, handler2); } catch (err) { if (typeof handler2.onError !== "function") { - throw new InvalidArgumentError("invalid onError method"); + throw err; } handler2.onError(err); return false; @@ -2501,299 +3393,60 @@ var require_dispatcher_base = __commonJS({ } }); -// node_modules/undici/lib/util/timers.js -var require_timers = __commonJS({ - "node_modules/undici/lib/util/timers.js"(exports2, module2) { - "use strict"; - var fastNow = 0; - var RESOLUTION_MS = 1e3; - var TICK_MS = (RESOLUTION_MS >> 1) - 1; - var fastNowTimeout; - var kFastTimer = /* @__PURE__ */ Symbol("kFastTimer"); - var fastTimers = []; - var NOT_IN_LIST = -2; - var TO_BE_CLEARED = -1; - var PENDING = 0; - var ACTIVE = 1; - function onTick() { - fastNow += TICK_MS; - let idx = 0; - let len = fastTimers.length; - while (idx < len) { - const timer = fastTimers[idx]; - if (timer._state === PENDING) { - 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; - if (--len !== 0) { - fastTimers[idx] = fastTimers[len]; - } - } else { - ++idx; - } - } - fastTimers.length = len; - if (fastTimers.length !== 0) { - refreshTimeout(); - } - } - function refreshTimeout() { - if (fastNowTimeout) { - fastNowTimeout.refresh(); - } else { - clearTimeout(fastNowTimeout); - fastNowTimeout = setTimeout(onTick, TICK_MS); - if (fastNowTimeout.unref) { - fastNowTimeout.unref(); - } - } - } - var FastTimer = class { - [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, delay2, arg) { - this._onTimeout = callback; - this._idleTimeout = delay2; - 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() { - if (this._state === NOT_IN_LIST) { - fastTimers.push(this); - } - if (!fastNowTimeout || fastTimers.length === 1) { - refreshTimeout(); - } - this._state = PENDING; - } - /** - * The `clear` method cancels the timer, preventing it from executing. - * - * @returns {void} - * @private - */ - clear() { - this._state = TO_BE_CLEARED; - this._idleStart = -1; - } - }; - module2.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, delay2, arg) { - return delay2 <= RESOLUTION_MS ? setTimeout(callback, delay2, arg) : new FastTimer(callback, delay2, arg); - }, - /** - * The clearTimeout method cancels an instantiated Timer previously created - * by calling setTimeout. - * - * @param {NodeJS.Timeout|FastTimer} timeout - */ - clearTimeout(timeout) { - if (timeout[kFastTimer]) { - timeout.clear(); - } 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, delay2, arg) { - return new FastTimer(callback, delay2, 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(delay2 = 0) { - fastNow += delay2 - 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 - }; - } -}); - // node_modules/undici/lib/core/connect.js var require_connect = __commonJS({ "node_modules/undici/lib/core/connect.js"(exports2, module2) { "use strict"; var net = require("node:net"); var assert = require("node:assert"); - var util3 = require_util(); - var { InvalidArgumentError, ConnectTimeoutError } = require_errors(); - var timers = require_timers(); - function noop3() { - } + var util4 = require_util(); + var { InvalidArgumentError } = require_errors(); var tls; - var SessionCache; - if (global.FinalizationRegistry && !(process.env.NODE_V8_COVERAGE || process.env.UNDICI_NO_FG)) { - SessionCache = class WeakSessionCache { - constructor(maxCachedSessions) { - this._maxCachedSessions = maxCachedSessions; - this._sessionCache = /* @__PURE__ */ new Map(); - this._sessionRegistry = new global.FinalizationRegistry((key) => { - if (this._sessionCache.size < this._maxCachedSessions) { - return; - } - const ref = this._sessionCache.get(key); - if (ref !== void 0 && ref.deref() === void 0) { - this._sessionCache.delete(key); - } - }); - } - get(sessionKey) { - const ref = this._sessionCache.get(sessionKey); - return ref ? ref.deref() : null; - } - set(sessionKey, session) { - if (this._maxCachedSessions === 0) { + var SessionCache = class WeakSessionCache { + constructor(maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions; + this._sessionCache = /* @__PURE__ */ new Map(); + this._sessionRegistry = new FinalizationRegistry((key) => { + if (this._sessionCache.size < this._maxCachedSessions) { return; } - this._sessionCache.set(sessionKey, new WeakRef(session)); - this._sessionRegistry.register(session, sessionKey); - } - }; - } else { - SessionCache = class SimpleSessionCache { - constructor(maxCachedSessions) { - this._maxCachedSessions = maxCachedSessions; - this._sessionCache = /* @__PURE__ */ new Map(); - } - get(sessionKey) { - return this._sessionCache.get(sessionKey); + const ref = this._sessionCache.get(key); + if (ref !== void 0 && ref.deref() === void 0) { + 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; } - set(sessionKey, session) { - if (this._maxCachedSessions === 0) { - return; + if (this._sessionCache.has(sessionKey)) { + this._sessionCache.delete(sessionKey); + } else if (this._sessionCache.size >= this._maxCachedSessions) { + let evicted = false; + for (const [key, ref] of this._sessionCache) { + if (ref.deref() === void 0) { + this._sessionCache.delete(key); + evicted = true; + break; + } } - if (this._sessionCache.size >= this._maxCachedSessions) { - const { value: oldestKey } = this._sessionCache.keys().next(); - this._sessionCache.delete(oldestKey); + if (!evicted) { + const oldest = this._sessionCache.keys().next(); + if (!oldest.done) { + this._sessionCache.delete(oldest.value); + } } - this._sessionCache.set(sessionKey, session); } - }; - } - function buildConnector({ allowH2, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) { + this._sessionCache.set(sessionKey, new WeakRef(session)); + this._sessionRegistry.register(session, sessionKey); + } + }; + function buildConnector({ allowH2, useH2c, 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"); } @@ -2807,7 +3460,7 @@ var require_connect = __commonJS({ if (!tls) { tls = require("node:tls"); } - servername = servername || options.servername || util3.getServerName(host) || null; + servername = servername || options.servername || util4.getServerName(host) || null; const sessionKey = servername || hostname; assert(sessionKey); const session = customSession || sessionCache.get(sessionKey) || null; @@ -2819,7 +3472,6 @@ var require_connect = __commonJS({ servername, session, localAddress, - // TODO(HTTP/2): Add support for h2c ALPNProtocols: allowH2 ? ["http/1.1", "h2"] : ["http/1.1"], socket: httpSocket, // upgrade socket connection @@ -2840,12 +3492,15 @@ var require_connect = __commonJS({ port, host: hostname }); + if (useH2c === true) { + socket.alpnProtocol = "h2"; + } } if (options.keepAlive == null || options.keepAlive) { const keepAliveInitialDelay = options.keepAliveInitialDelay === void 0 ? 6e4 : options.keepAliveInitialDelay; socket.setKeepAlive(true, keepAliveInitialDelay); } - const clearConnectTimeout = setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port }); + const clearConnectTimeout = util4.setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port }); socket.setNoDelay(true).once(protocol === "https:" ? "secureConnect" : "connect", function() { queueMicrotask(clearConnectTimeout); if (callback) { @@ -2864,50 +3519,6 @@ var require_connect = __commonJS({ return socket; }; } - var setupConnectTimeout = process.platform === "win32" ? (socketWeakRef, opts) => { - if (!opts.timeout) { - return noop3; - } - let s1 = null; - let s2 = null; - const fastTimer = timers.setFastTimeout(() => { - s1 = setImmediate(() => { - s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts)); - }); - }, opts.timeout); - return () => { - timers.clearFastTimeout(fastTimer); - clearImmediate(s1); - clearImmediate(s2); - }; - } : (socketWeakRef, opts) => { - if (!opts.timeout) { - return noop3; - } - let s1 = null; - const fastTimer = timers.setFastTimeout(() => { - s1 = setImmediate(() => { - onConnectTimeout(socketWeakRef.deref(), opts); - }); - }, opts.timeout); - return () => { - timers.clearFastTimeout(fastTimer); - clearImmediate(s1); - }; - }; - function onConnectTimeout(socket, opts) { - 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)`; - util3.destroy(socket, new ConnectTimeoutError(message)); - } module2.exports = buildConnector; } }); @@ -2917,18 +3528,14 @@ var require_utils2 = __commonJS({ "node_modules/undici/lib/llhttp/utils.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.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; - } exports2.enumToMap = enumToMap; + function enumToMap(obj, filter2 = [], exceptions = []) { + const emptyFilter = (filter2?.length ?? 0) === 0; + const emptyExceptions = (exceptions?.length ?? 0) === 0; + return Object.fromEntries(Object.entries(obj).filter(([, value]) => { + return typeof value === "number" && (emptyFilter || filter2.includes(value)) && (emptyExceptions || !exceptions.includes(value)); + })); + } } }); @@ -2937,180 +3544,453 @@ var require_constants2 = __commonJS({ "node_modules/undici/lib/llhttp/constants.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SPECIAL_HEADERS = exports2.HEADER_STATE = exports2.MINOR = exports2.MAJOR = exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS = exports2.TOKEN = exports2.STRICT_TOKEN = exports2.HEX = exports2.URL_CHAR = exports2.STRICT_URL_CHAR = exports2.USERINFO_CHARS = exports2.MARK = exports2.ALPHANUM = exports2.NUM = exports2.HEX_MAP = exports2.NUM_MAP = exports2.ALPHA = exports2.FINISH = exports2.H_METHOD_MAP = exports2.METHOD_MAP = exports2.METHODS_RTSP = exports2.METHODS_ICE = exports2.METHODS_HTTP = exports2.METHODS = exports2.LENIENT_FLAGS = exports2.FLAGS = exports2.TYPE = exports2.ERROR = void 0; + exports2.SPECIAL_HEADERS = exports2.MINOR = exports2.MAJOR = exports2.HTAB_SP_VCHAR_OBS_TEXT = exports2.QUOTED_STRING = exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS = exports2.TOKEN = exports2.HEX = exports2.URL_CHAR = exports2.USERINFO_CHARS = exports2.MARK = exports2.ALPHANUM = exports2.NUM = exports2.HEX_MAP = exports2.NUM_MAP = exports2.ALPHA = exports2.STATUSES_HTTP = exports2.H_METHOD_MAP = exports2.METHOD_MAP = exports2.METHODS_RTSP = exports2.METHODS_ICE = exports2.METHODS_HTTP = exports2.HEADER_STATE = exports2.FINISH = exports2.STATUSES = exports2.METHODS = exports2.LENIENT_FLAGS = exports2.FLAGS = exports2.TYPE = exports2.ERROR = void 0; var utils_1 = require_utils2(); - var ERROR; - (function(ERROR2) { - ERROR2[ERROR2["OK"] = 0] = "OK"; - ERROR2[ERROR2["INTERNAL"] = 1] = "INTERNAL"; - ERROR2[ERROR2["STRICT"] = 2] = "STRICT"; - ERROR2[ERROR2["LF_EXPECTED"] = 3] = "LF_EXPECTED"; - ERROR2[ERROR2["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; - ERROR2[ERROR2["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; - ERROR2[ERROR2["INVALID_METHOD"] = 6] = "INVALID_METHOD"; - ERROR2[ERROR2["INVALID_URL"] = 7] = "INVALID_URL"; - ERROR2[ERROR2["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; - ERROR2[ERROR2["INVALID_VERSION"] = 9] = "INVALID_VERSION"; - ERROR2[ERROR2["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; - ERROR2[ERROR2["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; - ERROR2[ERROR2["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; - ERROR2[ERROR2["INVALID_STATUS"] = 13] = "INVALID_STATUS"; - ERROR2[ERROR2["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; - ERROR2[ERROR2["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; - ERROR2[ERROR2["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; - ERROR2[ERROR2["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; - ERROR2[ERROR2["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; - ERROR2[ERROR2["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; - ERROR2[ERROR2["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; - ERROR2[ERROR2["PAUSED"] = 21] = "PAUSED"; - ERROR2[ERROR2["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; - ERROR2[ERROR2["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; - ERROR2[ERROR2["USER"] = 24] = "USER"; - })(ERROR = exports2.ERROR || (exports2.ERROR = {})); - var TYPE; - (function(TYPE2) { - TYPE2[TYPE2["BOTH"] = 0] = "BOTH"; - TYPE2[TYPE2["REQUEST"] = 1] = "REQUEST"; - TYPE2[TYPE2["RESPONSE"] = 2] = "RESPONSE"; - })(TYPE = exports2.TYPE || (exports2.TYPE = {})); - var FLAGS; - (function(FLAGS2) { - FLAGS2[FLAGS2["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; - FLAGS2[FLAGS2["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; - FLAGS2[FLAGS2["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; - FLAGS2[FLAGS2["CHUNKED"] = 8] = "CHUNKED"; - FLAGS2[FLAGS2["UPGRADE"] = 16] = "UPGRADE"; - FLAGS2[FLAGS2["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; - FLAGS2[FLAGS2["SKIPBODY"] = 64] = "SKIPBODY"; - FLAGS2[FLAGS2["TRAILING"] = 128] = "TRAILING"; - FLAGS2[FLAGS2["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; - })(FLAGS = exports2.FLAGS || (exports2.FLAGS = {})); - var LENIENT_FLAGS; - (function(LENIENT_FLAGS2) { - LENIENT_FLAGS2[LENIENT_FLAGS2["HEADERS"] = 1] = "HEADERS"; - LENIENT_FLAGS2[LENIENT_FLAGS2["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; - LENIENT_FLAGS2[LENIENT_FLAGS2["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; - })(LENIENT_FLAGS = exports2.LENIENT_FLAGS || (exports2.LENIENT_FLAGS = {})); - var METHODS; - (function(METHODS2) { - METHODS2[METHODS2["DELETE"] = 0] = "DELETE"; - METHODS2[METHODS2["GET"] = 1] = "GET"; - METHODS2[METHODS2["HEAD"] = 2] = "HEAD"; - METHODS2[METHODS2["POST"] = 3] = "POST"; - METHODS2[METHODS2["PUT"] = 4] = "PUT"; - METHODS2[METHODS2["CONNECT"] = 5] = "CONNECT"; - METHODS2[METHODS2["OPTIONS"] = 6] = "OPTIONS"; - METHODS2[METHODS2["TRACE"] = 7] = "TRACE"; - METHODS2[METHODS2["COPY"] = 8] = "COPY"; - METHODS2[METHODS2["LOCK"] = 9] = "LOCK"; - METHODS2[METHODS2["MKCOL"] = 10] = "MKCOL"; - METHODS2[METHODS2["MOVE"] = 11] = "MOVE"; - METHODS2[METHODS2["PROPFIND"] = 12] = "PROPFIND"; - METHODS2[METHODS2["PROPPATCH"] = 13] = "PROPPATCH"; - METHODS2[METHODS2["SEARCH"] = 14] = "SEARCH"; - METHODS2[METHODS2["UNLOCK"] = 15] = "UNLOCK"; - METHODS2[METHODS2["BIND"] = 16] = "BIND"; - METHODS2[METHODS2["REBIND"] = 17] = "REBIND"; - METHODS2[METHODS2["UNBIND"] = 18] = "UNBIND"; - METHODS2[METHODS2["ACL"] = 19] = "ACL"; - METHODS2[METHODS2["REPORT"] = 20] = "REPORT"; - METHODS2[METHODS2["MKACTIVITY"] = 21] = "MKACTIVITY"; - METHODS2[METHODS2["CHECKOUT"] = 22] = "CHECKOUT"; - METHODS2[METHODS2["MERGE"] = 23] = "MERGE"; - METHODS2[METHODS2["M-SEARCH"] = 24] = "M-SEARCH"; - METHODS2[METHODS2["NOTIFY"] = 25] = "NOTIFY"; - METHODS2[METHODS2["SUBSCRIBE"] = 26] = "SUBSCRIBE"; - METHODS2[METHODS2["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; - METHODS2[METHODS2["PATCH"] = 28] = "PATCH"; - METHODS2[METHODS2["PURGE"] = 29] = "PURGE"; - METHODS2[METHODS2["MKCALENDAR"] = 30] = "MKCALENDAR"; - METHODS2[METHODS2["LINK"] = 31] = "LINK"; - METHODS2[METHODS2["UNLINK"] = 32] = "UNLINK"; - METHODS2[METHODS2["SOURCE"] = 33] = "SOURCE"; - METHODS2[METHODS2["PRI"] = 34] = "PRI"; - METHODS2[METHODS2["DESCRIBE"] = 35] = "DESCRIBE"; - METHODS2[METHODS2["ANNOUNCE"] = 36] = "ANNOUNCE"; - METHODS2[METHODS2["SETUP"] = 37] = "SETUP"; - METHODS2[METHODS2["PLAY"] = 38] = "PLAY"; - METHODS2[METHODS2["PAUSE"] = 39] = "PAUSE"; - METHODS2[METHODS2["TEARDOWN"] = 40] = "TEARDOWN"; - METHODS2[METHODS2["GET_PARAMETER"] = 41] = "GET_PARAMETER"; - METHODS2[METHODS2["SET_PARAMETER"] = 42] = "SET_PARAMETER"; - METHODS2[METHODS2["REDIRECT"] = 43] = "REDIRECT"; - METHODS2[METHODS2["RECORD"] = 44] = "RECORD"; - METHODS2[METHODS2["FLUSH"] = 45] = "FLUSH"; - })(METHODS = exports2.METHODS || (exports2.METHODS = {})); + exports2.ERROR = { + OK: 0, + INTERNAL: 1, + STRICT: 2, + CR_EXPECTED: 25, + LF_EXPECTED: 3, + UNEXPECTED_CONTENT_LENGTH: 4, + UNEXPECTED_SPACE: 30, + CLOSED_CONNECTION: 5, + INVALID_METHOD: 6, + INVALID_URL: 7, + INVALID_CONSTANT: 8, + INVALID_VERSION: 9, + INVALID_HEADER_TOKEN: 10, + INVALID_CONTENT_LENGTH: 11, + INVALID_CHUNK_SIZE: 12, + INVALID_STATUS: 13, + INVALID_EOF_STATE: 14, + INVALID_TRANSFER_ENCODING: 15, + CB_MESSAGE_BEGIN: 16, + CB_HEADERS_COMPLETE: 17, + CB_MESSAGE_COMPLETE: 18, + CB_CHUNK_HEADER: 19, + CB_CHUNK_COMPLETE: 20, + PAUSED: 21, + PAUSED_UPGRADE: 22, + PAUSED_H2_UPGRADE: 23, + USER: 24, + CB_URL_COMPLETE: 26, + CB_STATUS_COMPLETE: 27, + CB_METHOD_COMPLETE: 32, + CB_VERSION_COMPLETE: 33, + CB_HEADER_FIELD_COMPLETE: 28, + CB_HEADER_VALUE_COMPLETE: 29, + CB_CHUNK_EXTENSION_NAME_COMPLETE: 34, + CB_CHUNK_EXTENSION_VALUE_COMPLETE: 35, + CB_RESET: 31, + CB_PROTOCOL_COMPLETE: 38 + }; + exports2.TYPE = { + BOTH: 0, + // default + REQUEST: 1, + RESPONSE: 2 + }; + exports2.FLAGS = { + CONNECTION_KEEP_ALIVE: 1 << 0, + CONNECTION_CLOSE: 1 << 1, + CONNECTION_UPGRADE: 1 << 2, + CHUNKED: 1 << 3, + UPGRADE: 1 << 4, + CONTENT_LENGTH: 1 << 5, + SKIPBODY: 1 << 6, + TRAILING: 1 << 7, + // 1 << 8 is unused + TRANSFER_ENCODING: 1 << 9 + }; + exports2.LENIENT_FLAGS = { + HEADERS: 1 << 0, + CHUNKED_LENGTH: 1 << 1, + KEEP_ALIVE: 1 << 2, + TRANSFER_ENCODING: 1 << 3, + VERSION: 1 << 4, + DATA_AFTER_CLOSE: 1 << 5, + OPTIONAL_LF_AFTER_CR: 1 << 6, + OPTIONAL_CRLF_AFTER_CHUNK: 1 << 7, + OPTIONAL_CR_BEFORE_LF: 1 << 8, + SPACES_AFTER_CHUNK_SIZE: 1 << 9 + }; + exports2.METHODS = { + "DELETE": 0, + "GET": 1, + "HEAD": 2, + "POST": 3, + "PUT": 4, + /* pathological */ + "CONNECT": 5, + "OPTIONS": 6, + "TRACE": 7, + /* WebDAV */ + "COPY": 8, + "LOCK": 9, + "MKCOL": 10, + "MOVE": 11, + "PROPFIND": 12, + "PROPPATCH": 13, + "SEARCH": 14, + "UNLOCK": 15, + "BIND": 16, + "REBIND": 17, + "UNBIND": 18, + "ACL": 19, + /* subversion */ + "REPORT": 20, + "MKACTIVITY": 21, + "CHECKOUT": 22, + "MERGE": 23, + /* upnp */ + "M-SEARCH": 24, + "NOTIFY": 25, + "SUBSCRIBE": 26, + "UNSUBSCRIBE": 27, + /* RFC-5789 */ + "PATCH": 28, + "PURGE": 29, + /* CalDAV */ + "MKCALENDAR": 30, + /* RFC-2068, section 19.6.1.2 */ + "LINK": 31, + "UNLINK": 32, + /* icecast */ + "SOURCE": 33, + /* RFC-7540, section 11.6 */ + "PRI": 34, + /* RFC-2326 RTSP */ + "DESCRIBE": 35, + "ANNOUNCE": 36, + "SETUP": 37, + "PLAY": 38, + "PAUSE": 39, + "TEARDOWN": 40, + "GET_PARAMETER": 41, + "SET_PARAMETER": 42, + "REDIRECT": 43, + "RECORD": 44, + /* RAOP */ + "FLUSH": 45, + /* DRAFT https://www.ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-02.html */ + "QUERY": 46 + }; + exports2.STATUSES = { + CONTINUE: 100, + SWITCHING_PROTOCOLS: 101, + PROCESSING: 102, + EARLY_HINTS: 103, + RESPONSE_IS_STALE: 110, + // Unofficial + REVALIDATION_FAILED: 111, + // Unofficial + DISCONNECTED_OPERATION: 112, + // Unofficial + HEURISTIC_EXPIRATION: 113, + // Unofficial + MISCELLANEOUS_WARNING: 199, + // Unofficial + OK: 200, + CREATED: 201, + ACCEPTED: 202, + NON_AUTHORITATIVE_INFORMATION: 203, + NO_CONTENT: 204, + RESET_CONTENT: 205, + PARTIAL_CONTENT: 206, + MULTI_STATUS: 207, + ALREADY_REPORTED: 208, + TRANSFORMATION_APPLIED: 214, + // Unofficial + IM_USED: 226, + MISCELLANEOUS_PERSISTENT_WARNING: 299, + // Unofficial + MULTIPLE_CHOICES: 300, + MOVED_PERMANENTLY: 301, + FOUND: 302, + SEE_OTHER: 303, + NOT_MODIFIED: 304, + USE_PROXY: 305, + SWITCH_PROXY: 306, + // No longer used + TEMPORARY_REDIRECT: 307, + PERMANENT_REDIRECT: 308, + BAD_REQUEST: 400, + UNAUTHORIZED: 401, + PAYMENT_REQUIRED: 402, + FORBIDDEN: 403, + NOT_FOUND: 404, + METHOD_NOT_ALLOWED: 405, + NOT_ACCEPTABLE: 406, + PROXY_AUTHENTICATION_REQUIRED: 407, + REQUEST_TIMEOUT: 408, + CONFLICT: 409, + GONE: 410, + LENGTH_REQUIRED: 411, + PRECONDITION_FAILED: 412, + PAYLOAD_TOO_LARGE: 413, + URI_TOO_LONG: 414, + UNSUPPORTED_MEDIA_TYPE: 415, + RANGE_NOT_SATISFIABLE: 416, + EXPECTATION_FAILED: 417, + IM_A_TEAPOT: 418, + PAGE_EXPIRED: 419, + // Unofficial + ENHANCE_YOUR_CALM: 420, + // Unofficial + MISDIRECTED_REQUEST: 421, + UNPROCESSABLE_ENTITY: 422, + LOCKED: 423, + FAILED_DEPENDENCY: 424, + TOO_EARLY: 425, + UPGRADE_REQUIRED: 426, + PRECONDITION_REQUIRED: 428, + TOO_MANY_REQUESTS: 429, + REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL: 430, + // Unofficial + REQUEST_HEADER_FIELDS_TOO_LARGE: 431, + LOGIN_TIMEOUT: 440, + // Unofficial + NO_RESPONSE: 444, + // Unofficial + RETRY_WITH: 449, + // Unofficial + BLOCKED_BY_PARENTAL_CONTROL: 450, + // Unofficial + UNAVAILABLE_FOR_LEGAL_REASONS: 451, + CLIENT_CLOSED_LOAD_BALANCED_REQUEST: 460, + // Unofficial + INVALID_X_FORWARDED_FOR: 463, + // Unofficial + REQUEST_HEADER_TOO_LARGE: 494, + // Unofficial + SSL_CERTIFICATE_ERROR: 495, + // Unofficial + SSL_CERTIFICATE_REQUIRED: 496, + // Unofficial + HTTP_REQUEST_SENT_TO_HTTPS_PORT: 497, + // Unofficial + INVALID_TOKEN: 498, + // Unofficial + CLIENT_CLOSED_REQUEST: 499, + // Unofficial + INTERNAL_SERVER_ERROR: 500, + NOT_IMPLEMENTED: 501, + BAD_GATEWAY: 502, + SERVICE_UNAVAILABLE: 503, + GATEWAY_TIMEOUT: 504, + HTTP_VERSION_NOT_SUPPORTED: 505, + VARIANT_ALSO_NEGOTIATES: 506, + INSUFFICIENT_STORAGE: 507, + LOOP_DETECTED: 508, + BANDWIDTH_LIMIT_EXCEEDED: 509, + NOT_EXTENDED: 510, + NETWORK_AUTHENTICATION_REQUIRED: 511, + WEB_SERVER_UNKNOWN_ERROR: 520, + // Unofficial + WEB_SERVER_IS_DOWN: 521, + // Unofficial + CONNECTION_TIMEOUT: 522, + // Unofficial + ORIGIN_IS_UNREACHABLE: 523, + // Unofficial + TIMEOUT_OCCURED: 524, + // Unofficial + SSL_HANDSHAKE_FAILED: 525, + // Unofficial + INVALID_SSL_CERTIFICATE: 526, + // Unofficial + RAILGUN_ERROR: 527, + // Unofficial + SITE_IS_OVERLOADED: 529, + // Unofficial + SITE_IS_FROZEN: 530, + // Unofficial + IDENTITY_PROVIDER_AUTHENTICATION_ERROR: 561, + // Unofficial + NETWORK_READ_TIMEOUT: 598, + // Unofficial + NETWORK_CONNECT_TIMEOUT: 599 + // Unofficial + }; + exports2.FINISH = { + SAFE: 0, + SAFE_WITH_CB: 1, + UNSAFE: 2 + }; + exports2.HEADER_STATE = { + GENERAL: 0, + CONNECTION: 1, + CONTENT_LENGTH: 2, + TRANSFER_ENCODING: 3, + UPGRADE: 4, + CONNECTION_KEEP_ALIVE: 5, + CONNECTION_CLOSE: 6, + CONNECTION_UPGRADE: 7, + TRANSFER_ENCODING_CHUNKED: 8 + }; exports2.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, + exports2.METHODS.DELETE, + exports2.METHODS.GET, + exports2.METHODS.HEAD, + exports2.METHODS.POST, + exports2.METHODS.PUT, + exports2.METHODS.CONNECT, + exports2.METHODS.OPTIONS, + exports2.METHODS.TRACE, + exports2.METHODS.COPY, + exports2.METHODS.LOCK, + exports2.METHODS.MKCOL, + exports2.METHODS.MOVE, + exports2.METHODS.PROPFIND, + exports2.METHODS.PROPPATCH, + exports2.METHODS.SEARCH, + exports2.METHODS.UNLOCK, + exports2.METHODS.BIND, + exports2.METHODS.REBIND, + exports2.METHODS.UNBIND, + exports2.METHODS.ACL, + exports2.METHODS.REPORT, + exports2.METHODS.MKACTIVITY, + exports2.METHODS.CHECKOUT, + exports2.METHODS.MERGE, + exports2.METHODS["M-SEARCH"], + exports2.METHODS.NOTIFY, + exports2.METHODS.SUBSCRIBE, + exports2.METHODS.UNSUBSCRIBE, + exports2.METHODS.PATCH, + exports2.METHODS.PURGE, + exports2.METHODS.MKCALENDAR, + exports2.METHODS.LINK, + exports2.METHODS.UNLINK, + exports2.METHODS.PRI, // TODO(indutny): should we allow it with HTTP? - METHODS.SOURCE + exports2.METHODS.SOURCE, + exports2.METHODS.QUERY ]; exports2.METHODS_ICE = [ - METHODS.SOURCE + exports2.METHODS.SOURCE ]; exports2.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, + exports2.METHODS.OPTIONS, + exports2.METHODS.DESCRIBE, + exports2.METHODS.ANNOUNCE, + exports2.METHODS.SETUP, + exports2.METHODS.PLAY, + exports2.METHODS.PAUSE, + exports2.METHODS.TEARDOWN, + exports2.METHODS.GET_PARAMETER, + exports2.METHODS.SET_PARAMETER, + exports2.METHODS.REDIRECT, + exports2.METHODS.RECORD, + exports2.METHODS.FLUSH, // For AirPlay - METHODS.GET, - METHODS.POST + exports2.METHODS.GET, + exports2.METHODS.POST + ]; + exports2.METHOD_MAP = (0, utils_1.enumToMap)(exports2.METHODS); + exports2.H_METHOD_MAP = Object.fromEntries(Object.entries(exports2.METHODS).filter(([k]) => k.startsWith("H"))); + exports2.STATUSES_HTTP = [ + exports2.STATUSES.CONTINUE, + exports2.STATUSES.SWITCHING_PROTOCOLS, + exports2.STATUSES.PROCESSING, + exports2.STATUSES.EARLY_HINTS, + exports2.STATUSES.RESPONSE_IS_STALE, + exports2.STATUSES.REVALIDATION_FAILED, + exports2.STATUSES.DISCONNECTED_OPERATION, + exports2.STATUSES.HEURISTIC_EXPIRATION, + exports2.STATUSES.MISCELLANEOUS_WARNING, + exports2.STATUSES.OK, + exports2.STATUSES.CREATED, + exports2.STATUSES.ACCEPTED, + exports2.STATUSES.NON_AUTHORITATIVE_INFORMATION, + exports2.STATUSES.NO_CONTENT, + exports2.STATUSES.RESET_CONTENT, + exports2.STATUSES.PARTIAL_CONTENT, + exports2.STATUSES.MULTI_STATUS, + exports2.STATUSES.ALREADY_REPORTED, + exports2.STATUSES.TRANSFORMATION_APPLIED, + exports2.STATUSES.IM_USED, + exports2.STATUSES.MISCELLANEOUS_PERSISTENT_WARNING, + exports2.STATUSES.MULTIPLE_CHOICES, + exports2.STATUSES.MOVED_PERMANENTLY, + exports2.STATUSES.FOUND, + exports2.STATUSES.SEE_OTHER, + exports2.STATUSES.NOT_MODIFIED, + exports2.STATUSES.USE_PROXY, + exports2.STATUSES.SWITCH_PROXY, + exports2.STATUSES.TEMPORARY_REDIRECT, + exports2.STATUSES.PERMANENT_REDIRECT, + exports2.STATUSES.BAD_REQUEST, + exports2.STATUSES.UNAUTHORIZED, + exports2.STATUSES.PAYMENT_REQUIRED, + exports2.STATUSES.FORBIDDEN, + exports2.STATUSES.NOT_FOUND, + exports2.STATUSES.METHOD_NOT_ALLOWED, + exports2.STATUSES.NOT_ACCEPTABLE, + exports2.STATUSES.PROXY_AUTHENTICATION_REQUIRED, + exports2.STATUSES.REQUEST_TIMEOUT, + exports2.STATUSES.CONFLICT, + exports2.STATUSES.GONE, + exports2.STATUSES.LENGTH_REQUIRED, + exports2.STATUSES.PRECONDITION_FAILED, + exports2.STATUSES.PAYLOAD_TOO_LARGE, + exports2.STATUSES.URI_TOO_LONG, + exports2.STATUSES.UNSUPPORTED_MEDIA_TYPE, + exports2.STATUSES.RANGE_NOT_SATISFIABLE, + exports2.STATUSES.EXPECTATION_FAILED, + exports2.STATUSES.IM_A_TEAPOT, + exports2.STATUSES.PAGE_EXPIRED, + exports2.STATUSES.ENHANCE_YOUR_CALM, + exports2.STATUSES.MISDIRECTED_REQUEST, + exports2.STATUSES.UNPROCESSABLE_ENTITY, + exports2.STATUSES.LOCKED, + exports2.STATUSES.FAILED_DEPENDENCY, + exports2.STATUSES.TOO_EARLY, + exports2.STATUSES.UPGRADE_REQUIRED, + exports2.STATUSES.PRECONDITION_REQUIRED, + exports2.STATUSES.TOO_MANY_REQUESTS, + exports2.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL, + exports2.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE, + exports2.STATUSES.LOGIN_TIMEOUT, + exports2.STATUSES.NO_RESPONSE, + exports2.STATUSES.RETRY_WITH, + exports2.STATUSES.BLOCKED_BY_PARENTAL_CONTROL, + exports2.STATUSES.UNAVAILABLE_FOR_LEGAL_REASONS, + exports2.STATUSES.CLIENT_CLOSED_LOAD_BALANCED_REQUEST, + exports2.STATUSES.INVALID_X_FORWARDED_FOR, + exports2.STATUSES.REQUEST_HEADER_TOO_LARGE, + exports2.STATUSES.SSL_CERTIFICATE_ERROR, + exports2.STATUSES.SSL_CERTIFICATE_REQUIRED, + exports2.STATUSES.HTTP_REQUEST_SENT_TO_HTTPS_PORT, + exports2.STATUSES.INVALID_TOKEN, + exports2.STATUSES.CLIENT_CLOSED_REQUEST, + exports2.STATUSES.INTERNAL_SERVER_ERROR, + exports2.STATUSES.NOT_IMPLEMENTED, + exports2.STATUSES.BAD_GATEWAY, + exports2.STATUSES.SERVICE_UNAVAILABLE, + exports2.STATUSES.GATEWAY_TIMEOUT, + exports2.STATUSES.HTTP_VERSION_NOT_SUPPORTED, + exports2.STATUSES.VARIANT_ALSO_NEGOTIATES, + exports2.STATUSES.INSUFFICIENT_STORAGE, + exports2.STATUSES.LOOP_DETECTED, + exports2.STATUSES.BANDWIDTH_LIMIT_EXCEEDED, + exports2.STATUSES.NOT_EXTENDED, + exports2.STATUSES.NETWORK_AUTHENTICATION_REQUIRED, + exports2.STATUSES.WEB_SERVER_UNKNOWN_ERROR, + exports2.STATUSES.WEB_SERVER_IS_DOWN, + exports2.STATUSES.CONNECTION_TIMEOUT, + exports2.STATUSES.ORIGIN_IS_UNREACHABLE, + exports2.STATUSES.TIMEOUT_OCCURED, + exports2.STATUSES.SSL_HANDSHAKE_FAILED, + exports2.STATUSES.INVALID_SSL_CERTIFICATE, + exports2.STATUSES.RAILGUN_ERROR, + exports2.STATUSES.SITE_IS_OVERLOADED, + exports2.STATUSES.SITE_IS_FROZEN, + exports2.STATUSES.IDENTITY_PROVIDER_AUTHENTICATION_ERROR, + exports2.STATUSES.NETWORK_READ_TIMEOUT, + exports2.STATUSES.NETWORK_CONNECT_TIMEOUT ]; - exports2.METHOD_MAP = utils_1.enumToMap(METHODS); - exports2.H_METHOD_MAP = {}; - Object.keys(exports2.METHOD_MAP).forEach((key) => { - if (/^H/.test(key)) { - exports2.H_METHOD_MAP[key] = exports2.METHOD_MAP[key]; - } - }); - var FINISH; - (function(FINISH2) { - FINISH2[FINISH2["SAFE"] = 0] = "SAFE"; - FINISH2[FINISH2["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; - FINISH2[FINISH2["UNSAFE"] = 2] = "UNSAFE"; - })(FINISH = exports2.FINISH || (exports2.FINISH = {})); exports2.ALPHA = []; for (let i = "A".charCodeAt(0); i <= "Z".charCodeAt(0); i++) { exports2.ALPHA.push(String.fromCharCode(i)); @@ -3167,7 +4047,7 @@ var require_constants2 = __commonJS({ exports2.ALPHANUM = exports2.ALPHA.concat(exports2.NUM); exports2.MARK = ["-", "_", ".", "!", "~", "*", "'", "(", ")"]; exports2.USERINFO_CHARS = exports2.ALPHANUM.concat(exports2.MARK).concat(["%", ";", ":", "&", "=", "+", "$", ","]); - exports2.STRICT_URL_CHAR = [ + exports2.URL_CHAR = [ "!", '"', "$", @@ -3199,12 +4079,8 @@ var require_constants2 = __commonJS({ "}", "~" ].concat(exports2.ALPHANUM); - exports2.URL_CHAR = exports2.STRICT_URL_CHAR.concat([" ", "\f"]); - for (let i = 128; i <= 255; i++) { - exports2.URL_CHAR.push(i); - } exports2.HEX = exports2.NUM.concat(["a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"]); - exports2.STRICT_TOKEN = [ + exports2.TOKEN = [ "!", "#", "$", @@ -3221,7 +4097,6 @@ var require_constants2 = __commonJS({ "|", "~" ].concat(exports2.ALPHANUM); - exports2.TOKEN = exports2.STRICT_TOKEN.concat([" "]); exports2.HEADER_CHARS = [" "]; for (let i = 32; i <= 255; i++) { if (i !== 127) { @@ -3229,26 +4104,60 @@ var require_constants2 = __commonJS({ } } exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS.filter((c) => c !== 44); + exports2.QUOTED_STRING = [" ", " "]; + for (let i = 33; i <= 255; i++) { + if (i !== 34 && i !== 92) { + exports2.QUOTED_STRING.push(i); + } + } + exports2.HTAB_SP_VCHAR_OBS_TEXT = [" ", " "]; + for (let i = 33; i <= 126; i++) { + exports2.HTAB_SP_VCHAR_OBS_TEXT.push(i); + } + for (let i = 128; i <= 255; i++) { + exports2.HTAB_SP_VCHAR_OBS_TEXT.push(i); + } exports2.MAJOR = exports2.NUM_MAP; exports2.MINOR = exports2.MAJOR; - var HEADER_STATE; - (function(HEADER_STATE2) { - HEADER_STATE2[HEADER_STATE2["GENERAL"] = 0] = "GENERAL"; - HEADER_STATE2[HEADER_STATE2["CONNECTION"] = 1] = "CONNECTION"; - HEADER_STATE2[HEADER_STATE2["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; - HEADER_STATE2[HEADER_STATE2["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; - HEADER_STATE2[HEADER_STATE2["UPGRADE"] = 4] = "UPGRADE"; - HEADER_STATE2[HEADER_STATE2["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; - HEADER_STATE2[HEADER_STATE2["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; - HEADER_STATE2[HEADER_STATE2["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; - HEADER_STATE2[HEADER_STATE2["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; - })(HEADER_STATE = exports2.HEADER_STATE || (exports2.HEADER_STATE = {})); exports2.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 + "connection": exports2.HEADER_STATE.CONNECTION, + "content-length": exports2.HEADER_STATE.CONTENT_LENGTH, + "proxy-connection": exports2.HEADER_STATE.CONNECTION, + "transfer-encoding": exports2.HEADER_STATE.TRANSFER_ENCODING, + "upgrade": exports2.HEADER_STATE.UPGRADE + }; + exports2.default = { + ERROR: exports2.ERROR, + TYPE: exports2.TYPE, + FLAGS: exports2.FLAGS, + LENIENT_FLAGS: exports2.LENIENT_FLAGS, + METHODS: exports2.METHODS, + STATUSES: exports2.STATUSES, + FINISH: exports2.FINISH, + HEADER_STATE: exports2.HEADER_STATE, + ALPHA: exports2.ALPHA, + NUM_MAP: exports2.NUM_MAP, + HEX_MAP: exports2.HEX_MAP, + NUM: exports2.NUM, + ALPHANUM: exports2.ALPHANUM, + MARK: exports2.MARK, + USERINFO_CHARS: exports2.USERINFO_CHARS, + URL_CHAR: exports2.URL_CHAR, + HEX: exports2.HEX, + TOKEN: exports2.TOKEN, + HEADER_CHARS: exports2.HEADER_CHARS, + CONNECTION_TOKEN_CHARS: exports2.CONNECTION_TOKEN_CHARS, + QUOTED_STRING: exports2.QUOTED_STRING, + HTAB_SP_VCHAR_OBS_TEXT: exports2.HTAB_SP_VCHAR_OBS_TEXT, + MAJOR: exports2.MAJOR, + MINOR: exports2.MINOR, + SPECIAL_HEADERS: exports2.SPECIAL_HEADERS, + METHODS_HTTP: exports2.METHODS_HTTP, + METHODS_ICE: exports2.METHODS_ICE, + METHODS_RTSP: exports2.METHODS_RTSP, + METHOD_MAP: exports2.METHOD_MAP, + H_METHOD_MAP: exports2.H_METHOD_MAP, + STATUSES_HTTP: exports2.STATUSES_HTTP }; } }); @@ -3257,8 +4166,14 @@ var require_constants2 = __commonJS({ var require_llhttp_wasm = __commonJS({ "node_modules/undici/lib/llhttp/llhttp-wasm.js"(exports2, module2) { "use strict"; - var { Buffer: Buffer2 } = require("node:buffer"); - module2.exports = Buffer2.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"); + var { Buffer: Buffer3 } = require("node:buffer"); + var wasmBase64 = "AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzU0BQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEBAwAAAwAAAAQFAXABExMFAwEAAgYIAX8BQcDZBAsHxQcoBm1lbW9yeQIAC19pbml0aWFsaXplAAgZX19pbmRpcmVjdF9mdW5jdGlvbl90YWJsZQEAC2xsaHR0cF9pbml0AAkYbGxodHRwX3Nob3VsZF9rZWVwX2FsaXZlADcMbGxodHRwX2FsbG9jAAsGbWFsbG9jADkLbGxodHRwX2ZyZWUADARmcmVlAAwPbGxodHRwX2dldF90eXBlAA0VbGxodHRwX2dldF9odHRwX21ham9yAA4VbGxodHRwX2dldF9odHRwX21pbm9yAA8RbGxodHRwX2dldF9tZXRob2QAEBZsbGh0dHBfZ2V0X3N0YXR1c19jb2RlABESbGxodHRwX2dldF91cGdyYWRlABIMbGxodHRwX3Jlc2V0ABMObGxodHRwX2V4ZWN1dGUAFBRsbGh0dHBfc2V0dGluZ3NfaW5pdAAVDWxsaHR0cF9maW5pc2gAFgxsbGh0dHBfcGF1c2UAFw1sbGh0dHBfcmVzdW1lABgbbGxodHRwX3Jlc3VtZV9hZnRlcl91cGdyYWRlABkQbGxodHRwX2dldF9lcnJubwAaF2xsaHR0cF9nZXRfZXJyb3JfcmVhc29uABsXbGxodHRwX3NldF9lcnJvcl9yZWFzb24AHBRsbGh0dHBfZ2V0X2Vycm9yX3BvcwAdEWxsaHR0cF9lcnJub19uYW1lAB4SbGxodHRwX21ldGhvZF9uYW1lAB8SbGxodHRwX3N0YXR1c19uYW1lACAabGxodHRwX3NldF9sZW5pZW50X2hlYWRlcnMAISFsbGh0dHBfc2V0X2xlbmllbnRfY2h1bmtlZF9sZW5ndGgAIh1sbGh0dHBfc2V0X2xlbmllbnRfa2VlcF9hbGl2ZQAjJGxsaHR0cF9zZXRfbGVuaWVudF90cmFuc2Zlcl9lbmNvZGluZwAkGmxsaHR0cF9zZXRfbGVuaWVudF92ZXJzaW9uACUjbGxodHRwX3NldF9sZW5pZW50X2RhdGFfYWZ0ZXJfY2xvc2UAJidsbGh0dHBfc2V0X2xlbmllbnRfb3B0aW9uYWxfbGZfYWZ0ZXJfY3IAJyxsbGh0dHBfc2V0X2xlbmllbnRfb3B0aW9uYWxfY3JsZl9hZnRlcl9jaHVuawAoKGxsaHR0cF9zZXRfbGVuaWVudF9vcHRpb25hbF9jcl9iZWZvcmVfbGYAKSpsbGh0dHBfc2V0X2xlbmllbnRfc3BhY2VzX2FmdGVyX2NodW5rX3NpemUAKhhsbGh0dHBfbWVzc2FnZV9uZWVkc19lb2YANgkYAQBBAQsSAQIDBAUKBgcyNDMuKy8tLDAxCq/ZAjQWAEHA1QAoAgAEQAALQcDVAEEBNgIACxQAIAAQOCAAIAI2AjggACABOgAoCxQAIAAgAC8BNCAALQAwIAAQNxAACx4BAX9BwAAQOiIBEDggAUGACDYCOCABIAA6ACggAQuPDAEHfwJAIABFDQAgAEEIayIBIABBBGsoAgAiAEF4cSIEaiEFAkAgAEEBcQ0AIABBA3FFDQEgASABKAIAIgBrIgFB1NUAKAIASQ0BIAAgBGohBAJAAkBB2NUAKAIAIAFHBEAgAEH/AU0EQCAAQQN2IQMgASgCCCIAIAEoAgwiAkYEQEHE1QBBxNUAKAIAQX4gA3dxNgIADAULIAIgADYCCCAAIAI2AgwMBAsgASgCGCEGIAEgASgCDCIARwRAIAAgASgCCCICNgIIIAIgADYCDAwDCyABQRRqIgMoAgAiAkUEQCABKAIQIgJFDQIgAUEQaiEDCwNAIAMhByACIgBBFGoiAygCACICDQAgAEEQaiEDIAAoAhAiAg0ACyAHQQA2AgAMAgsgBSgCBCIAQQNxQQNHDQIgBSAAQX5xNgIEQczVACAENgIAIAUgBDYCACABIARBAXI2AgQMAwtBACEACyAGRQ0AAkAgASgCHCICQQJ0QfTXAGoiAygCACABRgRAIAMgADYCACAADQFByNUAQcjVACgCAEF+IAJ3cTYCAAwCCyAGQRBBFCAGKAIQIAFGG2ogADYCACAARQ0BCyAAIAY2AhggASgCECICBEAgACACNgIQIAIgADYCGAsgAUEUaigCACICRQ0AIABBFGogAjYCACACIAA2AhgLIAEgBU8NACAFKAIEIgBBAXFFDQACQAJAAkACQCAAQQJxRQRAQdzVACgCACAFRgRAQdzVACABNgIAQdDVAEHQ1QAoAgAgBGoiADYCACABIABBAXI2AgQgAUHY1QAoAgBHDQZBzNUAQQA2AgBB2NUAQQA2AgAMBgtB2NUAKAIAIAVGBEBB2NUAIAE2AgBBzNUAQczVACgCACAEaiIANgIAIAEgAEEBcjYCBCAAIAFqIAA2AgAMBgsgAEF4cSAEaiEEIABB/wFNBEAgAEEDdiEDIAUoAggiACAFKAIMIgJGBEBBxNUAQcTVACgCAEF+IAN3cTYCAAwFCyACIAA2AgggACACNgIMDAQLIAUoAhghBiAFIAUoAgwiAEcEQEHU1QAoAgAaIAAgBSgCCCICNgIIIAIgADYCDAwDCyAFQRRqIgMoAgAiAkUEQCAFKAIQIgJFDQIgBUEQaiEDCwNAIAMhByACIgBBFGoiAygCACICDQAgAEEQaiEDIAAoAhAiAg0ACyAHQQA2AgAMAgsgBSAAQX5xNgIEIAEgBGogBDYCACABIARBAXI2AgQMAwtBACEACyAGRQ0AAkAgBSgCHCICQQJ0QfTXAGoiAygCACAFRgRAIAMgADYCACAADQFByNUAQcjVACgCAEF+IAJ3cTYCAAwCCyAGQRBBFCAGKAIQIAVGG2ogADYCACAARQ0BCyAAIAY2AhggBSgCECICBEAgACACNgIQIAIgADYCGAsgBUEUaigCACICRQ0AIABBFGogAjYCACACIAA2AhgLIAEgBGogBDYCACABIARBAXI2AgQgAUHY1QAoAgBHDQBBzNUAIAQ2AgAMAQsgBEH/AU0EQCAEQXhxQezVAGohAAJ/QcTVACgCACICQQEgBEEDdnQiA3FFBEBBxNUAIAIgA3I2AgAgAAwBCyAAKAIICyICIAE2AgwgACABNgIIIAEgADYCDCABIAI2AggMAQtBHyECIARB////B00EQCAEQSYgBEEIdmciAGt2QQFxIABBAXRrQT5qIQILIAEgAjYCHCABQgA3AhAgAkECdEH01wBqIQACQEHI1QAoAgAiA0EBIAJ0IgdxRQRAIAAgATYCAEHI1QAgAyAHcjYCACABIAA2AhggASABNgIIIAEgATYCDAwBCyAEQRkgAkEBdmtBACACQR9HG3QhAiAAKAIAIQACQANAIAAiAygCBEF4cSAERg0BIAJBHXYhACACQQF0IQIgAyAAQQRxakEQaiIHKAIAIgANAAsgByABNgIAIAEgAzYCGCABIAE2AgwgASABNgIIDAELIAMoAggiACABNgIMIAMgATYCCCABQQA2AhggASADNgIMIAEgADYCCAtB5NUAQeTVACgCAEEBayIAQX8gABs2AgALCwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgL5YUCAgd/A34gASACaiEEAkAgACIDKAIMIgANACADKAIEBEAgAyABNgIECyMAQRBrIgkkAAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAygCHCICQQJrDvwBAfkBAgMEBQYHCAkKCwwNDg8QERL4ARP3ARQV9gEWF/UBGBkaGxwdHh8g/QH7ASH0ASIjJCUmJygpKivzASwtLi8wMTLyAfEBMzTwAe8BNTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5P+gFQUVJT7gHtAVTsAVXrAVZXWFla6gFbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AbgBuQG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAccByAHJAcoBywHMAc0BzgHpAegBzwHnAdAB5gHRAdIB0wHUAeUB1QHWAdcB2AHZAdoB2wHcAd0B3gHfAeAB4QHiAeMBAPwBC0EADOMBC0EODOIBC0ENDOEBC0EPDOABC0EQDN8BC0ETDN4BC0EUDN0BC0EVDNwBC0EWDNsBC0EXDNoBC0EYDNkBC0EZDNgBC0EaDNcBC0EbDNYBC0EcDNUBC0EdDNQBC0EeDNMBC0EfDNIBC0EgDNEBC0EhDNABC0EIDM8BC0EiDM4BC0EkDM0BC0EjDMwBC0EHDMsBC0ElDMoBC0EmDMkBC0EnDMgBC0EoDMcBC0ESDMYBC0ERDMUBC0EpDMQBC0EqDMMBC0ErDMIBC0EsDMEBC0HeAQzAAQtBLgy/AQtBLwy+AQtBMAy9AQtBMQy8AQtBMgy7AQtBMwy6AQtBNAy5AQtB3wEMuAELQTUMtwELQTkMtgELQQwMtQELQTYMtAELQTcMswELQTgMsgELQT4MsQELQToMsAELQeABDK8BC0ELDK4BC0E/DK0BC0E7DKwBC0EKDKsBC0E8DKoBC0E9DKkBC0HhAQyoAQtBwQAMpwELQcAADKYBC0HCAAylAQtBCQykAQtBLQyjAQtBwwAMogELQcQADKEBC0HFAAygAQtBxgAMnwELQccADJ4BC0HIAAydAQtByQAMnAELQcoADJsBC0HLAAyaAQtBzAAMmQELQc0ADJgBC0HOAAyXAQtBzwAMlgELQdAADJUBC0HRAAyUAQtB0gAMkwELQdMADJIBC0HVAAyRAQtB1AAMkAELQdYADI8BC0HXAAyOAQtB2AAMjQELQdkADIwBC0HaAAyLAQtB2wAMigELQdwADIkBC0HdAAyIAQtB3gAMhwELQd8ADIYBC0HgAAyFAQtB4QAMhAELQeIADIMBC0HjAAyCAQtB5AAMgQELQeUADIABC0HiAQx/C0HmAAx+C0HnAAx9C0EGDHwLQegADHsLQQUMegtB6QAMeQtBBAx4C0HqAAx3C0HrAAx2C0HsAAx1C0HtAAx0C0EDDHMLQe4ADHILQe8ADHELQfAADHALQfIADG8LQfEADG4LQfMADG0LQfQADGwLQfUADGsLQfYADGoLQQIMaQtB9wAMaAtB+AAMZwtB+QAMZgtB+gAMZQtB+wAMZAtB/AAMYwtB/QAMYgtB/gAMYQtB/wAMYAtBgAEMXwtBgQEMXgtBggEMXQtBgwEMXAtBhAEMWwtBhQEMWgtBhgEMWQtBhwEMWAtBiAEMVwtBiQEMVgtBigEMVQtBiwEMVAtBjAEMUwtBjQEMUgtBjgEMUQtBjwEMUAtBkAEMTwtBkQEMTgtBkgEMTQtBkwEMTAtBlAEMSwtBlQEMSgtBlgEMSQtBlwEMSAtBmAEMRwtBmQEMRgtBmgEMRQtBmwEMRAtBnAEMQwtBnQEMQgtBngEMQQtBnwEMQAtBoAEMPwtBoQEMPgtBogEMPQtBowEMPAtBpAEMOwtBpQEMOgtBpgEMOQtBpwEMOAtBqAEMNwtBqQEMNgtBqgEMNQtBqwEMNAtBrAEMMwtBrQEMMgtBrgEMMQtBrwEMMAtBsAEMLwtBsQEMLgtBsgEMLQtBswEMLAtBtAEMKwtBtQEMKgtBtgEMKQtBtwEMKAtBuAEMJwtBuQEMJgtBugEMJQtBuwEMJAtBvAEMIwtBvQEMIgtBvgEMIQtBvwEMIAtBwAEMHwtBwQEMHgtBwgEMHQtBAQwcC0HDAQwbC0HEAQwaC0HFAQwZC0HGAQwYC0HHAQwXC0HIAQwWC0HJAQwVC0HKAQwUC0HLAQwTC0HMAQwSC0HNAQwRC0HOAQwQC0HPAQwPC0HQAQwOC0HRAQwNC0HSAQwMC0HTAQwLC0HUAQwKC0HVAQwJC0HWAQwIC0HjAQwHC0HXAQwGC0HYAQwFC0HZAQwEC0HaAQwDC0HbAQwCC0HdAQwBC0HcAQshAgNAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJ/AkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAg7jAQABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEjJCUnKCmeA5sDmgORA4oDgwOAA/0C+wL4AvIC8QLvAu0C6ALnAuYC5QLkAtwC2wLaAtkC2ALXAtYC1QLPAs4CzALLAsoCyQLIAscCxgLEAsMCvgK8AroCuQK4ArcCtgK1ArQCswKyArECsAKuAq0CqQKoAqcCpgKlAqQCowKiAqECoAKfApgCkAKMAosCigKBAv4B/QH8AfsB+gH5AfgB9wH1AfMB8AHrAekB6AHnAeYB5QHkAeMB4gHhAeAB3wHeAd0B3AHaAdkB2AHXAdYB1QHUAdMB0gHRAdABzwHOAc0BzAHLAcoByQHIAccBxgHFAcQBwwHCAcEBwAG/Ab4BvQG8AbsBugG5AbgBtwG2AbUBtAGzAbIBsQGwAa8BrgGtAawBqwGqAakBqAGnAaYBpQGkAaMBogGfAZ4BmQGYAZcBlgGVAZQBkwGSAZEBkAGPAY0BjAGHAYYBhQGEAYMBggF9fHt6eXZ1dFBRUlNUVQsgASAERw1yQf0BIQIMvgMLIAEgBEcNmAFB2wEhAgy9AwsgASAERw3xAUGOASECDLwDCyABIARHDfwBQYQBIQIMuwMLIAEgBEcNigJB/wAhAgy6AwsgASAERw2RAkH9ACECDLkDCyABIARHDZQCQfsAIQIMuAMLIAEgBEcNHkEeIQIMtwMLIAEgBEcNGUEYIQIMtgMLIAEgBEcNygJBzQAhAgy1AwsgASAERw3VAkHGACECDLQDCyABIARHDdYCQcMAIQIMswMLIAEgBEcN3AJBOCECDLIDCyADLQAwQQFGDa0DDIkDC0EAIQACQAJAAkAgAy0AKkUNACADLQArRQ0AIAMvATIiAkECcUUNAQwCCyADLwEyIgJBAXFFDQELQQEhACADLQAoQQFGDQAgAy8BNCIGQeQAa0HkAEkNACAGQcwBRg0AIAZBsAJGDQAgAkHAAHENAEEAIQAgAkGIBHFBgARGDQAgAkEocUEARyEACyADQQA7ATIgA0EAOgAxAkAgAEUEQCADQQA6ADEgAy0ALkEEcQ0BDLEDCyADQgA3AyALIANBADoAMSADQQE6ADYMSAtBACEAAkAgAygCOCICRQ0AIAIoAjAiAkUNACADIAIRAAAhAAsgAEUNSCAAQRVHDWIgA0EENgIcIAMgATYCFCADQdIbNgIQIANBFTYCDEEAIQIMrwMLIAEgBEYEQEEGIQIMrwMLIAEtAABBCkcNGSABQQFqIQEMGgsgA0IANwMgQRIhAgyUAwsgASAERw2KA0EjIQIMrAMLIAEgBEYEQEEHIQIMrAMLAkACQCABLQAAQQprDgQBGBgAGAsgAUEBaiEBQRAhAgyTAwsgAUEBaiEBIANBL2otAABBAXENF0EAIQIgA0EANgIcIAMgATYCFCADQZkgNgIQIANBGTYCDAyrAwsgAyADKQMgIgwgBCABa60iCn0iC0IAIAsgDFgbNwMgIAogDFoNGEEIIQIMqgMLIAEgBEcEQCADQQk2AgggAyABNgIEQRQhAgyRAwtBCSECDKkDCyADKQMgUA2uAgxDCyABIARGBEBBCyECDKgDCyABLQAAQQpHDRYgAUEBaiEBDBcLIANBL2otAABBAXFFDRkMJgtBACEAAkAgAygCOCICRQ0AIAIoAlAiAkUNACADIAIRAAAhAAsgAA0ZDEILQQAhAAJAIAMoAjgiAkUNACACKAJQIgJFDQAgAyACEQAAIQALIAANGgwkC0EAIQACQCADKAI4IgJFDQAgAigCUCICRQ0AIAMgAhEAACEACyAADRsMMgsgA0Evai0AAEEBcUUNHAwiC0EAIQACQCADKAI4IgJFDQAgAigCVCICRQ0AIAMgAhEAACEACyAADRwMQgtBACEAAkAgAygCOCICRQ0AIAIoAlQiAkUNACADIAIRAAAhAAsgAA0dDCALIAEgBEYEQEETIQIMoAMLAkAgAS0AACIAQQprDgQfIyMAIgsgAUEBaiEBDB8LQQAhAAJAIAMoAjgiAkUNACACKAJUIgJFDQAgAyACEQAAIQALIAANIgxCCyABIARGBEBBFiECDJ4DCyABLQAAQcDBAGotAABBAUcNIwyDAwsCQANAIAEtAABBsDtqLQAAIgBBAUcEQAJAIABBAmsOAgMAJwsgAUEBaiEBQSEhAgyGAwsgBCABQQFqIgFHDQALQRghAgydAwsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAFBAWoiARA0IgANIQxBC0EAIQACQCADKAI4IgJFDQAgAigCVCICRQ0AIAMgAhEAACEACyAADSMMKgsgASAERgRAQRwhAgybAwsgA0EKNgIIIAMgATYCBEEAIQACQCADKAI4IgJFDQAgAigCUCICRQ0AIAMgAhEAACEACyAADSVBJCECDIEDCyABIARHBEADQCABLQAAQbA9ai0AACIAQQNHBEAgAEEBaw4FGBomggMlJgsgBCABQQFqIgFHDQALQRshAgyaAwtBGyECDJkDCwNAIAEtAABBsD9qLQAAIgBBA0cEQCAAQQFrDgUPEScTJicLIAQgAUEBaiIBRw0AC0EeIQIMmAMLIAEgBEcEQCADQQs2AgggAyABNgIEQQchAgz/AgtBHyECDJcDCyABIARGBEBBICECDJcDCwJAIAEtAABBDWsOFC4/Pz8/Pz8/Pz8/Pz8/Pz8/Pz8APwtBACECIANBADYCHCADQb8LNgIQIANBAjYCDCADIAFBAWo2AhQMlgMLIANBL2ohAgNAIAEgBEYEQEEhIQIMlwMLAkACQAJAIAEtAAAiAEEJaw4YAgApKQEpKSkpKSkpKSkpKSkpKSkpKSkCJwsgAUEBaiEBIANBL2otAABBAXFFDQoMGAsgAUEBaiEBDBcLIAFBAWohASACLQAAQQJxDQALQQAhAiADQQA2AhwgAyABNgIUIANBnxU2AhAgA0EMNgIMDJUDCyADLQAuQYABcUUNAQtBACEAAkAgAygCOCICRQ0AIAIoAlwiAkUNACADIAIRAAAhAAsgAEUN5gIgAEEVRgRAIANBJDYCHCADIAE2AhQgA0GbGzYCECADQRU2AgxBACECDJQDC0EAIQIgA0EANgIcIAMgATYCFCADQZAONgIQIANBFDYCDAyTAwtBACECIANBADYCHCADIAE2AhQgA0G+IDYCECADQQI2AgwMkgMLIAMoAgQhAEEAIQIgA0EANgIEIAMgACABIAynaiIBEDIiAEUNKyADQQc2AhwgAyABNgIUIAMgADYCDAyRAwsgAy0ALkHAAHFFDQELQQAhAAJAIAMoAjgiAkUNACACKAJYIgJFDQAgAyACEQAAIQALIABFDSsgAEEVRgRAIANBCjYCHCADIAE2AhQgA0HrGTYCECADQRU2AgxBACECDJADC0EAIQIgA0EANgIcIAMgATYCFCADQZMMNgIQIANBEzYCDAyPAwtBACECIANBADYCHCADIAE2AhQgA0GCFTYCECADQQI2AgwMjgMLQQAhAiADQQA2AhwgAyABNgIUIANB3RQ2AhAgA0EZNgIMDI0DC0EAIQIgA0EANgIcIAMgATYCFCADQeYdNgIQIANBGTYCDAyMAwsgAEEVRg09QQAhAiADQQA2AhwgAyABNgIUIANB0A82AhAgA0EiNgIMDIsDCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFDSggA0ENNgIcIAMgATYCFCADIAA2AgwMigMLIABBFUYNOkEAIQIgA0EANgIcIAMgATYCFCADQdAPNgIQIANBIjYCDAyJAwsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMyIARQRAIAFBAWohAQwoCyADQQ42AhwgAyAANgIMIAMgAUEBajYCFAyIAwsgAEEVRg03QQAhAiADQQA2AhwgAyABNgIUIANB0A82AhAgA0EiNgIMDIcDCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDCcLIANBDzYCHCADIAA2AgwgAyABQQFqNgIUDIYDC0EAIQIgA0EANgIcIAMgATYCFCADQeIXNgIQIANBGTYCDAyFAwsgAEEVRg0zQQAhAiADQQA2AhwgAyABNgIUIANB1gw2AhAgA0EjNgIMDIQDCyADKAIEIQBBACECIANBADYCBCADIAAgARA0IgBFDSUgA0ERNgIcIAMgATYCFCADIAA2AgwMgwMLIABBFUYNMEEAIQIgA0EANgIcIAMgATYCFCADQdYMNgIQIANBIzYCDAyCAwsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQNCIARQRAIAFBAWohAQwlCyADQRI2AhwgAyAANgIMIAMgAUEBajYCFAyBAwsgA0Evai0AAEEBcUUNAQtBFyECDOYCC0EAIQIgA0EANgIcIAMgATYCFCADQeIXNgIQIANBGTYCDAz+AgsgAEE7Rw0AIAFBAWohAQwMC0EAIQIgA0EANgIcIAMgATYCFCADQZIYNgIQIANBAjYCDAz8AgsgAEEVRg0oQQAhAiADQQA2AhwgAyABNgIUIANB1gw2AhAgA0EjNgIMDPsCCyADQRQ2AhwgAyABNgIUIAMgADYCDAz6AgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQNCIARQRAIAFBAWohAQz1AgsgA0EVNgIcIAMgADYCDCADIAFBAWo2AhQM+QILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDQiAEUEQCABQQFqIQEM8wILIANBFzYCHCADIAA2AgwgAyABQQFqNgIUDPgCCyAAQRVGDSNBACECIANBADYCHCADIAE2AhQgA0HWDDYCECADQSM2AgwM9wILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDQiAEUEQCABQQFqIQEMHQsgA0EZNgIcIAMgADYCDCADIAFBAWo2AhQM9gILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDQiAEUEQCABQQFqIQEM7wILIANBGjYCHCADIAA2AgwgAyABQQFqNgIUDPUCCyAAQRVGDR9BACECIANBADYCHCADIAE2AhQgA0HQDzYCECADQSI2AgwM9AILIAMoAgQhACADQQA2AgQgAyAAIAEQMyIARQRAIAFBAWohAQwbCyADQRw2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIM8wILIAMoAgQhACADQQA2AgQgAyAAIAEQMyIARQRAIAFBAWohAQzrAgsgA0EdNgIcIAMgADYCDCADIAFBAWo2AhRBACECDPICCyAAQTtHDQEgAUEBaiEBC0EmIQIM1wILQQAhAiADQQA2AhwgAyABNgIUIANBnxU2AhAgA0EMNgIMDO8CCyABIARHBEADQCABLQAAQSBHDYQCIAQgAUEBaiIBRw0AC0EsIQIM7wILQSwhAgzuAgsgASAERgRAQTQhAgzuAgsCQAJAA0ACQCABLQAAQQprDgQCAAADAAsgBCABQQFqIgFHDQALQTQhAgzvAgsgAygCBCEAIANBADYCBCADIAAgARAxIgBFDZ8CIANBMjYCHCADIAE2AhQgAyAANgIMQQAhAgzuAgsgAygCBCEAIANBADYCBCADIAAgARAxIgBFBEAgAUEBaiEBDJ8CCyADQTI2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIM7QILIAEgBEcEQAJAA0AgAS0AAEEwayIAQf8BcUEKTwRAQTohAgzXAgsgAykDICILQpmz5syZs+bMGVYNASADIAtCCn4iCjcDICAKIACtQv8BgyILQn+FVg0BIAMgCiALfDcDICAEIAFBAWoiAUcNAAtBwAAhAgzuAgsgAygCBCEAIANBADYCBCADIAAgAUEBaiIBEDEiAA0XDOICC0HAACECDOwCCyABIARGBEBByQAhAgzsAgsCQANAAkAgAS0AAEEJaw4YAAKiAqICqQKiAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAqICogIAogILIAQgAUEBaiIBRw0AC0HJACECDOwCCyABQQFqIQEgA0Evai0AAEEBcQ2lAiADQQA2AhwgAyABNgIUIANBlxA2AhAgA0EKNgIMQQAhAgzrAgsgASAERwRAA0AgAS0AAEEgRw0VIAQgAUEBaiIBRw0AC0H4ACECDOsCC0H4ACECDOoCCyADQQI6ACgMOAtBACECIANBADYCHCADQb8LNgIQIANBAjYCDCADIAFBAWo2AhQM6AILQQAhAgzOAgtBDSECDM0CC0ETIQIMzAILQRUhAgzLAgtBFiECDMoCC0EYIQIMyQILQRkhAgzIAgtBGiECDMcCC0EbIQIMxgILQRwhAgzFAgtBHSECDMQCC0EeIQIMwwILQR8hAgzCAgtBICECDMECC0EiIQIMwAILQSMhAgy/AgtBJSECDL4CC0HlACECDL0CCyADQT02AhwgAyABNgIUIAMgADYCDEEAIQIM1QILIANBGzYCHCADIAE2AhQgA0GkHDYCECADQRU2AgxBACECDNQCCyADQSA2AhwgAyABNgIUIANBmBo2AhAgA0EVNgIMQQAhAgzTAgsgA0ETNgIcIAMgATYCFCADQZgaNgIQIANBFTYCDEEAIQIM0gILIANBCzYCHCADIAE2AhQgA0GYGjYCECADQRU2AgxBACECDNECCyADQRA2AhwgAyABNgIUIANBmBo2AhAgA0EVNgIMQQAhAgzQAgsgA0EgNgIcIAMgATYCFCADQaQcNgIQIANBFTYCDEEAIQIMzwILIANBCzYCHCADIAE2AhQgA0GkHDYCECADQRU2AgxBACECDM4CCyADQQw2AhwgAyABNgIUIANBpBw2AhAgA0EVNgIMQQAhAgzNAgtBACECIANBADYCHCADIAE2AhQgA0HdDjYCECADQRI2AgwMzAILAkADQAJAIAEtAABBCmsOBAACAgACCyAEIAFBAWoiAUcNAAtB/QEhAgzMAgsCQAJAIAMtADZBAUcNAEEAIQACQCADKAI4IgJFDQAgAigCYCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUcNASADQfwBNgIcIAMgATYCFCADQdwZNgIQIANBFTYCDEEAIQIMzQILQdwBIQIMswILIANBADYCHCADIAE2AhQgA0H5CzYCECADQR82AgxBACECDMsCCwJAAkAgAy0AKEEBaw4CBAEAC0HbASECDLICC0HUASECDLECCyADQQI6ADFBACEAAkAgAygCOCICRQ0AIAIoAgAiAkUNACADIAIRAAAhAAsgAEUEQEHdASECDLECCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQbQMNgIQIANBEDYCDEEAIQIMygILIANB+wE2AhwgAyABNgIUIANBgRo2AhAgA0EVNgIMQQAhAgzJAgsgASAERgRAQfoBIQIMyQILIAEtAABByABGDQEgA0EBOgAoC0HAASECDK4CC0HaASECDK0CCyABIARHBEAgA0EMNgIIIAMgATYCBEHZASECDK0CC0H5ASECDMUCCyABIARGBEBB+AEhAgzFAgsgAS0AAEHIAEcNBCABQQFqIQFB2AEhAgyrAgsgASAERgRAQfcBIQIMxAILAkACQCABLQAAQcUAaw4QAAUFBQUFBQUFBQUFBQUFAQULIAFBAWohAUHWASECDKsCCyABQQFqIQFB1wEhAgyqAgtB9gEhAiABIARGDcICIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbrVAGotAABHDQMgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADMMCCyADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQLiIARQRAQeMBIQIMqgILIANB9QE2AhwgAyABNgIUIAMgADYCDEEAIQIMwgILQfQBIQIgASAERg3BAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEG41QBqLQAARw0CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzCAgsgA0GBBDsBKCADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQLiIADQMMAgsgA0EANgIAC0EAIQIgA0EANgIcIAMgATYCFCADQeUfNgIQIANBCDYCDAy/AgtB1QEhAgylAgsgA0HzATYCHCADIAE2AhQgAyAANgIMQQAhAgy9AgtBACEAAkAgAygCOCICRQ0AIAIoAkAiAkUNACADIAIRAAAhAAsgAEUNbiAAQRVHBEAgA0EANgIcIAMgATYCFCADQYIPNgIQIANBIDYCDEEAIQIMvQILIANBjwE2AhwgAyABNgIUIANB7Bs2AhAgA0EVNgIMQQAhAgy8AgsgASAERwRAIANBDTYCCCADIAE2AgRB0wEhAgyjAgtB8gEhAgy7AgsgASAERgRAQfEBIQIMuwILAkACQAJAIAEtAABByABrDgsAAQgICAgICAgIAggLIAFBAWohAUHQASECDKMCCyABQQFqIQFB0QEhAgyiAgsgAUEBaiEBQdIBIQIMoQILQfABIQIgASAERg25AiADKAIAIgAgBCABa2ohBiABIABrQQJqIQUDQCABLQAAIABBtdUAai0AAEcNBCAAQQJGDQMgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAY2AgAMuQILQe8BIQIgASAERg24AiADKAIAIgAgBCABa2ohBiABIABrQQFqIQUDQCABLQAAIABBs9UAai0AAEcNAyAAQQFGDQIgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAY2AgAMuAILQe4BIQIgASAERg23AiADKAIAIgAgBCABa2ohBiABIABrQQJqIQUDQCABLQAAIABBsNUAai0AAEcNAiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAY2AgAMtwILIAMoAgQhACADQgA3AwAgAyAAIAVBAWoiARArIgBFDQIgA0HsATYCHCADIAE2AhQgAyAANgIMQQAhAgy2AgsgA0EANgIACyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNnAIgA0HtATYCHCADIAE2AhQgAyAANgIMQQAhAgy0AgtBzwEhAgyaAgtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDLQCC0HOASECDJoCCyADQesBNgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMsgILIAEgBEYEQEHrASECDLICCyABLQAAQS9GBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GyODYCECADQQg2AgxBACECDLECC0HNASECDJcCCyABIARHBEAgA0EONgIIIAMgATYCBEHMASECDJcCC0HqASECDK8CCyABIARGBEBB6QEhAgyvAgsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFBywEhAgyWAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZcCIANB6AE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILIAEgBEYEQEHnASECDK4CCwJAIAEtAABBLkYEQCABQQFqIQEMAQsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZgCIANB5gE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILQcoBIQIMlAILIAEgBEYEQEHlASECDK0CC0EAIQBBASEFQQEhB0EAIQICQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQCABLQAAQTBrDgoKCQABAgMEBQYICwtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshAkEAIQVBACEHDAILQQkhAkEBIQBBACEFQQAhBwwBC0EAIQVBASECCyADIAI6ACsgAUEBaiEBAkACQCADLQAuQRBxDQACQAJAAkAgAy0AKg4DAQACBAsgB0UNAwwCCyAADQEMAgsgBUUNAQsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDQIgA0HiATYCHCADIAE2AhQgAyAANgIMQQAhAgyvAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZoCIANB4wE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ2YAiADQeQBNgIcIAMgATYCFCADIAA2AgwMrQILQckBIQIMkwILQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANBpA02AhAgA0EhNgIMQQAhAgytAgtByAEhAgyTAgsgA0HhATYCHCADIAE2AhQgA0HQGjYCECADQRU2AgxBACECDKsCCyABIARGBEBB4QEhAgyrAgsCQCABLQAAQSBGBEAgA0EAOwE0IAFBAWohAQwBCyADQQA2AhwgAyABNgIUIANBmRE2AhAgA0EJNgIMQQAhAgyrAgtBxwEhAgyRAgsgASAERgRAQeABIQIMqgILAkAgAS0AAEEwa0H/AXEiAkEKSQRAIAFBAWohAQJAIAMvATQiAEGZM0sNACADIABBCmwiADsBNCAAQf7/A3EgAkH//wNzSw0AIAMgACACajsBNAwCC0EAIQIgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDAyrAgsgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDEEAIQIMqgILQcYBIQIMkAILIAEgBEYEQEHfASECDKkCCwJAIAEtAABBMGtB/wFxIgJBCkkEQCABQQFqIQECQCADLwE0IgBBmTNLDQAgAyAAQQpsIgA7ATQgAEH+/wNxIAJB//8Dc0sNACADIAAgAmo7ATQMAgtBACECIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgwMqgILIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgxBACECDKkCC0HFASECDI8CCyABIARGBEBB3gEhAgyoAgsCQCABLQAAQTBrQf8BcSICQQpJBEAgAUEBaiEBAkAgAy8BNCIAQZkzSw0AIAMgAEEKbCIAOwE0IABB/v8DcSACQf//A3NLDQAgAyAAIAJqOwE0DAILQQAhAiADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMDKkCCyADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMQQAhAgyoAgtBxAEhAgyOAgsgASAERgRAQd0BIQIMpwILAkACQAJAAkAgAS0AAEEKaw4XAgMDAAMDAwMDAwMDAwMDAwMDAwMDAwEDCyABQQFqDAULIAFBAWohAUHDASECDI8CCyABQQFqIQEgA0Evai0AAEEBcQ0IIANBADYCHCADIAE2AhQgA0GNCzYCECADQQ02AgxBACECDKcCCyADQQA2AhwgAyABNgIUIANBjQs2AhAgA0ENNgIMQQAhAgymAgsgASAERwRAIANBDzYCCCADIAE2AgRBASECDI0CC0HcASECDKUCCwJAAkADQAJAIAEtAABBCmsOBAIAAAMACyAEIAFBAWoiAUcNAAtB2wEhAgymAgsgAygCBCEAIANBADYCBCADIAAgARAtIgBFBEAgAUEBaiEBDAQLIANB2gE2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMpQILIAMoAgQhACADQQA2AgQgAyAAIAEQLSIADQEgAUEBagshAUHBASECDIoCCyADQdkBNgIcIAMgADYCDCADIAFBAWo2AhRBACECDKICC0HCASECDIgCCyADQS9qLQAAQQFxDQEgA0EANgIcIAMgATYCFCADQeQcNgIQIANBGTYCDEEAIQIMoAILIAEgBEYEQEHZASECDKACCwJAAkACQCABLQAAQQprDgQBAgIAAgsgAUEBaiEBDAILIAFBAWohAQwBCyADLQAuQcAAcUUNAQtBACEAAkAgAygCOCICRQ0AIAIoAjwiAkUNACADIAIRAAAhAAsgAEUNoAEgAEEVRgRAIANB2QA2AhwgAyABNgIUIANBtxo2AhAgA0EVNgIMQQAhAgyfAgsgA0EANgIcIAMgATYCFCADQYANNgIQIANBGzYCDEEAIQIMngILIANBADYCHCADIAE2AhQgA0HcKDYCECADQQI2AgxBACECDJ0CCyABIARHBEAgA0EMNgIIIAMgATYCBEG/ASECDIQCC0HYASECDJwCCyABIARGBEBB1wEhAgycAgsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBwQBrDhUAAQIDWgQFBlpaWgcICQoLDA0ODxBaCyABQQFqIQFB+wAhAgySAgsgAUEBaiEBQfwAIQIMkQILIAFBAWohAUGBASECDJACCyABQQFqIQFBhQEhAgyPAgsgAUEBaiEBQYYBIQIMjgILIAFBAWohAUGJASECDI0CCyABQQFqIQFBigEhAgyMAgsgAUEBaiEBQY0BIQIMiwILIAFBAWohAUGWASECDIoCCyABQQFqIQFBlwEhAgyJAgsgAUEBaiEBQZgBIQIMiAILIAFBAWohAUGlASECDIcCCyABQQFqIQFBpgEhAgyGAgsgAUEBaiEBQawBIQIMhQILIAFBAWohAUG0ASECDIQCCyABQQFqIQFBtwEhAgyDAgsgAUEBaiEBQb4BIQIMggILIAEgBEYEQEHWASECDJsCCyABLQAAQc4ARw1IIAFBAWohAUG9ASECDIECCyABIARGBEBB1QEhAgyaAgsCQAJAAkAgAS0AAEHCAGsOEgBKSkpKSkpKSkoBSkpKSkpKAkoLIAFBAWohAUG4ASECDIICCyABQQFqIQFBuwEhAgyBAgsgAUEBaiEBQbwBIQIMgAILQdQBIQIgASAERg2YAiADKAIAIgAgBCABa2ohBSABIABrQQdqIQYCQANAIAEtAAAgAEGo1QBqLQAARw1FIABBB0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyZAgsgA0EANgIAIAZBAWohAUEbDEULIAEgBEYEQEHTASECDJgCCwJAAkAgAS0AAEHJAGsOBwBHR0dHRwFHCyABQQFqIQFBuQEhAgz/AQsgAUEBaiEBQboBIQIM/gELQdIBIQIgASAERg2WAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGm1QBqLQAARw1DIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyXAgsgA0EANgIAIAZBAWohAUEPDEMLQdEBIQIgASAERg2VAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGk1QBqLQAARw1CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyWAgsgA0EANgIAIAZBAWohAUEgDEILQdABIQIgASAERg2UAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGh1QBqLQAARw1BIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyVAgsgA0EANgIAIAZBAWohAUESDEELIAEgBEYEQEHPASECDJQCCwJAAkAgAS0AAEHFAGsODgBDQ0NDQ0NDQ0NDQ0MBQwsgAUEBaiEBQbUBIQIM+wELIAFBAWohAUG2ASECDPoBC0HOASECIAEgBEYNkgIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBntUAai0AAEcNPyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMkwILIANBADYCACAGQQFqIQFBBww/C0HNASECIAEgBEYNkQIgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBmNUAai0AAEcNPiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMkgILIANBADYCACAGQQFqIQFBKAw+CyABIARGBEBBzAEhAgyRAgsCQAJAAkAgAS0AAEHFAGsOEQBBQUFBQUFBQUEBQUFBQUECQQsgAUEBaiEBQbEBIQIM+QELIAFBAWohAUGyASECDPgBCyABQQFqIQFBswEhAgz3AQtBywEhAiABIARGDY8CIAMoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAS0AACAAQZHVAGotAABHDTwgAEEGRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJACCyADQQA2AgAgBkEBaiEBQRoMPAtBygEhAiABIARGDY4CIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQY3VAGotAABHDTsgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADI8CCyADQQA2AgAgBkEBaiEBQSEMOwsgASAERgRAQckBIQIMjgILAkACQCABLQAAQcEAaw4UAD09PT09PT09PT09PT09PT09PQE9CyABQQFqIQFBrQEhAgz1AQsgAUEBaiEBQbABIQIM9AELIAEgBEYEQEHIASECDI0CCwJAAkAgAS0AAEHVAGsOCwA8PDw8PDw8PDwBPAsgAUEBaiEBQa4BIQIM9AELIAFBAWohAUGvASECDPMBC0HHASECIAEgBEYNiwIgAygCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABBhNUAai0AAEcNOCAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMjAILIANBADYCACAGQQFqIQFBKgw4CyABIARGBEBBxgEhAgyLAgsgAS0AAEHQAEcNOCABQQFqIQFBJQw3C0HFASECIAEgBEYNiQIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBgdUAai0AAEcNNiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMigILIANBADYCACAGQQFqIQFBDgw2CyABIARGBEBBxAEhAgyJAgsgAS0AAEHFAEcNNiABQQFqIQFBqwEhAgzvAQsgASAERgRAQcMBIQIMiAILAkACQAJAAkAgAS0AAEHCAGsODwABAjk5OTk5OTk5OTk5AzkLIAFBAWohAUGnASECDPEBCyABQQFqIQFBqAEhAgzwAQsgAUEBaiEBQakBIQIM7wELIAFBAWohAUGqASECDO4BC0HCASECIAEgBEYNhgIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB/tQAai0AAEcNMyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMhwILIANBADYCACAGQQFqIQFBFAwzC0HBASECIAEgBEYNhQIgAygCACIAIAQgAWtqIQUgASAAa0EEaiEGAkADQCABLQAAIABB+dQAai0AAEcNMiAAQQRGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMhgILIANBADYCACAGQQFqIQFBKwwyC0HAASECIAEgBEYNhAIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB9tQAai0AAEcNMSAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMhQILIANBADYCACAGQQFqIQFBLAwxC0G/ASECIAEgBEYNgwIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBodUAai0AAEcNMCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMhAILIANBADYCACAGQQFqIQFBEQwwC0G+ASECIAEgBEYNggIgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABB8tQAai0AAEcNLyAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMgwILIANBADYCACAGQQFqIQFBLgwvCyABIARGBEBBvQEhAgyCAgsCQAJAAkACQAJAIAEtAABBwQBrDhUANDQ0NDQ0NDQ0NAE0NAI0NAM0NAQ0CyABQQFqIQFBmwEhAgzsAQsgAUEBaiEBQZwBIQIM6wELIAFBAWohAUGdASECDOoBCyABQQFqIQFBogEhAgzpAQsgAUEBaiEBQaQBIQIM6AELIAEgBEYEQEG8ASECDIECCwJAAkAgAS0AAEHSAGsOAwAwATALIAFBAWohAUGjASECDOgBCyABQQFqIQFBBAwtC0G7ASECIAEgBEYN/wEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB8NQAai0AAEcNLCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMgAILIANBADYCACAGQQFqIQFBHQwsCyABIARGBEBBugEhAgz/AQsCQAJAIAEtAABByQBrDgcBLi4uLi4ALgsgAUEBaiEBQaEBIQIM5gELIAFBAWohAUEiDCsLIAEgBEYEQEG5ASECDP4BCyABLQAAQdAARw0rIAFBAWohAUGgASECDOQBCyABIARGBEBBuAEhAgz9AQsCQAJAIAEtAABBxgBrDgsALCwsLCwsLCwsASwLIAFBAWohAUGeASECDOQBCyABQQFqIQFBnwEhAgzjAQtBtwEhAiABIARGDfsBIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQezUAGotAABHDSggAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPwBCyADQQA2AgAgBkEBaiEBQQ0MKAtBtgEhAiABIARGDfoBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQaHVAGotAABHDScgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPsBCyADQQA2AgAgBkEBaiEBQQwMJwtBtQEhAiABIARGDfkBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQerUAGotAABHDSYgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPoBCyADQQA2AgAgBkEBaiEBQQMMJgtBtAEhAiABIARGDfgBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQejUAGotAABHDSUgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPkBCyADQQA2AgAgBkEBaiEBQSYMJQsgASAERgRAQbMBIQIM+AELAkACQCABLQAAQdQAaw4CAAEnCyABQQFqIQFBmQEhAgzfAQsgAUEBaiEBQZoBIQIM3gELQbIBIQIgASAERg32ASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHm1ABqLQAARw0jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz3AQsgA0EANgIAIAZBAWohAUEnDCMLQbEBIQIgASAERg31ASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHk1ABqLQAARw0iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz2AQsgA0EANgIAIAZBAWohAUEcDCILQbABIQIgASAERg30ASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHe1ABqLQAARw0hIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz1AQsgA0EANgIAIAZBAWohAUEGDCELQa8BIQIgASAERg3zASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHZ1ABqLQAARw0gIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz0AQsgA0EANgIAIAZBAWohAUEZDCALIAEgBEYEQEGuASECDPMBCwJAAkACQAJAIAEtAABBLWsOIwAkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJAEkJCQkJAIkJCQDJAsgAUEBaiEBQY4BIQIM3AELIAFBAWohAUGPASECDNsBCyABQQFqIQFBlAEhAgzaAQsgAUEBaiEBQZUBIQIM2QELQa0BIQIgASAERg3xASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHX1ABqLQAARw0eIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzyAQsgA0EANgIAIAZBAWohAUELDB4LIAEgBEYEQEGsASECDPEBCwJAAkAgAS0AAEHBAGsOAwAgASALIAFBAWohAUGQASECDNgBCyABQQFqIQFBkwEhAgzXAQsgASAERgRAQasBIQIM8AELAkACQCABLQAAQcEAaw4PAB8fHx8fHx8fHx8fHx8BHwsgAUEBaiEBQZEBIQIM1wELIAFBAWohAUGSASECDNYBCyABIARGBEBBqgEhAgzvAQsgAS0AAEHMAEcNHCABQQFqIQFBCgwbC0GpASECIAEgBEYN7QEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABB0dQAai0AAEcNGiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM7gELIANBADYCACAGQQFqIQFBHgwaC0GoASECIAEgBEYN7AEgAygCACIAIAQgAWtqIQUgASAAa0EGaiEGAkADQCABLQAAIABBytQAai0AAEcNGSAAQQZGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM7QELIANBADYCACAGQQFqIQFBFQwZC0GnASECIAEgBEYN6wEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBx9QAai0AAEcNGCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM7AELIANBADYCACAGQQFqIQFBFwwYC0GmASECIAEgBEYN6gEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBwdQAai0AAEcNFyAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM6wELIANBADYCACAGQQFqIQFBGAwXCyABIARGBEBBpQEhAgzqAQsCQAJAIAEtAABByQBrDgcAGRkZGRkBGQsgAUEBaiEBQYsBIQIM0QELIAFBAWohAUGMASECDNABC0GkASECIAEgBEYN6AEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBptUAai0AAEcNFSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM6QELIANBADYCACAGQQFqIQFBCQwVC0GjASECIAEgBEYN5wEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBpNUAai0AAEcNFCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM6AELIANBADYCACAGQQFqIQFBHwwUC0GiASECIAEgBEYN5gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBvtQAai0AAEcNEyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM5wELIANBADYCACAGQQFqIQFBAgwTC0GhASECIAEgBEYN5QEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGA0AgAS0AACAAQbzUAGotAABHDREgAEEBRg0CIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADOUBCyABIARGBEBBoAEhAgzlAQtBASABLQAAQd8ARw0RGiABQQFqIQFBhwEhAgzLAQsgA0EANgIAIAZBAWohAUGIASECDMoBC0GfASECIAEgBEYN4gEgAygCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABBhNUAai0AAEcNDyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4wELIANBADYCACAGQQFqIQFBKQwPC0GeASECIAEgBEYN4QEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBuNQAai0AAEcNDiAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4gELIANBADYCACAGQQFqIQFBLQwOCyABIARGBEBBnQEhAgzhAQsgAS0AAEHFAEcNDiABQQFqIQFBhAEhAgzHAQsgASAERgRAQZwBIQIM4AELAkACQCABLQAAQcwAaw4IAA8PDw8PDwEPCyABQQFqIQFBggEhAgzHAQsgAUEBaiEBQYMBIQIMxgELQZsBIQIgASAERg3eASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEGz1ABqLQAARw0LIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzfAQsgA0EANgIAIAZBAWohAUEjDAsLQZoBIQIgASAERg3dASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGw1ABqLQAARw0KIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzeAQsgA0EANgIAIAZBAWohAUEADAoLIAEgBEYEQEGZASECDN0BCwJAAkAgAS0AAEHIAGsOCAAMDAwMDAwBDAsgAUEBaiEBQf0AIQIMxAELIAFBAWohAUGAASECDMMBCyABIARGBEBBmAEhAgzcAQsCQAJAIAEtAABBzgBrDgMACwELCyABQQFqIQFB/gAhAgzDAQsgAUEBaiEBQf8AIQIMwgELIAEgBEYEQEGXASECDNsBCyABLQAAQdkARw0IIAFBAWohAUEIDAcLQZYBIQIgASAERg3ZASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEGs1ABqLQAARw0GIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzaAQsgA0EANgIAIAZBAWohAUEFDAYLQZUBIQIgASAERg3YASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGm1ABqLQAARw0FIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzZAQsgA0EANgIAIAZBAWohAUEWDAULQZQBIQIgASAERg3XASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGh1QBqLQAARw0EIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzYAQsgA0EANgIAIAZBAWohAUEQDAQLIAEgBEYEQEGTASECDNcBCwJAAkAgAS0AAEHDAGsODAAGBgYGBgYGBgYGAQYLIAFBAWohAUH5ACECDL4BCyABQQFqIQFB+gAhAgy9AQtBkgEhAiABIARGDdUBIAMoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQaDUAGotAABHDQIgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNYBCyADQQA2AgAgBkEBaiEBQSQMAgsgA0EANgIADAILIAEgBEYEQEGRASECDNQBCyABLQAAQcwARw0BIAFBAWohAUETCzoAKSADKAIEIQAgA0EANgIEIAMgACABEC4iAA0CDAELQQAhAiADQQA2AhwgAyABNgIUIANB/h82AhAgA0EGNgIMDNEBC0H4ACECDLcBCyADQZABNgIcIAMgATYCFCADIAA2AgxBACECDM8BC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUYNASADQQA2AhwgAyABNgIUIANBgg82AhAgA0EgNgIMQQAhAgzOAQtB9wAhAgy0AQsgA0GPATYCHCADIAE2AhQgA0HsGzYCECADQRU2AgxBACECDMwBCyABIARGBEBBjwEhAgzMAQsCQCABLQAAQSBGBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GbHzYCECADQQY2AgxBACECDMwBC0ECIQIMsgELA0AgAS0AAEEgRw0CIAQgAUEBaiIBRw0AC0GOASECDMoBCyABIARGBEBBjQEhAgzKAQsCQCABLQAAQQlrDgRKAABKAAtB9QAhAgywAQsgAy0AKUEFRgRAQfYAIQIMsAELQfQAIQIMrwELIAEgBEYEQEGMASECDMgBCyADQRA2AgggAyABNgIEDAoLIAEgBEYEQEGLASECDMcBCwJAIAEtAABBCWsOBEcAAEcAC0HzACECDK0BCyABIARHBEAgA0EQNgIIIAMgATYCBEHxACECDK0BC0GKASECDMUBCwJAIAEgBEcEQANAIAEtAABBoNAAai0AACIAQQNHBEACQCAAQQFrDgJJAAQLQfAAIQIMrwELIAQgAUEBaiIBRw0AC0GIASECDMYBC0GIASECDMUBCyADQQA2AhwgAyABNgIUIANB2yA2AhAgA0EHNgIMQQAhAgzEAQsgASAERgRAQYkBIQIMxAELAkACQAJAIAEtAABBoNIAai0AAEEBaw4DRgIAAQtB8gAhAgysAQsgA0EANgIcIAMgATYCFCADQbQSNgIQIANBBzYCDEEAIQIMxAELQeoAIQIMqgELIAEgBEcEQCABQQFqIQFB7wAhAgyqAQtBhwEhAgzCAQsgBCABIgBGBEBBhgEhAgzCAQsgAC0AACIBQS9GBEAgAEEBaiEBQe4AIQIMqQELIAFBCWsiAkEXSw0BIAAhAUEBIAJ0QZuAgARxDUEMAQsgBCABIgBGBEBBhQEhAgzBAQsgAC0AAEEvRw0AIABBAWohAQwDC0EAIQIgA0EANgIcIAMgADYCFCADQdsgNgIQIANBBzYCDAy/AQsCQAJAAkACQAJAA0AgAS0AAEGgzgBqLQAAIgBBBUcEQAJAAkAgAEEBaw4IRwUGBwgABAEIC0HrACECDK0BCyABQQFqIQFB7QAhAgysAQsgBCABQQFqIgFHDQALQYQBIQIMwwELIAFBAWoMFAsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDR4gA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgzBAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDR4gA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgzAAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDR4gA0H6ADYCHCADIAE2AhQgAyAANgIMQQAhAgy/AQsgA0EANgIcIAMgATYCFCADQfkPNgIQIANBBzYCDEEAIQIMvgELIAEgBEYEQEGDASECDL4BCwJAIAEtAABBoM4Aai0AAEEBaw4IPgQFBgAIAgMHCyABQQFqIQELQQMhAgyjAQsgAUEBagwNC0EAIQIgA0EANgIcIANB0RI2AhAgA0EHNgIMIAMgAUEBajYCFAy6AQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDRYgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgy5AQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDRYgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgy4AQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDRYgA0H6ADYCHCADIAE2AhQgAyAANgIMQQAhAgy3AQsgA0EANgIcIAMgATYCFCADQfkPNgIQIANBBzYCDEEAIQIMtgELQewAIQIMnAELIAEgBEYEQEGCASECDLUBCyABQQFqDAILIAEgBEYEQEGBASECDLQBCyABQQFqDAELIAEgBEYNASABQQFqCyEBQQQhAgyYAQtBgAEhAgywAQsDQCABLQAAQaDMAGotAAAiAEECRwRAIABBAUcEQEHpACECDJkBCwwxCyAEIAFBAWoiAUcNAAtB/wAhAgyvAQsgASAERgRAQf4AIQIMrwELAkAgAS0AAEEJaw43LwMGLwQGBgYGBgYGBgYGBgYGBgYGBgYFBgYCBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGAAYLIAFBAWoLIQFBBSECDJQBCyABQQFqDAYLIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0IIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMqwELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0IIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMqgELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0IIANB+gA2AhwgAyABNgIUIAMgADYCDEEAIQIMqQELIANBADYCHCADIAE2AhQgA0GNFDYCECADQQc2AgxBACECDKgBCwJAAkACQAJAA0AgAS0AAEGgygBqLQAAIgBBBUcEQAJAIABBAWsOBi4DBAUGAAYLQegAIQIMlAELIAQgAUEBaiIBRw0AC0H9ACECDKsBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNByADQdsANgIcIAMgATYCFCADIAA2AgxBACECDKoBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNByADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDKkBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNByADQfoANgIcIAMgATYCFCADIAA2AgxBACECDKgBCyADQQA2AhwgAyABNgIUIANB5Ag2AhAgA0EHNgIMQQAhAgynAQsgASAERg0BIAFBAWoLIQFBBiECDIwBC0H8ACECDKQBCwJAAkACQAJAA0AgAS0AAEGgyABqLQAAIgBBBUcEQCAAQQFrDgQpAgMEBQsgBCABQQFqIgFHDQALQfsAIQIMpwELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0DIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMpgELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0DIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMpQELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0DIANB+gA2AhwgAyABNgIUIAMgADYCDEEAIQIMpAELIANBADYCHCADIAE2AhQgA0G8CjYCECADQQc2AgxBACECDKMBC0HPACECDIkBC0HRACECDIgBC0HnACECDIcBCyABIARGBEBB+gAhAgygAQsCQCABLQAAQQlrDgQgAAAgAAsgAUEBaiEBQeYAIQIMhgELIAEgBEYEQEH5ACECDJ8BCwJAIAEtAABBCWsOBB8AAB8AC0EAIQACQCADKAI4IgJFDQAgAigCOCICRQ0AIAMgAhEAACEACyAARQRAQeIBIQIMhgELIABBFUcEQCADQQA2AhwgAyABNgIUIANByQ02AhAgA0EaNgIMQQAhAgyfAQsgA0H4ADYCHCADIAE2AhQgA0HqGjYCECADQRU2AgxBACECDJ4BCyABIARHBEAgA0ENNgIIIAMgATYCBEHkACECDIUBC0H3ACECDJ0BCyABIARGBEBB9gAhAgydAQsCQAJAAkAgAS0AAEHIAGsOCwABCwsLCwsLCwsCCwsgAUEBaiEBQd0AIQIMhQELIAFBAWohAUHgACECDIQBCyABQQFqIQFB4wAhAgyDAQtB9QAhAiABIARGDZsBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbXVAGotAABHDQggAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJwBCyADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQKyIABEAgA0H0ADYCHCADIAE2AhQgAyAANgIMQQAhAgycAQtB4gAhAgyCAQtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJwBC0HhACECDIIBCyADQfMANgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMmgELIAMtACkiAEEja0ELSQ0JAkAgAEEGSw0AQQEgAHRBygBxRQ0ADAoLQQAhAiADQQA2AhwgAyABNgIUIANB7Qk2AhAgA0EINgIMDJkBC0HyACECIAEgBEYNmAEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBs9UAai0AAEcNBSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMmQELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgAEQCADQfEANgIcIAMgATYCFCADIAA2AgxBACECDJkBC0HfACECDH8LQQAhAAJAIAMoAjgiAkUNACACKAI0IgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANB6g02AhAgA0EmNgIMQQAhAgyZAQtB3gAhAgx/CyADQfAANgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMlwELIAMtAClBIUYNBiADQQA2AhwgAyABNgIUIANBkQo2AhAgA0EINgIMQQAhAgyWAQtB7wAhAiABIARGDZUBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbDVAGotAABHDQIgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJYBCyADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQKyIARQ0CIANB7QA2AhwgAyABNgIUIAMgADYCDEEAIQIMlQELIANBADYCAAsgAygCBCEAIANBADYCBCADIAAgARArIgBFDYABIANB7gA2AhwgAyABNgIUIAMgADYCDEEAIQIMkwELQdwAIQIMeQtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJMBC0HbACECDHkLIANB7AA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyRAQsgAy0AKSIAQSNJDQAgAEEuRg0AIANBADYCHCADIAE2AhQgA0HJCTYCECADQQg2AgxBACECDJABC0HaACECDHYLIAEgBEYEQEHrACECDI8BCwJAIAEtAABBL0YEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQbI4NgIQIANBCDYCDEEAIQIMjwELQdkAIQIMdQsgASAERwRAIANBDjYCCCADIAE2AgRB2AAhAgx1C0HqACECDI0BCyABIARGBEBB6QAhAgyNAQsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFB1wAhAgx0CyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNeiADQegANgIcIAMgATYCFCADIAA2AgxBACECDIwBCyABIARGBEBB5wAhAgyMAQsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ17IANB5gA2AhwgAyABNgIUIAMgADYCDEEAIQIMjAELQdYAIQIMcgsgASAERgRAQeUAIQIMiwELQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNAiADQeIANgIcIAMgATYCFCADIAA2AgxBACECDI0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNfSADQeMANgIcIAMgATYCFCADIAA2AgxBACECDIwBCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNeyADQeQANgIcIAMgATYCFCADIAA2AgwMiwELQdQAIQIMcQsgAy0AKUEiRg2GAUHTACECDHALQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALIABFBEBB1QAhAgxwCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQaQNNgIQIANBITYCDEEAIQIMiQELIANB4QA2AhwgAyABNgIUIANB0Bo2AhAgA0EVNgIMQQAhAgyIAQsgASAERgRAQeAAIQIMiAELAkACQAJAAkACQCABLQAAQQprDgQBBAQABAsgAUEBaiEBDAELIAFBAWohASADQS9qLQAAQQFxRQ0BC0HSACECDHALIANBADYCHCADIAE2AhQgA0G2ETYCECADQQk2AgxBACECDIgBCyADQQA2AhwgAyABNgIUIANBthE2AhAgA0EJNgIMQQAhAgyHAQsgASAERgRAQd8AIQIMhwELIAEtAABBCkYEQCABQQFqIQEMCQsgAy0ALkHAAHENCCADQQA2AhwgAyABNgIUIANBthE2AhAgA0ECNgIMQQAhAgyGAQsgASAERgRAQd0AIQIMhgELIAEtAAAiAkENRgRAIAFBAWohAUHQACECDG0LIAEhACACQQlrDgQFAQEFAQsgBCABIgBGBEBB3AAhAgyFAQsgAC0AAEEKRw0AIABBAWoMAgtBACECIANBADYCHCADIAA2AhQgA0HKLTYCECADQQc2AgwMgwELIAEgBEYEQEHbACECDIMBCwJAIAEtAABBCWsOBAMAAAMACyABQQFqCyEBQc4AIQIMaAsgASAERgRAQdoAIQIMgQELIAEtAABBCWsOBAABAQABC0EAIQIgA0EANgIcIANBmhI2AhAgA0EHNgIMIAMgAUEBajYCFAx/CyADQYASOwEqQQAhAAJAIAMoAjgiAkUNACACKAI4IgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB2QA2AhwgAyABNgIUIANB6ho2AhAgA0EVNgIMQQAhAgx+C0HNACECDGQLIANBADYCHCADIAE2AhQgA0HJDTYCECADQRo2AgxBACECDHwLIAEgBEYEQEHZACECDHwLIAEtAABBIEcNPSABQQFqIQEgAy0ALkEBcQ09IANBADYCHCADIAE2AhQgA0HCHDYCECADQR42AgxBACECDHsLIAEgBEYEQEHYACECDHsLAkACQAJAAkACQCABLQAAIgBBCmsOBAIDAwABCyABQQFqIQFBLCECDGULIABBOkcNASADQQA2AhwgAyABNgIUIANB5xE2AhAgA0EKNgIMQQAhAgx9CyABQQFqIQEgA0Evai0AAEEBcUUNcyADLQAyQYABcUUEQCADQTJqIQIgAxA1QQAhAAJAIAMoAjgiBkUNACAGKAIoIgZFDQAgAyAGEQAAIQALAkACQCAADhZNTEsBAQEBAQEBAQEBAQEBAQEBAQEAAQsgA0EpNgIcIAMgATYCFCADQawZNgIQIANBFTYCDEEAIQIMfgsgA0EANgIcIAMgATYCFCADQeULNgIQIANBETYCDEEAIQIMfQtBACEAAkAgAygCOCICRQ0AIAIoAlwiAkUNACADIAIRAAAhAAsgAEUNWSAAQRVHDQEgA0EFNgIcIAMgATYCFCADQZsbNgIQIANBFTYCDEEAIQIMfAtBywAhAgxiC0EAIQIgA0EANgIcIAMgATYCFCADQZAONgIQIANBFDYCDAx6CyADIAMvATJBgAFyOwEyDDsLIAEgBEcEQCADQRE2AgggAyABNgIEQcoAIQIMYAtB1wAhAgx4CyABIARGBEBB1gAhAgx4CwJAAkACQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxQeMAaw4TAEBAQEBAQEBAQEBAQAFAQEACA0ALIAFBAWohAUHGACECDGELIAFBAWohAUHHACECDGALIAFBAWohAUHIACECDF8LIAFBAWohAUHJACECDF4LQdUAIQIgBCABIgBGDXYgBCABayADKAIAIgFqIQYgACABa0EFaiEHA0AgAUGQyABqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0IQQQgAUEFRg0KGiABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAx2C0HUACECIAQgASIARg11IAQgAWsgAygCACIBaiEGIAAgAWtBD2ohBwNAIAFBgMgAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNB0EDIAFBD0YNCRogAUEBaiEBIAQgAEEBaiIARw0ACyADIAY2AgAMdQtB0wAhAiAEIAEiAEYNdCAEIAFrIAMoAgAiAWohBiAAIAFrQQ5qIQcDQCABQeLHAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQYgAUEORg0HIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADHQLQdIAIQIgBCABIgBGDXMgBCABayADKAIAIgFqIQUgACABa0EBaiEGA0AgAUHgxwBqLQAAIAAtAAAiB0EgciAHIAdBwQBrQf8BcUEaSRtB/wFxRw0FIAFBAUYNAiABQQFqIQEgBCAAQQFqIgBHDQALIAMgBTYCAAxzCyABIARGBEBB0QAhAgxzCwJAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXFB7gBrDgcAOTk5OTkBOQsgAUEBaiEBQcMAIQIMWgsgAUEBaiEBQcQAIQIMWQsgA0EANgIAIAZBAWohAUHFACECDFgLQdAAIQIgBCABIgBGDXAgBCABayADKAIAIgFqIQYgACABa0EJaiEHA0AgAUHWxwBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0CQQIgAUEJRg0EGiABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxwC0HPACECIAQgASIARg1vIAQgAWsgAygCACIBaiEGIAAgAWtBBWohBwNAIAFB0McAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNASABQQVGDQIgAUEBaiEBIAQgAEEBaiIARw0ACyADIAY2AgAMbwsgACEBIANBADYCAAwzC0EBCzoALCADQQA2AgAgB0EBaiEBC0EtIQIMUgsCQANAIAEtAABB0MUAai0AAEEBRw0BIAQgAUEBaiIBRw0AC0HNACECDGsLQcIAIQIMUQsgASAERgRAQcwAIQIMagsgAS0AAEE6RgRAIAMoAgQhACADQQA2AgQgAyAAIAEQMCIARQ0zIANBywA2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMagsgA0EANgIcIAMgATYCFCADQecRNgIQIANBCjYCDEEAIQIMaQsCQAJAIAMtACxBAmsOAgABJwsgA0Ezai0AAEECcUUNJiADLQAuQQJxDSYgA0EANgIcIAMgATYCFCADQaYUNgIQIANBCzYCDEEAIQIMaQsgAy0AMkEgcUUNJSADLQAuQQJxDSUgA0EANgIcIAMgATYCFCADQb0TNgIQIANBDzYCDEEAIQIMaAtBACEAAkAgAygCOCICRQ0AIAIoAkgiAkUNACADIAIRAAAhAAsgAEUEQEHBACECDE8LIABBFUcEQCADQQA2AhwgAyABNgIUIANBpg82AhAgA0EcNgIMQQAhAgxoCyADQcoANgIcIAMgATYCFCADQYUcNgIQIANBFTYCDEEAIQIMZwsgASAERwRAA0AgAS0AAEHAwQBqLQAAQQFHDRcgBCABQQFqIgFHDQALQcQAIQIMZwtBxAAhAgxmCyABIARHBEADQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxIgBBCUYNACAAQSBGDQACQAJAAkACQCAAQeMAaw4TAAMDAwMDAwMBAwMDAwMDAwMDAgMLIAFBAWohAUE2IQIMUgsgAUEBaiEBQTchAgxRCyABQQFqIQFBOCECDFALDBULIAQgAUEBaiIBRw0AC0E8IQIMZgtBPCECDGULIAEgBEYEQEHIACECDGULIANBEjYCCCADIAE2AgQCQAJAAkACQAJAIAMtACxBAWsOBBQAAQIJCyADLQAyQSBxDQNB4AEhAgxPCwJAIAMvATIiAEEIcUUNACADLQAoQQFHDQAgAy0ALkEIcUUNAgsgAyAAQff7A3FBgARyOwEyDAsLIAMgAy8BMkEQcjsBMgwECyADQQA2AgQgAyABIAEQMSIABEAgA0HBADYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgxmCyABQQFqIQEMWAsgA0EANgIcIAMgATYCFCADQfQTNgIQIANBBDYCDEEAIQIMZAtBxwAhAiABIARGDWMgAygCACIAIAQgAWtqIQUgASAAa0EGaiEGAkADQCAAQcDFAGotAAAgAS0AAEEgckcNASAAQQZGDUogAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMZAsgA0EANgIADAULAkAgASAERwRAA0AgAS0AAEHAwwBqLQAAIgBBAUcEQCAAQQJHDQMgAUEBaiEBDAULIAQgAUEBaiIBRw0AC0HFACECDGQLQcUAIQIMYwsLIANBADoALAwBC0ELIQIMRwtBPyECDEYLAkACQANAIAEtAAAiAEEgRwRAAkAgAEEKaw4EAwUFAwALIABBLEYNAwwECyAEIAFBAWoiAUcNAAtBxgAhAgxgCyADQQg6ACwMDgsgAy0AKEEBRw0CIAMtAC5BCHENAiADKAIEIQAgA0EANgIEIAMgACABEDEiAARAIANBwgA2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMXwsgAUEBaiEBDFALQTshAgxECwJAA0AgAS0AACIAQSBHIABBCUdxDQEgBCABQQFqIgFHDQALQcMAIQIMXQsLQTwhAgxCCwJAAkAgASAERwRAA0AgAS0AACIAQSBHBEAgAEEKaw4EAwQEAwQLIAQgAUEBaiIBRw0AC0E/IQIMXQtBPyECDFwLIAMgAy8BMkEgcjsBMgwKCyADKAIEIQAgA0EANgIEIAMgACABEDEiAEUNTiADQT42AhwgAyABNgIUIAMgADYCDEEAIQIMWgsCQCABIARHBEADQCABLQAAQcDDAGotAAAiAEEBRwRAIABBAkYNAwwMCyAEIAFBAWoiAUcNAAtBNyECDFsLQTchAgxaCyABQQFqIQEMBAtBOyECIAQgASIARg1YIAQgAWsgAygCACIBaiEGIAAgAWtBBWohBwJAA0AgAUGQyABqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBBUYEQEEHIQEMPwsgAUEBaiEBIAQgAEEBaiIARw0ACyADIAY2AgAMWQsgA0EANgIAIAAhAQwFC0E6IQIgBCABIgBGDVcgBCABayADKAIAIgFqIQYgACABa0EIaiEHAkADQCABQbTBAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQEgAUEIRgRAQQUhAQw+CyABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxYCyADQQA2AgAgACEBDAQLQTkhAiAEIAEiAEYNViAEIAFrIAMoAgAiAWohBiAAIAFrQQNqIQcCQANAIAFBsMEAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNASABQQNGBEBBBiEBDD0LIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADFcLIANBADYCACAAIQEMAwsCQANAIAEtAAAiAEEgRwRAIABBCmsOBAcEBAcCCyAEIAFBAWoiAUcNAAtBOCECDFYLIABBLEcNASABQQFqIQBBASEBAkACQAJAAkACQCADLQAsQQVrDgQDAQIEAAsgACEBDAQLQQIhAQwBC0EEIQELIANBAToALCADIAMvATIgAXI7ATIgACEBDAELIAMgAy8BMkEIcjsBMiAAIQELQT4hAgw7CyADQQA6ACwLQTkhAgw5CyABIARGBEBBNiECDFILAkACQAJAAkACQCABLQAAQQprDgQAAgIBAgsgAygCBCEAIANBADYCBCADIAAgARAxIgBFDQIgA0EzNgIcIAMgATYCFCADIAA2AgxBACECDFULIAMoAgQhACADQQA2AgQgAyAAIAEQMSIARQRAIAFBAWohAQwGCyADQTI2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMVAsgAy0ALkEBcQRAQd8BIQIMOwsgAygCBCEAIANBADYCBCADIAAgARAxIgANAQxJC0E0IQIMOQsgA0E1NgIcIAMgATYCFCADIAA2AgxBACECDFELQTUhAgw3CyADQS9qLQAAQQFxDQAgA0EANgIcIAMgATYCFCADQesWNgIQIANBGTYCDEEAIQIMTwtBMyECDDULIAEgBEYEQEEyIQIMTgsCQCABLQAAQQpGBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GSFzYCECADQQM2AgxBACECDE4LQTIhAgw0CyABIARGBEBBMSECDE0LAkAgAS0AACIAQQlGDQAgAEEgRg0AQQEhAgJAIAMtACxBBWsOBAYEBQANCyADIAMvATJBCHI7ATIMDAsgAy0ALkEBcUUNASADLQAsQQhHDQAgA0EAOgAsC0E9IQIMMgsgA0EANgIcIAMgATYCFCADQcIWNgIQIANBCjYCDEEAIQIMSgtBAiECDAELQQQhAgsgA0EBOgAsIAMgAy8BMiACcjsBMgwGCyABIARGBEBBMCECDEcLIAEtAABBCkYEQCABQQFqIQEMAQsgAy0ALkEBcQ0AIANBADYCHCADIAE2AhQgA0HcKDYCECADQQI2AgxBACECDEYLQTAhAgwsCyABQQFqIQFBMSECDCsLIAEgBEYEQEEvIQIMRAsgAS0AACIAQQlHIABBIEdxRQRAIAFBAWohASADLQAuQQFxDQEgA0EANgIcIAMgATYCFCADQZcQNgIQIANBCjYCDEEAIQIMRAtBASECAkACQAJAAkACQAJAIAMtACxBAmsOBwUEBAMBAgAECyADIAMvATJBCHI7ATIMAwtBAiECDAELQQQhAgsgA0EBOgAsIAMgAy8BMiACcjsBMgtBLyECDCsLIANBADYCHCADIAE2AhQgA0GEEzYCECADQQs2AgxBACECDEMLQeEBIQIMKQsgASAERgRAQS4hAgxCCyADQQA2AgQgA0ESNgIIIAMgASABEDEiAA0BC0EuIQIMJwsgA0EtNgIcIAMgATYCFCADIAA2AgxBACECDD8LQQAhAAJAIAMoAjgiAkUNACACKAJMIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB2AA2AhwgAyABNgIUIANBsxs2AhAgA0EVNgIMQQAhAgw+C0HMACECDCQLIANBADYCHCADIAE2AhQgA0GzDjYCECADQR02AgxBACECDDwLIAEgBEYEQEHOACECDDwLIAEtAAAiAEEgRg0CIABBOkYNAQsgA0EAOgAsQQkhAgwhCyADKAIEIQAgA0EANgIEIAMgACABEDAiAA0BDAILIAMtAC5BAXEEQEHeASECDCALIAMoAgQhACADQQA2AgQgAyAAIAEQMCIARQ0CIANBKjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgw4CyADQcsANgIcIAMgADYCDCADIAFBAWo2AhRBACECDDcLIAFBAWohAUHAACECDB0LIAFBAWohAQwsCyABIARGBEBBKyECDDULAkAgAS0AAEEKRgRAIAFBAWohAQwBCyADLQAuQcAAcUUNBgsgAy0AMkGAAXEEQEEAIQACQCADKAI4IgJFDQAgAigCXCICRQ0AIAMgAhEAACEACyAARQ0SIABBFUYEQCADQQU2AhwgAyABNgIUIANBmxs2AhAgA0EVNgIMQQAhAgw2CyADQQA2AhwgAyABNgIUIANBkA42AhAgA0EUNgIMQQAhAgw1CyADQTJqIQIgAxA1QQAhAAJAIAMoAjgiBkUNACAGKAIoIgZFDQAgAyAGEQAAIQALIAAOFgIBAAQEBAQEBAQEBAQEBAQEBAQEBAMECyADQQE6ADALIAIgAi8BAEHAAHI7AQALQSshAgwYCyADQSk2AhwgAyABNgIUIANBrBk2AhAgA0EVNgIMQQAhAgwwCyADQQA2AhwgAyABNgIUIANB5Qs2AhAgA0ERNgIMQQAhAgwvCyADQQA2AhwgAyABNgIUIANBpQs2AhAgA0ECNgIMQQAhAgwuC0EBIQcgAy8BMiIFQQhxRQRAIAMpAyBCAFIhBwsCQCADLQAwBEBBASEAIAMtAClBBUYNASAFQcAAcUUgB3FFDQELAkAgAy0AKCICQQJGBEBBASEAIAMvATQiBkHlAEYNAkEAIQAgBUHAAHENAiAGQeQARg0CIAZB5gBrQQJJDQIgBkHMAUYNAiAGQbACRg0CDAELQQAhACAFQcAAcQ0BC0ECIQAgBUEIcQ0AIAVBgARxBEACQCACQQFHDQAgAy0ALkEKcQ0AQQUhAAwCC0EEIQAMAQsgBUEgcUUEQCADEDZBAEdBAnQhAAwBC0EAQQMgAykDIFAbIQALIABBAWsOBQIABwEDBAtBESECDBMLIANBAToAMQwpC0EAIQICQCADKAI4IgBFDQAgACgCMCIARQ0AIAMgABEAACECCyACRQ0mIAJBFUYEQCADQQM2AhwgAyABNgIUIANB0hs2AhAgA0EVNgIMQQAhAgwrC0EAIQIgA0EANgIcIAMgATYCFCADQd0ONgIQIANBEjYCDAwqCyADQQA2AhwgAyABNgIUIANB+SA2AhAgA0EPNgIMQQAhAgwpC0EAIQACQCADKAI4IgJFDQAgAigCMCICRQ0AIAMgAhEAACEACyAADQELQQ4hAgwOCyAAQRVGBEAgA0ECNgIcIAMgATYCFCADQdIbNgIQIANBFTYCDEEAIQIMJwsgA0EANgIcIAMgATYCFCADQd0ONgIQIANBEjYCDEEAIQIMJgtBKiECDAwLIAEgBEcEQCADQQk2AgggAyABNgIEQSkhAgwMC0EmIQIMJAsgAyADKQMgIgwgBCABa60iCn0iC0IAIAsgDFgbNwMgIAogDFQEQEElIQIMJAsgAygCBCEAIANBADYCBCADIAAgASAMp2oiARAyIgBFDQAgA0EFNgIcIAMgATYCFCADIAA2AgxBACECDCMLQQ8hAgwJC0IAIQoCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAS0AAEEwaw43FxYAAQIDBAUGBxQUFBQUFBQICQoLDA0UFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFA4PEBESExQLQgIhCgwWC0IDIQoMFQtCBCEKDBQLQgUhCgwTC0IGIQoMEgtCByEKDBELQgghCgwQC0IJIQoMDwtCCiEKDA4LQgshCgwNC0IMIQoMDAtCDSEKDAsLQg4hCgwKC0IPIQoMCQtCCiEKDAgLQgshCgwHC0IMIQoMBgtCDSEKDAULQg4hCgwEC0IPIQoMAwsgA0EANgIcIAMgATYCFCADQZ8VNgIQIANBDDYCDEEAIQIMIQsgASAERgRAQSIhAgwhC0IAIQoCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBMGsONxUUAAECAwQFBgcWFhYWFhYWCAkKCwwNFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYODxAREhMWC0ICIQoMFAtCAyEKDBMLQgQhCgwSC0IFIQoMEQtCBiEKDBALQgchCgwPC0IIIQoMDgtCCSEKDA0LQgohCgwMC0ILIQoMCwtCDCEKDAoLQg0hCgwJC0IOIQoMCAtCDyEKDAcLQgohCgwGC0ILIQoMBQtCDCEKDAQLQg0hCgwDC0IOIQoMAgtCDyEKDAELQgEhCgsgAUEBaiEBIAMpAyAiC0L//////////w9YBEAgAyALQgSGIAqENwMgDAILIANBADYCHCADIAE2AhQgA0G1CTYCECADQQw2AgxBACECDB4LQSchAgwEC0EoIQIMAwsgAyABOgAsIANBADYCACAHQQFqIQFBDCECDAILIANBADYCACAGQQFqIQFBCiECDAELIAFBAWohAUEIIQIMAAsAC0EAIQIgA0EANgIcIAMgATYCFCADQbI4NgIQIANBCDYCDAwXC0EAIQIgA0EANgIcIAMgATYCFCADQYMRNgIQIANBCTYCDAwWC0EAIQIgA0EANgIcIAMgATYCFCADQd8KNgIQIANBCTYCDAwVC0EAIQIgA0EANgIcIAMgATYCFCADQe0QNgIQIANBCTYCDAwUC0EAIQIgA0EANgIcIAMgATYCFCADQdIRNgIQIANBCTYCDAwTC0EAIQIgA0EANgIcIAMgATYCFCADQbI4NgIQIANBCDYCDAwSC0EAIQIgA0EANgIcIAMgATYCFCADQYMRNgIQIANBCTYCDAwRC0EAIQIgA0EANgIcIAMgATYCFCADQd8KNgIQIANBCTYCDAwQC0EAIQIgA0EANgIcIAMgATYCFCADQe0QNgIQIANBCTYCDAwPC0EAIQIgA0EANgIcIAMgATYCFCADQdIRNgIQIANBCTYCDAwOC0EAIQIgA0EANgIcIAMgATYCFCADQbkXNgIQIANBDzYCDAwNC0EAIQIgA0EANgIcIAMgATYCFCADQbkXNgIQIANBDzYCDAwMC0EAIQIgA0EANgIcIAMgATYCFCADQZkTNgIQIANBCzYCDAwLC0EAIQIgA0EANgIcIAMgATYCFCADQZ0JNgIQIANBCzYCDAwKC0EAIQIgA0EANgIcIAMgATYCFCADQZcQNgIQIANBCjYCDAwJC0EAIQIgA0EANgIcIAMgATYCFCADQbEQNgIQIANBCjYCDAwIC0EAIQIgA0EANgIcIAMgATYCFCADQbsdNgIQIANBAjYCDAwHC0EAIQIgA0EANgIcIAMgATYCFCADQZYWNgIQIANBAjYCDAwGC0EAIQIgA0EANgIcIAMgATYCFCADQfkYNgIQIANBAjYCDAwFC0EAIQIgA0EANgIcIAMgATYCFCADQcQYNgIQIANBAjYCDAwECyADQQI2AhwgAyABNgIUIANBqR42AhAgA0EWNgIMQQAhAgwDC0HeACECIAEgBEYNAiAJQQhqIQcgAygCACEFAkACQCABIARHBEAgBUGWyABqIQggBCAFaiABayEGIAVBf3NBCmoiBSABaiEAA0AgAS0AACAILQAARwRAQQIhCAwDCyAFRQRAQQAhCCAAIQEMAwsgBUEBayEFIAhBAWohCCAEIAFBAWoiAUcNAAsgBiEFIAQhAQsgB0EBNgIAIAMgBTYCAAwBCyADQQA2AgAgByAINgIACyAHIAE2AgQgCSgCDCEAAkACQCAJKAIIQQFrDgIEAQALIANBADYCHCADQcIeNgIQIANBFzYCDCADIABBAWo2AhRBACECDAMLIANBADYCHCADIAA2AhQgA0HXHjYCECADQQk2AgxBACECDAILIAEgBEYEQEEoIQIMAgsgA0EJNgIIIAMgATYCBEEnIQIMAQsgASAERgRAQQEhAgwBCwNAAkACQAJAIAEtAABBCmsOBAABAQABCyABQQFqIQEMAQsgAUEBaiEBIAMtAC5BIHENAEEAIQIgA0EANgIcIAMgATYCFCADQaEhNgIQIANBBTYCDAwCC0EBIQIgASAERw0ACwsgCUEQaiQAIAJFBEAgAygCDCEADAELIAMgAjYCHEEAIQAgAygCBCIBRQ0AIAMgASAEIAMoAggRAQAiAUUNACADIAQ2AhQgAyABNgIMIAEhAAsgAAu+AgECfyAAQQA6AAAgAEHkAGoiAUEBa0EAOgAAIABBADoAAiAAQQA6AAEgAUEDa0EAOgAAIAFBAmtBADoAACAAQQA6AAMgAUEEa0EAOgAAQQAgAGtBA3EiASAAaiIAQQA2AgBB5AAgAWtBfHEiAiAAaiIBQQRrQQA2AgACQCACQQlJDQAgAEEANgIIIABBADYCBCABQQhrQQA2AgAgAUEMa0EANgIAIAJBGUkNACAAQQA2AhggAEEANgIUIABBADYCECAAQQA2AgwgAUEQa0EANgIAIAFBFGtBADYCACABQRhrQQA2AgAgAUEca0EANgIAIAIgAEEEcUEYciICayIBQSBJDQAgACACaiEAA0AgAEIANwMYIABCADcDECAAQgA3AwggAEIANwMAIABBIGohACABQSBrIgFBH0sNAAsLC1YBAX8CQCAAKAIMDQACQAJAAkACQCAALQAxDgMBAAMCCyAAKAI4IgFFDQAgASgCMCIBRQ0AIAAgAREAACIBDQMLQQAPCwALIABByhk2AhBBDiEBCyABCxoAIAAoAgxFBEAgAEHeHzYCECAAQRU2AgwLCxQAIAAoAgxBFUYEQCAAQQA2AgwLCxQAIAAoAgxBFkYEQCAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsrAAJAIABBJ08NAEL//////wkgAK2IQgGDUA0AIABBAnRB0DhqKAIADwsACxcAIABBL08EQAALIABBAnRB7DlqKAIAC78JAQF/QfQtIQECQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAQeQAaw70A2NiAAFhYWFhYWECAwQFYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQYHCAkKCwwNDg9hYWFhYRBhYWFhYWFhYWFhYRFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWESExQVFhcYGRobYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1NmE3ODk6YWFhYWFhYWE7YWFhPGFhYWE9Pj9hYWFhYWFhYUBhYUFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFCQ0RFRkdISUpLTE1OT1BRUlNhYWFhYWFhYVRVVldYWVpbYVxdYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhXmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYV9gYQtB6iwPC0GYJg8LQe0xDwtBoDcPC0HJKQ8LQbQpDwtBli0PC0HrKw8LQaI1DwtB2zQPC0HgKQ8LQeMkDwtB1SQPC0HuJA8LQeYlDwtByjQPC0HQNw8LQao1DwtB9SwPC0H2Jg8LQYIiDwtB8jMPC0G+KA8LQec3DwtBzSEPC0HAIQ8LQbglDwtByyUPC0GWJA8LQY80DwtBzTUPC0HdKg8LQe4zDwtBnDQPC0GeMQ8LQfQ1DwtB5SIPC0GvJQ8LQZkxDwtBsjYPC0H5Ng8LQcQyDwtB3SwPC0GCMQ8LQcExDwtBjTcPC0HJJA8LQew2DwtB5yoPC0HIIw8LQeIhDwtByTcPC0GlIg8LQZQiDwtB2zYPC0HeNQ8LQYYmDwtBvCsPC0GLMg8LQaAjDwtB9jAPC0GALA8LQYkrDwtBpCYPC0HyIw8LQYEoDwtBqzIPC0HrJw8LQcI2DwtBoiQPC0HPKg8LQdwjDwtBhycPC0HkNA8LQbciDwtBrTEPC0HVIg8LQa80DwtB3iYPC0HWMg8LQfQ0DwtBgTgPC0H0Nw8LQZI2DwtBnScPC0GCKQ8LQY0jDwtB1zEPC0G9NQ8LQbQ3DwtB2DAPC0G2Jw8LQZo4DwtBpyoPC0HEJw8LQa4jDwtB9SIPCwALQcomIQELIAELFwAgACAALwEuQf7/A3EgAUEAR3I7AS4LGgAgACAALwEuQf3/A3EgAUEAR0EBdHI7AS4LGgAgACAALwEuQfv/A3EgAUEAR0ECdHI7AS4LGgAgACAALwEuQff/A3EgAUEAR0EDdHI7AS4LGgAgACAALwEuQe//A3EgAUEAR0EEdHI7AS4LGgAgACAALwEuQd//A3EgAUEAR0EFdHI7AS4LGgAgACAALwEuQb//A3EgAUEAR0EGdHI7AS4LGgAgACAALwEuQf/+A3EgAUEAR0EHdHI7AS4LGgAgACAALwEuQf/9A3EgAUEAR0EIdHI7AS4LGgAgACAALwEuQf/7A3EgAUEAR0EJdHI7AS4LPgECfwJAIAAoAjgiA0UNACADKAIEIgNFDQAgACABIAIgAWsgAxEBACIEQX9HDQAgAEHhEjYCEEEYIQQLIAQLPgECfwJAIAAoAjgiA0UNACADKAIIIgNFDQAgACABIAIgAWsgAxEBACIEQX9HDQAgAEH8ETYCEEEYIQQLIAQLPgECfwJAIAAoAjgiA0UNACADKAIMIgNFDQAgACABIAIgAWsgAxEBACIEQX9HDQAgAEHsCjYCEEEYIQQLIAQLPgECfwJAIAAoAjgiA0UNACADKAIQIgNFDQAgACABIAIgAWsgAxEBACIEQX9HDQAgAEH6HjYCEEEYIQQLIAQLPgECfwJAIAAoAjgiA0UNACADKAIUIgNFDQAgACABIAIgAWsgAxEBACIEQX9HDQAgAEHLEDYCEEEYIQQLIAQLPgECfwJAIAAoAjgiA0UNACADKAIYIgNFDQAgACABIAIgAWsgAxEBACIEQX9HDQAgAEG3HzYCEEEYIQQLIAQLPgECfwJAIAAoAjgiA0UNACADKAIcIgNFDQAgACABIAIgAWsgAxEBACIEQX9HDQAgAEG/FTYCEEEYIQQLIAQLPgECfwJAIAAoAjgiA0UNACADKAIsIgNFDQAgACABIAIgAWsgAxEBACIEQX9HDQAgAEH+CDYCEEEYIQQLIAQLPgECfwJAIAAoAjgiA0UNACADKAIgIgNFDQAgACABIAIgAWsgAxEBACIEQX9HDQAgAEGMHTYCEEEYIQQLIAQLPgECfwJAIAAoAjgiA0UNACADKAIkIgNFDQAgACABIAIgAWsgAxEBACIEQX9HDQAgAEHmFTYCEEEYIQQLIAQLOAAgAAJ/IAAvATJBFHFBFEYEQEEBIAAtAChBAUYNARogAC8BNEHlAEYMAQsgAC0AKUEFRgs6ADALWQECfwJAIAAtAChBAUYNACAALwE0IgFB5ABrQeQASQ0AIAFBzAFGDQAgAUGwAkYNACAALwEyIgBBwABxDQBBASECIABBiARxQYAERg0AIABBKHFFIQILIAILjAEBAn8CQAJAAkAgAC0AKkUNACAALQArRQ0AIAAvATIiAUECcUUNAQwCCyAALwEyIgFBAXFFDQELQQEhAiAALQAoQQFGDQAgAC8BNCIAQeQAa0HkAEkNACAAQcwBRg0AIABBsAJGDQAgAUHAAHENAEEAIQIgAUGIBHFBgARGDQAgAUEocUEARyECCyACC1cAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEH9ATYCHAsGACAAEDoLmi0BC38jAEEQayIKJABB3NUAKAIAIglFBEBBnNkAKAIAIgVFBEBBqNkAQn83AgBBoNkAQoCAhICAgMAANwIAQZzZACAKQQhqQXBxQdiq1aoFcyIFNgIAQbDZAEEANgIAQYDZAEEANgIAC0GE2QBBwNkENgIAQdTVAEHA2QQ2AgBB6NUAIAU2AgBB5NUAQX82AgBBiNkAQcCmAzYCAANAIAFBgNYAaiABQfTVAGoiAjYCACACIAFB7NUAaiIDNgIAIAFB+NUAaiADNgIAIAFBiNYAaiABQfzVAGoiAzYCACADIAI2AgAgAUGQ1gBqIAFBhNYAaiICNgIAIAIgAzYCACABQYzWAGogAjYCACABQSBqIgFBgAJHDQALQczZBEGBpgM2AgBB4NUAQazZACgCADYCAEHQ1QBBgKYDNgIAQdzVAEHI2QQ2AgBBzP8HQTg2AgBByNkEIQkLAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEHsAU0EQEHE1QAoAgAiBkEQIABBE2pBcHEgAEELSRsiBEEDdiIAdiIBQQNxBEACQCABQQFxIAByQQFzIgJBA3QiAEHs1QBqIgEgAEH01QBqKAIAIgAoAggiA0YEQEHE1QAgBkF+IAJ3cTYCAAwBCyABIAM2AgggAyABNgIMCyAAQQhqIQEgACACQQN0IgJBA3I2AgQgACACaiIAIAAoAgRBAXI2AgQMEQtBzNUAKAIAIgggBE8NASABBEACQEECIAB0IgJBACACa3IgASAAdHFoIgBBA3QiAkHs1QBqIgEgAkH01QBqKAIAIgIoAggiA0YEQEHE1QAgBkF+IAB3cSIGNgIADAELIAEgAzYCCCADIAE2AgwLIAIgBEEDcjYCBCAAQQN0IgAgBGshBSAAIAJqIAU2AgAgAiAEaiIEIAVBAXI2AgQgCARAIAhBeHFB7NUAaiEAQdjVACgCACEDAn9BASAIQQN2dCIBIAZxRQRAQcTVACABIAZyNgIAIAAMAQsgACgCCAsiASADNgIMIAAgAzYCCCADIAA2AgwgAyABNgIICyACQQhqIQFB2NUAIAQ2AgBBzNUAIAU2AgAMEQtByNUAKAIAIgtFDQEgC2hBAnRB9NcAaigCACIAKAIEQXhxIARrIQUgACECA0ACQCACKAIQIgFFBEAgAkEUaigCACIBRQ0BCyABKAIEQXhxIARrIgMgBUkhAiADIAUgAhshBSABIAAgAhshACABIQIMAQsLIAAoAhghCSAAKAIMIgMgAEcEQEHU1QAoAgAaIAMgACgCCCIBNgIIIAEgAzYCDAwQCyAAQRRqIgIoAgAiAUUEQCAAKAIQIgFFDQMgAEEQaiECCwNAIAIhByABIgNBFGoiAigCACIBDQAgA0EQaiECIAMoAhAiAQ0ACyAHQQA2AgAMDwtBfyEEIABBv39LDQAgAEETaiIBQXBxIQRByNUAKAIAIghFDQBBACAEayEFAkACQAJAAn9BACAEQYACSQ0AGkEfIARB////B0sNABogBEEmIAFBCHZnIgBrdkEBcSAAQQF0a0E+agsiBkECdEH01wBqKAIAIgJFBEBBACEBQQAhAwwBC0EAIQEgBEEZIAZBAXZrQQAgBkEfRxt0IQBBACEDA0ACQCACKAIEQXhxIARrIgcgBU8NACACIQMgByIFDQBBACEFIAIhAQwDCyABIAJBFGooAgAiByAHIAIgAEEddkEEcWpBEGooAgAiAkYbIAEgBxshASAAQQF0IQAgAg0ACwsgASADckUEQEEAIQNBAiAGdCIAQQAgAGtyIAhxIgBFDQMgAGhBAnRB9NcAaigCACEBCyABRQ0BCwNAIAEoAgRBeHEgBGsiAiAFSSEAIAIgBSAAGyEFIAEgAyAAGyEDIAEoAhAiAAR/IAAFIAFBFGooAgALIgENAAsLIANFDQAgBUHM1QAoAgAgBGtPDQAgAygCGCEHIAMgAygCDCIARwRAQdTVACgCABogACADKAIIIgE2AgggASAANgIMDA4LIANBFGoiAigCACIBRQRAIAMoAhAiAUUNAyADQRBqIQILA0AgAiEGIAEiAEEUaiICKAIAIgENACAAQRBqIQIgACgCECIBDQALIAZBADYCAAwNC0HM1QAoAgAiAyAETwRAQdjVACgCACEBAkAgAyAEayICQRBPBEAgASAEaiIAIAJBAXI2AgQgASADaiACNgIAIAEgBEEDcjYCBAwBCyABIANBA3I2AgQgASADaiIAIAAoAgRBAXI2AgRBACEAQQAhAgtBzNUAIAI2AgBB2NUAIAA2AgAgAUEIaiEBDA8LQdDVACgCACIDIARLBEAgBCAJaiIAIAMgBGsiAUEBcjYCBEHc1QAgADYCAEHQ1QAgATYCACAJIARBA3I2AgQgCUEIaiEBDA8LQQAhASAEAn9BnNkAKAIABEBBpNkAKAIADAELQajZAEJ/NwIAQaDZAEKAgISAgIDAADcCAEGc2QAgCkEMakFwcUHYqtWqBXM2AgBBsNkAQQA2AgBBgNkAQQA2AgBBgIAECyIAIARBxwBqIgVqIgZBACAAayIHcSICTwRAQbTZAEEwNgIADA8LAkBB/NgAKAIAIgFFDQBB9NgAKAIAIgggAmohACAAIAFNIAAgCEtxDQBBACEBQbTZAEEwNgIADA8LQYDZAC0AAEEEcQ0EAkACQCAJBEBBhNkAIQEDQCABKAIAIgAgCU0EQCAAIAEoAgRqIAlLDQMLIAEoAggiAQ0ACwtBABA7IgBBf0YNBSACIQZBoNkAKAIAIgFBAWsiAyAAcQRAIAIgAGsgACADakEAIAFrcWohBgsgBCAGTw0FIAZB/v///wdLDQVB/NgAKAIAIgMEQEH02AAoAgAiByAGaiEBIAEgB00NBiABIANLDQYLIAYQOyIBIABHDQEMBwsgBiADayAHcSIGQf7///8HSw0EIAYQOyEAIAAgASgCACABKAIEakYNAyAAIQELAkAgBiAEQcgAak8NACABQX9GDQBBpNkAKAIAIgAgBSAGa2pBACAAa3EiAEH+////B0sEQCABIQAMBwsgABA7QX9HBEAgACAGaiEGIAEhAAwHC0EAIAZrEDsaDAQLIAEiAEF/Rw0FDAMLQQAhAwwMC0EAIQAMCgsgAEF/Rw0CC0GA2QBBgNkAKAIAQQRyNgIACyACQf7///8HSw0BIAIQOyEAQQAQOyEBIABBf0YNASABQX9GDQEgACABTw0BIAEgAGsiBiAEQThqTQ0BC0H02ABB9NgAKAIAIAZqIgE2AgBB+NgAKAIAIAFJBEBB+NgAIAE2AgALAkACQAJAQdzVACgCACICBEBBhNkAIQEDQCAAIAEoAgAiAyABKAIEIgVqRg0CIAEoAggiAQ0ACwwCC0HU1QAoAgAiAUEARyAAIAFPcUUEQEHU1QAgADYCAAtBACEBQYjZACAGNgIAQYTZACAANgIAQeTVAEF/NgIAQejVAEGc2QAoAgA2AgBBkNkAQQA2AgADQCABQYDWAGogAUH01QBqIgI2AgAgAiABQezVAGoiAzYCACABQfjVAGogAzYCACABQYjWAGogAUH81QBqIgM2AgAgAyACNgIAIAFBkNYAaiABQYTWAGoiAjYCACACIAM2AgAgAUGM1gBqIAI2AgAgAUEgaiIBQYACRw0AC0F4IABrQQ9xIgEgAGoiAiAGQThrIgMgAWsiAUEBcjYCBEHg1QBBrNkAKAIANgIAQdDVACABNgIAQdzVACACNgIAIAAgA2pBODYCBAwCCyAAIAJNDQAgAiADSQ0AIAEoAgxBCHENAEF4IAJrQQ9xIgAgAmoiA0HQ1QAoAgAgBmoiByAAayIAQQFyNgIEIAEgBSAGajYCBEHg1QBBrNkAKAIANgIAQdDVACAANgIAQdzVACADNgIAIAIgB2pBODYCBAwBCyAAQdTVACgCAEkEQEHU1QAgADYCAAsgACAGaiEDQYTZACEBAkACQAJAA0AgAyABKAIARwRAIAEoAggiAQ0BDAILCyABLQAMQQhxRQ0BC0GE2QAhAQNAIAEoAgAiAyACTQRAIAMgASgCBGoiBSACSw0DCyABKAIIIQEMAAsACyABIAA2AgAgASABKAIEIAZqNgIEIABBeCAAa0EPcWoiCSAEQQNyNgIEIANBeCADa0EPcWoiBiAEIAlqIgRrIQEgAiAGRgRAQdzVACAENgIAQdDVAEHQ1QAoAgAgAWoiADYCACAEIABBAXI2AgQMCAtB2NUAKAIAIAZGBEBB2NUAIAQ2AgBBzNUAQczVACgCACABaiIANgIAIAQgAEEBcjYCBCAAIARqIAA2AgAMCAsgBigCBCIFQQNxQQFHDQYgBUF4cSEIIAVB/wFNBEAgBUEDdiEDIAYoAggiACAGKAIMIgJGBEBBxNUAQcTVACgCAEF+IAN3cTYCAAwHCyACIAA2AgggACACNgIMDAYLIAYoAhghByAGIAYoAgwiAEcEQCAAIAYoAggiAjYCCCACIAA2AgwMBQsgBkEUaiICKAIAIgVFBEAgBigCECIFRQ0EIAZBEGohAgsDQCACIQMgBSIAQRRqIgIoAgAiBQ0AIABBEGohAiAAKAIQIgUNAAsgA0EANgIADAQLQXggAGtBD3EiASAAaiIHIAZBOGsiAyABayIBQQFyNgIEIAAgA2pBODYCBCACIAVBNyAFa0EPcWpBP2siAyADIAJBEGpJGyIDQSM2AgRB4NUAQazZACgCADYCAEHQ1QAgATYCAEHc1QAgBzYCACADQRBqQYzZACkCADcCACADQYTZACkCADcCCEGM2QAgA0EIajYCAEGI2QAgBjYCAEGE2QAgADYCAEGQ2QBBADYCACADQSRqIQEDQCABQQc2AgAgBSABQQRqIgFLDQALIAIgA0YNACADIAMoAgRBfnE2AgQgAyADIAJrIgU2AgAgAiAFQQFyNgIEIAVB/wFNBEAgBUF4cUHs1QBqIQACf0HE1QAoAgAiAUEBIAVBA3Z0IgNxRQRAQcTVACABIANyNgIAIAAMAQsgACgCCAsiASACNgIMIAAgAjYCCCACIAA2AgwgAiABNgIIDAELQR8hASAFQf///wdNBEAgBUEmIAVBCHZnIgBrdkEBcSAAQQF0a0E+aiEBCyACIAE2AhwgAkIANwIQIAFBAnRB9NcAaiEAQcjVACgCACIDQQEgAXQiBnFFBEAgACACNgIAQcjVACADIAZyNgIAIAIgADYCGCACIAI2AgggAiACNgIMDAELIAVBGSABQQF2a0EAIAFBH0cbdCEBIAAoAgAhAwJAA0AgAyIAKAIEQXhxIAVGDQEgAUEddiEDIAFBAXQhASAAIANBBHFqQRBqIgYoAgAiAw0ACyAGIAI2AgAgAiAANgIYIAIgAjYCDCACIAI2AggMAQsgACgCCCIBIAI2AgwgACACNgIIIAJBADYCGCACIAA2AgwgAiABNgIIC0HQ1QAoAgAiASAETQ0AQdzVACgCACIAIARqIgIgASAEayIBQQFyNgIEQdDVACABNgIAQdzVACACNgIAIAAgBEEDcjYCBCAAQQhqIQEMCAtBACEBQbTZAEEwNgIADAcLQQAhAAsgB0UNAAJAIAYoAhwiAkECdEH01wBqIgMoAgAgBkYEQCADIAA2AgAgAA0BQcjVAEHI1QAoAgBBfiACd3E2AgAMAgsgB0EQQRQgBygCECAGRhtqIAA2AgAgAEUNAQsgACAHNgIYIAYoAhAiAgRAIAAgAjYCECACIAA2AhgLIAZBFGooAgAiAkUNACAAQRRqIAI2AgAgAiAANgIYCyABIAhqIQEgBiAIaiIGKAIEIQULIAYgBUF+cTYCBCABIARqIAE2AgAgBCABQQFyNgIEIAFB/wFNBEAgAUF4cUHs1QBqIQACf0HE1QAoAgAiAkEBIAFBA3Z0IgFxRQRAQcTVACABIAJyNgIAIAAMAQsgACgCCAsiASAENgIMIAAgBDYCCCAEIAA2AgwgBCABNgIIDAELQR8hBSABQf///wdNBEAgAUEmIAFBCHZnIgBrdkEBcSAAQQF0a0E+aiEFCyAEIAU2AhwgBEIANwIQIAVBAnRB9NcAaiEAQcjVACgCACICQQEgBXQiA3FFBEAgACAENgIAQcjVACACIANyNgIAIAQgADYCGCAEIAQ2AgggBCAENgIMDAELIAFBGSAFQQF2a0EAIAVBH0cbdCEFIAAoAgAhAAJAA0AgACICKAIEQXhxIAFGDQEgBUEddiEAIAVBAXQhBSACIABBBHFqQRBqIgMoAgAiAA0ACyADIAQ2AgAgBCACNgIYIAQgBDYCDCAEIAQ2AggMAQsgAigCCCIAIAQ2AgwgAiAENgIIIARBADYCGCAEIAI2AgwgBCAANgIICyAJQQhqIQEMAgsCQCAHRQ0AAkAgAygCHCIBQQJ0QfTXAGoiAigCACADRgRAIAIgADYCACAADQFByNUAIAhBfiABd3EiCDYCAAwCCyAHQRBBFCAHKAIQIANGG2ogADYCACAARQ0BCyAAIAc2AhggAygCECIBBEAgACABNgIQIAEgADYCGAsgA0EUaigCACIBRQ0AIABBFGogATYCACABIAA2AhgLAkAgBUEPTQRAIAMgBCAFaiIAQQNyNgIEIAAgA2oiACAAKAIEQQFyNgIEDAELIAMgBGoiAiAFQQFyNgIEIAMgBEEDcjYCBCACIAVqIAU2AgAgBUH/AU0EQCAFQXhxQezVAGohAAJ/QcTVACgCACIBQQEgBUEDdnQiBXFFBEBBxNUAIAEgBXI2AgAgAAwBCyAAKAIICyIBIAI2AgwgACACNgIIIAIgADYCDCACIAE2AggMAQtBHyEBIAVB////B00EQCAFQSYgBUEIdmciAGt2QQFxIABBAXRrQT5qIQELIAIgATYCHCACQgA3AhAgAUECdEH01wBqIQBBASABdCIEIAhxRQRAIAAgAjYCAEHI1QAgBCAIcjYCACACIAA2AhggAiACNgIIIAIgAjYCDAwBCyAFQRkgAUEBdmtBACABQR9HG3QhASAAKAIAIQQCQANAIAQiACgCBEF4cSAFRg0BIAFBHXYhBCABQQF0IQEgACAEQQRxakEQaiIGKAIAIgQNAAsgBiACNgIAIAIgADYCGCACIAI2AgwgAiACNgIIDAELIAAoAggiASACNgIMIAAgAjYCCCACQQA2AhggAiAANgIMIAIgATYCCAsgA0EIaiEBDAELAkAgCUUNAAJAIAAoAhwiAUECdEH01wBqIgIoAgAgAEYEQCACIAM2AgAgAw0BQcjVACALQX4gAXdxNgIADAILIAlBEEEUIAkoAhAgAEYbaiADNgIAIANFDQELIAMgCTYCGCAAKAIQIgEEQCADIAE2AhAgASADNgIYCyAAQRRqKAIAIgFFDQAgA0EUaiABNgIAIAEgAzYCGAsCQCAFQQ9NBEAgACAEIAVqIgFBA3I2AgQgACABaiIBIAEoAgRBAXI2AgQMAQsgACAEaiIHIAVBAXI2AgQgACAEQQNyNgIEIAUgB2ogBTYCACAIBEAgCEF4cUHs1QBqIQFB2NUAKAIAIQMCf0EBIAhBA3Z0IgIgBnFFBEBBxNUAIAIgBnI2AgAgAQwBCyABKAIICyICIAM2AgwgASADNgIIIAMgATYCDCADIAI2AggLQdjVACAHNgIAQczVACAFNgIACyAAQQhqIQELIApBEGokACABC0MAIABFBEA/AEEQdA8LAkAgAEH//wNxDQAgAEEASA0AIABBEHZAACIAQX9GBEBBtNkAQTA2AgBBfw8LIABBEHQPCwALC5lCIgBBgAgLDQEAAAAAAAAAAgAAAAMAQZgICwUEAAAABQBBqAgLCQYAAAAHAAAACABB5AgLwjJJbnZhbGlkIGNoYXIgaW4gdXJsIHF1ZXJ5AFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fYm9keQBDb250ZW50LUxlbmd0aCBvdmVyZmxvdwBDaHVuayBzaXplIG92ZXJmbG93AEludmFsaWQgbWV0aG9kIGZvciBIVFRQL3gueCByZXF1ZXN0AEludmFsaWQgbWV0aG9kIGZvciBSVFNQL3gueCByZXF1ZXN0AEV4cGVjdGVkIFNPVVJDRSBtZXRob2QgZm9yIElDRS94LnggcmVxdWVzdABJbnZhbGlkIGNoYXIgaW4gdXJsIGZyYWdtZW50IHN0YXJ0AEV4cGVjdGVkIGRvdABTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3N0YXR1cwBJbnZhbGlkIHJlc3BvbnNlIHN0YXR1cwBFeHBlY3RlZCBMRiBhZnRlciBoZWFkZXJzAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMAVXNlciBjYWxsYmFjayBlcnJvcgBgb25fcmVzZXRgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19oZWFkZXJgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3Byb3RvY29sX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fcHJvdG9jb2wARW1wdHkgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyYWN0ZXIgaW4gQ29udGVudC1MZW5ndGgAVHJhbnNmZXItRW5jb2RpbmcgY2FuJ3QgYmUgcHJlc2VudCB3aXRoIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgc2l6ZQBFeHBlY3RlZCBMRiBhZnRlciBjaHVuayBzaXplAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBVbmV4cGVjdGVkIHdoaXRlc3BhY2UgYWZ0ZXIgaGVhZGVyIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgaGVhZGVyIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgTEYgYWZ0ZXIgaGVhZGVyIHZhbHVlAEludmFsaWQgYFRyYW5zZmVyLUVuY29kaW5nYCBoZWFkZXIgdmFsdWUATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciBjaHVuayBleHRlbnNpb24gdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZSB2YWx1ZQBJbnZhbGlkIHF1b3RlZC1wYWlyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fcHJvdG9jb2xfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciByZXNwb25zZSBsaW5lAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBuYW1lAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgZXh0ZW5zaW9uIG5hbWUASW52YWxpZCBzdGF0dXMgY29kZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABNaXNzaW5nIGV4cGVjdGVkIENSIGFmdGVyIGNodW5rIGRhdGEARXhwZWN0ZWQgTEYgYWZ0ZXIgY2h1bmsgZGF0YQBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AARGF0YSBhZnRlciBgQ29ubmVjdGlvbjogY2xvc2VgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBRVUVSWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAEV4cGVjdGVkIExGIGFmdGVyIENSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX1BST1RPQ09MX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19DT01QTEVURQBIUEVfQ0JfSEVBREVSX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9OQU1FX0NPTVBMRVRFAEhQRV9DQl9NRVNTQUdFX0NPTVBMRVRFAEhQRV9DQl9NRVRIT0RfQ09NUExFVEUASFBFX0NCX0hFQURFUl9GSUVMRF9DT01QTEVURQBERUxFVEUASFBFX0lOVkFMSURfRU9GX1NUQVRFAElOVkFMSURfU1NMX0NFUlRJRklDQVRFAFBBVVNFAE5PX1JFU1BPTlNFAFVOU1VQUE9SVEVEX01FRElBX1RZUEUAR09ORQBOT1RfQUNDRVBUQUJMRQBTRVJWSUNFX1VOQVZBSUxBQkxFAFJBTkdFX05PVF9TQVRJU0ZJQUJMRQBPUklHSU5fSVNfVU5SRUFDSEFCTEUAUkVTUE9OU0VfSVNfU1RBTEUAUFVSR0UATUVSR0UAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRQBSRVFVRVNUX0hFQURFUl9UT09fTEFSR0UAUEFZTE9BRF9UT09fTEFSR0UASU5TVUZGSUNJRU5UX1NUT1JBR0UASFBFX1BBVVNFRF9VUEdSQURFAEhQRV9QQVVTRURfSDJfVVBHUkFERQBTT1VSQ0UAQU5OT1VOQ0UAVFJBQ0UASFBFX1VORVhQRUNURURfU1BBQ0UAREVTQ1JJQkUAVU5TVUJTQ1JJQkUAUkVDT1JEAEhQRV9JTlZBTElEX01FVEhPRABOT1RfRk9VTkQAUFJPUEZJTkQAVU5CSU5EAFJFQklORABVTkFVVEhPUklaRUQATUVUSE9EX05PVF9BTExPV0VEAEhUVFBfVkVSU0lPTl9OT1RfU1VQUE9SVEVEAEFMUkVBRFlfUkVQT1JURUQAQUNDRVBURUQATk9UX0lNUExFTUVOVEVEAExPT1BfREVURUNURUQASFBFX0NSX0VYUEVDVEVEAEhQRV9MRl9FWFBFQ1RFRABDUkVBVEVEAElNX1VTRUQASFBFX1BBVVNFRABUSU1FT1VUX09DQ1VSRUQAUEFZTUVOVF9SRVFVSVJFRABQUkVDT05ESVRJT05fUkVRVUlSRUQAUFJPWFlfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATkVUV09SS19BVVRIRU5USUNBVElPTl9SRVFVSVJFRABMRU5HVEhfUkVRVUlSRUQAU1NMX0NFUlRJRklDQVRFX1JFUVVJUkVEAFVQR1JBREVfUkVRVUlSRUQAUEFHRV9FWFBJUkVEAFBSRUNPTkRJVElPTl9GQUlMRUQARVhQRUNUQVRJT05fRkFJTEVEAFJFVkFMSURBVElPTl9GQUlMRUQAU1NMX0hBTkRTSEFLRV9GQUlMRUQATE9DS0VEAFRSQU5TRk9STUFUSU9OX0FQUExJRUQATk9UX01PRElGSUVEAE5PVF9FWFRFTkRFRABCQU5EV0lEVEhfTElNSVRfRVhDRUVERUQAU0lURV9JU19PVkVSTE9BREVEAEhFQUQARXhwZWN0ZWQgSFRUUC8sIFJUU1AvIG9yIElDRS8A5xUAAK8VAACkEgAAkhoAACYWAACeFAAA2xkAAHkVAAB+EgAA/hQAADYVAAALFgAA2BYAAPMSAABCGAAArBYAABIVAAAUFwAA7xcAAEgUAABxFwAAshoAAGsZAAB+GQAANRQAAIIaAABEFwAA/RYAAB4YAACHFwAAqhkAAJMSAAAHGAAALBcAAMoXAACkFwAA5xUAAOcVAABYFwAAOxgAAKASAAAtHAAAwxEAAEgRAADeEgAAQhMAAKQZAAD9EAAA9xUAAKUVAADvFgAA+BkAAEoWAABWFgAA9RUAAAoaAAAIGgAAARoAAKsVAABCEgAA1xAAAEwRAAAFGQAAVBYAAB4RAADKGQAAyBkAAE4WAAD/GAAAcRQAAPAVAADuFQAAlBkAAPwVAAC/GQAAmxkAAHwUAABDEQAAcBgAAJUUAAAnFAAAGRQAANUSAADUGQAARBYAAPcQAEG5OwsBAQBB0DsL4AEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBBuj0LBAEAAAIAQdE9C14DBAMDAwMDAAADAwADAwADAwMDAwMDAwMDAAUAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAwADAEG6PwsEAQAAAgBB0T8LXgMAAwMDAwMAAAMDAAMDAAMDAwMDAwMDAwMABAAFAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwADAAMAQbDBAAsNbG9zZWVlcC1hbGl2ZQBBycEACwEBAEHgwQAL4AEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBBycMACwEBAEHgwwAL5wEBAQEBAQEBAQEBAQECAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAWNodW5rZWQAQfHFAAteAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQBB0McACyFlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AQYDIAAsgcmFuc2Zlci1lbmNvZGluZ3BncmFkZQ0KDQpTTQ0KDQoAQanIAAsFAQIAAQMAQcDIAAtfBAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAQanKAAsFAQIAAQMAQcDKAAtfBAUFBgUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAQanMAAsEAQAAAQBBwcwAC14CAgACAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAEGpzgALBQECAAEDAEHAzgALXwQFAAAFBQUFBQUFBQUFBQYFBQUFBQUFBQUFBQUABQAHCAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQAFAAUABQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAAAAFAEGp0AALBQEBAAEBAEHA0AALAQEAQdrQAAtBAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQanSAAsFAQEAAQEAQcDSAAsBAQBBytIACwYCAAAAAAIAQeHSAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBBoNQAC50BTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRVVFUllPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFVFRQQ0VUU1BBRFRQLw=="; + var wasmBuffer; + Object.defineProperty(module2, "exports", { + get: () => { + return wasmBuffer ? wasmBuffer : wasmBuffer = Buffer3.from(wasmBase64, "base64"); + } + }); } }); @@ -3266,8 +4181,14 @@ var require_llhttp_wasm = __commonJS({ var require_llhttp_simd_wasm = __commonJS({ "node_modules/undici/lib/llhttp/llhttp_simd-wasm.js"(exports2, module2) { "use strict"; - var { Buffer: Buffer2 } = require("node:buffer"); - module2.exports = Buffer2.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"); + var { Buffer: Buffer3 } = require("node:buffer"); + var wasmBase64 = "AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzU0BQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEBAwAAAwAAAAQFAXABExMFAwEAAgYIAX8BQcDZBAsHxQcoBm1lbW9yeQIAC19pbml0aWFsaXplAAgZX19pbmRpcmVjdF9mdW5jdGlvbl90YWJsZQEAC2xsaHR0cF9pbml0AAkYbGxodHRwX3Nob3VsZF9rZWVwX2FsaXZlADcMbGxodHRwX2FsbG9jAAsGbWFsbG9jADkLbGxodHRwX2ZyZWUADARmcmVlAAwPbGxodHRwX2dldF90eXBlAA0VbGxodHRwX2dldF9odHRwX21ham9yAA4VbGxodHRwX2dldF9odHRwX21pbm9yAA8RbGxodHRwX2dldF9tZXRob2QAEBZsbGh0dHBfZ2V0X3N0YXR1c19jb2RlABESbGxodHRwX2dldF91cGdyYWRlABIMbGxodHRwX3Jlc2V0ABMObGxodHRwX2V4ZWN1dGUAFBRsbGh0dHBfc2V0dGluZ3NfaW5pdAAVDWxsaHR0cF9maW5pc2gAFgxsbGh0dHBfcGF1c2UAFw1sbGh0dHBfcmVzdW1lABgbbGxodHRwX3Jlc3VtZV9hZnRlcl91cGdyYWRlABkQbGxodHRwX2dldF9lcnJubwAaF2xsaHR0cF9nZXRfZXJyb3JfcmVhc29uABsXbGxodHRwX3NldF9lcnJvcl9yZWFzb24AHBRsbGh0dHBfZ2V0X2Vycm9yX3BvcwAdEWxsaHR0cF9lcnJub19uYW1lAB4SbGxodHRwX21ldGhvZF9uYW1lAB8SbGxodHRwX3N0YXR1c19uYW1lACAabGxodHRwX3NldF9sZW5pZW50X2hlYWRlcnMAISFsbGh0dHBfc2V0X2xlbmllbnRfY2h1bmtlZF9sZW5ndGgAIh1sbGh0dHBfc2V0X2xlbmllbnRfa2VlcF9hbGl2ZQAjJGxsaHR0cF9zZXRfbGVuaWVudF90cmFuc2Zlcl9lbmNvZGluZwAkGmxsaHR0cF9zZXRfbGVuaWVudF92ZXJzaW9uACUjbGxodHRwX3NldF9sZW5pZW50X2RhdGFfYWZ0ZXJfY2xvc2UAJidsbGh0dHBfc2V0X2xlbmllbnRfb3B0aW9uYWxfbGZfYWZ0ZXJfY3IAJyxsbGh0dHBfc2V0X2xlbmllbnRfb3B0aW9uYWxfY3JsZl9hZnRlcl9jaHVuawAoKGxsaHR0cF9zZXRfbGVuaWVudF9vcHRpb25hbF9jcl9iZWZvcmVfbGYAKSpsbGh0dHBfc2V0X2xlbmllbnRfc3BhY2VzX2FmdGVyX2NodW5rX3NpemUAKhhsbGh0dHBfbWVzc2FnZV9uZWVkc19lb2YANgkYAQBBAQsSAQIDBAUKBgcyNDMuKy8tLDAxCuzaAjQWAEHA1QAoAgAEQAALQcDVAEEBNgIACxQAIAAQOCAAIAI2AjggACABOgAoCxQAIAAgAC8BNCAALQAwIAAQNxAACx4BAX9BwAAQOiIBEDggAUGACDYCOCABIAA6ACggAQuPDAEHfwJAIABFDQAgAEEIayIBIABBBGsoAgAiAEF4cSIEaiEFAkAgAEEBcQ0AIABBA3FFDQEgASABKAIAIgBrIgFB1NUAKAIASQ0BIAAgBGohBAJAAkBB2NUAKAIAIAFHBEAgAEH/AU0EQCAAQQN2IQMgASgCCCIAIAEoAgwiAkYEQEHE1QBBxNUAKAIAQX4gA3dxNgIADAULIAIgADYCCCAAIAI2AgwMBAsgASgCGCEGIAEgASgCDCIARwRAIAAgASgCCCICNgIIIAIgADYCDAwDCyABQRRqIgMoAgAiAkUEQCABKAIQIgJFDQIgAUEQaiEDCwNAIAMhByACIgBBFGoiAygCACICDQAgAEEQaiEDIAAoAhAiAg0ACyAHQQA2AgAMAgsgBSgCBCIAQQNxQQNHDQIgBSAAQX5xNgIEQczVACAENgIAIAUgBDYCACABIARBAXI2AgQMAwtBACEACyAGRQ0AAkAgASgCHCICQQJ0QfTXAGoiAygCACABRgRAIAMgADYCACAADQFByNUAQcjVACgCAEF+IAJ3cTYCAAwCCyAGQRBBFCAGKAIQIAFGG2ogADYCACAARQ0BCyAAIAY2AhggASgCECICBEAgACACNgIQIAIgADYCGAsgAUEUaigCACICRQ0AIABBFGogAjYCACACIAA2AhgLIAEgBU8NACAFKAIEIgBBAXFFDQACQAJAAkACQCAAQQJxRQRAQdzVACgCACAFRgRAQdzVACABNgIAQdDVAEHQ1QAoAgAgBGoiADYCACABIABBAXI2AgQgAUHY1QAoAgBHDQZBzNUAQQA2AgBB2NUAQQA2AgAMBgtB2NUAKAIAIAVGBEBB2NUAIAE2AgBBzNUAQczVACgCACAEaiIANgIAIAEgAEEBcjYCBCAAIAFqIAA2AgAMBgsgAEF4cSAEaiEEIABB/wFNBEAgAEEDdiEDIAUoAggiACAFKAIMIgJGBEBBxNUAQcTVACgCAEF+IAN3cTYCAAwFCyACIAA2AgggACACNgIMDAQLIAUoAhghBiAFIAUoAgwiAEcEQEHU1QAoAgAaIAAgBSgCCCICNgIIIAIgADYCDAwDCyAFQRRqIgMoAgAiAkUEQCAFKAIQIgJFDQIgBUEQaiEDCwNAIAMhByACIgBBFGoiAygCACICDQAgAEEQaiEDIAAoAhAiAg0ACyAHQQA2AgAMAgsgBSAAQX5xNgIEIAEgBGogBDYCACABIARBAXI2AgQMAwtBACEACyAGRQ0AAkAgBSgCHCICQQJ0QfTXAGoiAygCACAFRgRAIAMgADYCACAADQFByNUAQcjVACgCAEF+IAJ3cTYCAAwCCyAGQRBBFCAGKAIQIAVGG2ogADYCACAARQ0BCyAAIAY2AhggBSgCECICBEAgACACNgIQIAIgADYCGAsgBUEUaigCACICRQ0AIABBFGogAjYCACACIAA2AhgLIAEgBGogBDYCACABIARBAXI2AgQgAUHY1QAoAgBHDQBBzNUAIAQ2AgAMAQsgBEH/AU0EQCAEQXhxQezVAGohAAJ/QcTVACgCACICQQEgBEEDdnQiA3FFBEBBxNUAIAIgA3I2AgAgAAwBCyAAKAIICyICIAE2AgwgACABNgIIIAEgADYCDCABIAI2AggMAQtBHyECIARB////B00EQCAEQSYgBEEIdmciAGt2QQFxIABBAXRrQT5qIQILIAEgAjYCHCABQgA3AhAgAkECdEH01wBqIQACQEHI1QAoAgAiA0EBIAJ0IgdxRQRAIAAgATYCAEHI1QAgAyAHcjYCACABIAA2AhggASABNgIIIAEgATYCDAwBCyAEQRkgAkEBdmtBACACQR9HG3QhAiAAKAIAIQACQANAIAAiAygCBEF4cSAERg0BIAJBHXYhACACQQF0IQIgAyAAQQRxakEQaiIHKAIAIgANAAsgByABNgIAIAEgAzYCGCABIAE2AgwgASABNgIIDAELIAMoAggiACABNgIMIAMgATYCCCABQQA2AhggASADNgIMIAEgADYCCAtB5NUAQeTVACgCAEEBayIAQX8gABs2AgALCwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgLhocCAwd/A34BeyABIAJqIQQCQCAAIgMoAgwiAA0AIAMoAgQEQCADIAE2AgQLIwBBEGsiCSQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADKAIcIgJBAmsO/AEB+QECAwQFBgcICQoLDA0ODxAREvgBE/cBFBX2ARYX9QEYGRobHB0eHyD9AfsBIfQBIiMkJSYnKCkqK/MBLC0uLzAxMvIB8QEzNPAB7wE1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk/6AVBRUlPuAe0BVOwBVesBVldYWVrqAVtcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AAYEBggGDAYQBhQGGAYcBiAGJAYoBiwGMAY0BjgGPAZABkQGSAZMBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBuAG5AboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBxwHIAckBygHLAcwBzQHOAekB6AHPAecB0AHmAdEB0gHTAdQB5QHVAdYB1wHYAdkB2gHbAdwB3QHeAd8B4AHhAeIB4wEA/AELQQAM4wELQQ4M4gELQQ0M4QELQQ8M4AELQRAM3wELQRMM3gELQRQM3QELQRUM3AELQRYM2wELQRcM2gELQRgM2QELQRkM2AELQRoM1wELQRsM1gELQRwM1QELQR0M1AELQR4M0wELQR8M0gELQSAM0QELQSEM0AELQQgMzwELQSIMzgELQSQMzQELQSMMzAELQQcMywELQSUMygELQSYMyQELQScMyAELQSgMxwELQRIMxgELQREMxQELQSkMxAELQSoMwwELQSsMwgELQSwMwQELQd4BDMABC0EuDL8BC0EvDL4BC0EwDL0BC0ExDLwBC0EyDLsBC0EzDLoBC0E0DLkBC0HfAQy4AQtBNQy3AQtBOQy2AQtBDAy1AQtBNgy0AQtBNwyzAQtBOAyyAQtBPgyxAQtBOgywAQtB4AEMrwELQQsMrgELQT8MrQELQTsMrAELQQoMqwELQTwMqgELQT0MqQELQeEBDKgBC0HBAAynAQtBwAAMpgELQcIADKUBC0EJDKQBC0EtDKMBC0HDAAyiAQtBxAAMoQELQcUADKABC0HGAAyfAQtBxwAMngELQcgADJ0BC0HJAAycAQtBygAMmwELQcsADJoBC0HMAAyZAQtBzQAMmAELQc4ADJcBC0HPAAyWAQtB0AAMlQELQdEADJQBC0HSAAyTAQtB0wAMkgELQdUADJEBC0HUAAyQAQtB1gAMjwELQdcADI4BC0HYAAyNAQtB2QAMjAELQdoADIsBC0HbAAyKAQtB3AAMiQELQd0ADIgBC0HeAAyHAQtB3wAMhgELQeAADIUBC0HhAAyEAQtB4gAMgwELQeMADIIBC0HkAAyBAQtB5QAMgAELQeIBDH8LQeYADH4LQecADH0LQQYMfAtB6AAMewtBBQx6C0HpAAx5C0EEDHgLQeoADHcLQesADHYLQewADHULQe0ADHQLQQMMcwtB7gAMcgtB7wAMcQtB8AAMcAtB8gAMbwtB8QAMbgtB8wAMbQtB9AAMbAtB9QAMawtB9gAMagtBAgxpC0H3AAxoC0H4AAxnC0H5AAxmC0H6AAxlC0H7AAxkC0H8AAxjC0H9AAxiC0H+AAxhC0H/AAxgC0GAAQxfC0GBAQxeC0GCAQxdC0GDAQxcC0GEAQxbC0GFAQxaC0GGAQxZC0GHAQxYC0GIAQxXC0GJAQxWC0GKAQxVC0GLAQxUC0GMAQxTC0GNAQxSC0GOAQxRC0GPAQxQC0GQAQxPC0GRAQxOC0GSAQxNC0GTAQxMC0GUAQxLC0GVAQxKC0GWAQxJC0GXAQxIC0GYAQxHC0GZAQxGC0GaAQxFC0GbAQxEC0GcAQxDC0GdAQxCC0GeAQxBC0GfAQxAC0GgAQw/C0GhAQw+C0GiAQw9C0GjAQw8C0GkAQw7C0GlAQw6C0GmAQw5C0GnAQw4C0GoAQw3C0GpAQw2C0GqAQw1C0GrAQw0C0GsAQwzC0GtAQwyC0GuAQwxC0GvAQwwC0GwAQwvC0GxAQwuC0GyAQwtC0GzAQwsC0G0AQwrC0G1AQwqC0G2AQwpC0G3AQwoC0G4AQwnC0G5AQwmC0G6AQwlC0G7AQwkC0G8AQwjC0G9AQwiC0G+AQwhC0G/AQwgC0HAAQwfC0HBAQweC0HCAQwdC0EBDBwLQcMBDBsLQcQBDBoLQcUBDBkLQcYBDBgLQccBDBcLQcgBDBYLQckBDBULQcoBDBQLQcsBDBMLQcwBDBILQc0BDBELQc4BDBALQc8BDA8LQdABDA4LQdEBDA0LQdIBDAwLQdMBDAsLQdQBDAoLQdUBDAkLQdYBDAgLQeMBDAcLQdcBDAYLQdgBDAULQdkBDAQLQdoBDAMLQdsBDAILQd0BDAELQdwBCyECA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAn8CQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAwJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCACDuMBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISMkJScoKZ4DmwOaA5EDigODA4AD/QL7AvgC8gLxAu8C7QLoAucC5gLlAuQC3ALbAtoC2QLYAtcC1gLVAs8CzgLMAssCygLJAsgCxwLGAsQCwwK+ArwCugK5ArgCtwK2ArUCtAKzArICsQKwAq4CrQKpAqgCpwKmAqUCpAKjAqICoQKgAp8CmAKQAowCiwKKAoEC/gH9AfwB+wH6AfkB+AH3AfUB8wHwAesB6QHoAecB5gHlAeQB4wHiAeEB4AHfAd4B3QHcAdoB2QHYAdcB1gHVAdQB0wHSAdEB0AHPAc4BzQHMAcsBygHJAcgBxwHGAcUBxAHDAcIBwQHAAb8BvgG9AbwBuwG6AbkBuAG3AbYBtQG0AbMBsgGxAbABrwGuAa0BrAGrAaoBqQGoAacBpgGlAaQBowGiAZ8BngGZAZgBlwGWAZUBlAGTAZIBkQGQAY8BjQGMAYcBhgGFAYQBgwGCAX18e3p5dnV0UFFSU1RVCyABIARHDXJB/QEhAgy+AwsgASAERw2YAUHbASECDL0DCyABIARHDfEBQY4BIQIMvAMLIAEgBEcN/AFBhAEhAgy7AwsgASAERw2KAkH/ACECDLoDCyABIARHDZECQf0AIQIMuQMLIAEgBEcNlAJB+wAhAgy4AwsgASAERw0eQR4hAgy3AwsgASAERw0ZQRghAgy2AwsgASAERw3KAkHNACECDLUDCyABIARHDdUCQcYAIQIMtAMLIAEgBEcN1gJBwwAhAgyzAwsgASAERw3cAkE4IQIMsgMLIAMtADBBAUYNrQMMiQMLQQAhAAJAAkACQCADLQAqRQ0AIAMtACtFDQAgAy8BMiICQQJxRQ0BDAILIAMvATIiAkEBcUUNAQtBASEAIAMtAChBAUYNACADLwE0IgZB5ABrQeQASQ0AIAZBzAFGDQAgBkGwAkYNACACQcAAcQ0AQQAhACACQYgEcUGABEYNACACQShxQQBHIQALIANBADsBMiADQQA6ADECQCAARQRAIANBADoAMSADLQAuQQRxDQEMsQMLIANCADcDIAsgA0EAOgAxIANBAToANgxIC0EAIQACQCADKAI4IgJFDQAgAigCMCICRQ0AIAMgAhEAACEACyAARQ1IIABBFUcNYiADQQQ2AhwgAyABNgIUIANB0hs2AhAgA0EVNgIMQQAhAgyvAwsgASAERgRAQQYhAgyvAwsgAS0AAEEKRw0ZIAFBAWohAQwaCyADQgA3AyBBEiECDJQDCyABIARHDYoDQSMhAgysAwsgASAERgRAQQchAgysAwsCQAJAIAEtAABBCmsOBAEYGAAYCyABQQFqIQFBECECDJMDCyABQQFqIQEgA0Evai0AAEEBcQ0XQQAhAiADQQA2AhwgAyABNgIUIANBmSA2AhAgA0EZNgIMDKsDCyADIAMpAyAiDCAEIAFrrSIKfSILQgAgCyAMWBs3AyAgCiAMWg0YQQghAgyqAwsgASAERwRAIANBCTYCCCADIAE2AgRBFCECDJEDC0EJIQIMqQMLIAMpAyBQDa4CDEMLIAEgBEYEQEELIQIMqAMLIAEtAABBCkcNFiABQQFqIQEMFwsgA0Evai0AAEEBcUUNGQwmC0EAIQACQCADKAI4IgJFDQAgAigCUCICRQ0AIAMgAhEAACEACyAADRkMQgtBACEAAkAgAygCOCICRQ0AIAIoAlAiAkUNACADIAIRAAAhAAsgAA0aDCQLQQAhAAJAIAMoAjgiAkUNACACKAJQIgJFDQAgAyACEQAAIQALIAANGwwyCyADQS9qLQAAQQFxRQ0cDCILQQAhAAJAIAMoAjgiAkUNACACKAJUIgJFDQAgAyACEQAAIQALIAANHAxCC0EAIQACQCADKAI4IgJFDQAgAigCVCICRQ0AIAMgAhEAACEACyAADR0MIAsgASAERgRAQRMhAgygAwsCQCABLQAAIgBBCmsOBB8jIwAiCyABQQFqIQEMHwtBACEAAkAgAygCOCICRQ0AIAIoAlQiAkUNACADIAIRAAAhAAsgAA0iDEILIAEgBEYEQEEWIQIMngMLIAEtAABBwMEAai0AAEEBRw0jDIMDCwJAA0AgAS0AAEGwO2otAAAiAEEBRwRAAkAgAEECaw4CAwAnCyABQQFqIQFBISECDIYDCyAEIAFBAWoiAUcNAAtBGCECDJ0DCyADKAIEIQBBACECIANBADYCBCADIAAgAUEBaiIBEDQiAA0hDEELQQAhAAJAIAMoAjgiAkUNACACKAJUIgJFDQAgAyACEQAAIQALIAANIwwqCyABIARGBEBBHCECDJsDCyADQQo2AgggAyABNgIEQQAhAAJAIAMoAjgiAkUNACACKAJQIgJFDQAgAyACEQAAIQALIAANJUEkIQIMgQMLIAEgBEcEQANAIAEtAABBsD1qLQAAIgBBA0cEQCAAQQFrDgUYGiaCAyUmCyAEIAFBAWoiAUcNAAtBGyECDJoDC0EbIQIMmQMLA0AgAS0AAEGwP2otAAAiAEEDRwRAIABBAWsOBQ8RJxMmJwsgBCABQQFqIgFHDQALQR4hAgyYAwsgASAERwRAIANBCzYCCCADIAE2AgRBByECDP8CC0EfIQIMlwMLIAEgBEYEQEEgIQIMlwMLAkAgAS0AAEENaw4ULj8/Pz8/Pz8/Pz8/Pz8/Pz8/PwA/C0EAIQIgA0EANgIcIANBvws2AhAgA0ECNgIMIAMgAUEBajYCFAyWAwsgA0EvaiECA0AgASAERgRAQSEhAgyXAwsCQAJAAkAgAS0AACIAQQlrDhgCACkpASkpKSkpKSkpKSkpKSkpKSkpKQInCyABQQFqIQEgA0Evai0AAEEBcUUNCgwYCyABQQFqIQEMFwsgAUEBaiEBIAItAABBAnENAAtBACECIANBADYCHCADIAE2AhQgA0GfFTYCECADQQw2AgwMlQMLIAMtAC5BgAFxRQ0BC0EAIQACQCADKAI4IgJFDQAgAigCXCICRQ0AIAMgAhEAACEACyAARQ3mAiAAQRVGBEAgA0EkNgIcIAMgATYCFCADQZsbNgIQIANBFTYCDEEAIQIMlAMLQQAhAiADQQA2AhwgAyABNgIUIANBkA42AhAgA0EUNgIMDJMDC0EAIQIgA0EANgIcIAMgATYCFCADQb4gNgIQIANBAjYCDAySAwsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEgDKdqIgEQMiIARQ0rIANBBzYCHCADIAE2AhQgAyAANgIMDJEDCyADLQAuQcAAcUUNAQtBACEAAkAgAygCOCICRQ0AIAIoAlgiAkUNACADIAIRAAAhAAsgAEUNKyAAQRVGBEAgA0EKNgIcIAMgATYCFCADQesZNgIQIANBFTYCDEEAIQIMkAMLQQAhAiADQQA2AhwgAyABNgIUIANBkww2AhAgA0ETNgIMDI8DC0EAIQIgA0EANgIcIAMgATYCFCADQYIVNgIQIANBAjYCDAyOAwtBACECIANBADYCHCADIAE2AhQgA0HdFDYCECADQRk2AgwMjQMLQQAhAiADQQA2AhwgAyABNgIUIANB5h02AhAgA0EZNgIMDIwDCyAAQRVGDT1BACECIANBADYCHCADIAE2AhQgA0HQDzYCECADQSI2AgwMiwMLIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDMiAEUNKCADQQ02AhwgAyABNgIUIAMgADYCDAyKAwsgAEEVRg06QQAhAiADQQA2AhwgAyABNgIUIANB0A82AhAgA0EiNgIMDIkDCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDCgLIANBDjYCHCADIAA2AgwgAyABQQFqNgIUDIgDCyAAQRVGDTdBACECIANBADYCHCADIAE2AhQgA0HQDzYCECADQSI2AgwMhwMLIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDMiAEUEQCABQQFqIQEMJwsgA0EPNgIcIAMgADYCDCADIAFBAWo2AhQMhgMLQQAhAiADQQA2AhwgAyABNgIUIANB4hc2AhAgA0EZNgIMDIUDCyAAQRVGDTNBACECIANBADYCHCADIAE2AhQgA0HWDDYCECADQSM2AgwMhAMLIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDQiAEUNJSADQRE2AhwgAyABNgIUIAMgADYCDAyDAwsgAEEVRg0wQQAhAiADQQA2AhwgAyABNgIUIANB1gw2AhAgA0EjNgIMDIIDCyADKAIEIQBBACECIANBADYCBCADIAAgARA0IgBFBEAgAUEBaiEBDCULIANBEjYCHCADIAA2AgwgAyABQQFqNgIUDIEDCyADQS9qLQAAQQFxRQ0BC0EXIQIM5gILQQAhAiADQQA2AhwgAyABNgIUIANB4hc2AhAgA0EZNgIMDP4CCyAAQTtHDQAgAUEBaiEBDAwLQQAhAiADQQA2AhwgAyABNgIUIANBkhg2AhAgA0ECNgIMDPwCCyAAQRVGDShBACECIANBADYCHCADIAE2AhQgA0HWDDYCECADQSM2AgwM+wILIANBFDYCHCADIAE2AhQgAyAANgIMDPoCCyADKAIEIQBBACECIANBADYCBCADIAAgARA0IgBFBEAgAUEBaiEBDPUCCyADQRU2AhwgAyAANgIMIAMgAUEBajYCFAz5AgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQNCIARQRAIAFBAWohAQzzAgsgA0EXNgIcIAMgADYCDCADIAFBAWo2AhQM+AILIABBFUYNI0EAIQIgA0EANgIcIAMgATYCFCADQdYMNgIQIANBIzYCDAz3AgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQNCIARQRAIAFBAWohAQwdCyADQRk2AhwgAyAANgIMIAMgAUEBajYCFAz2AgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQNCIARQRAIAFBAWohAQzvAgsgA0EaNgIcIAMgADYCDCADIAFBAWo2AhQM9QILIABBFUYNH0EAIQIgA0EANgIcIAMgATYCFCADQdAPNgIQIANBIjYCDAz0AgsgAygCBCEAIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDBsLIANBHDYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgzzAgsgAygCBCEAIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDOsCCyADQR02AhwgAyAANgIMIAMgAUEBajYCFEEAIQIM8gILIABBO0cNASABQQFqIQELQSYhAgzXAgtBACECIANBADYCHCADIAE2AhQgA0GfFTYCECADQQw2AgwM7wILIAEgBEcEQANAIAEtAABBIEcNhAIgBCABQQFqIgFHDQALQSwhAgzvAgtBLCECDO4CCyABIARGBEBBNCECDO4CCwJAAkADQAJAIAEtAABBCmsOBAIAAAMACyAEIAFBAWoiAUcNAAtBNCECDO8CCyADKAIEIQAgA0EANgIEIAMgACABEDEiAEUNnwIgA0EyNgIcIAMgATYCFCADIAA2AgxBACECDO4CCyADKAIEIQAgA0EANgIEIAMgACABEDEiAEUEQCABQQFqIQEMnwILIANBMjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgztAgsgASAERwRAAkADQCABLQAAQTBrIgBB/wFxQQpPBEBBOiECDNcCCyADKQMgIgtCmbPmzJmz5swZVg0BIAMgC0IKfiIKNwMgIAogAK1C/wGDIgtCf4VWDQEgAyAKIAt8NwMgIAQgAUEBaiIBRw0AC0HAACECDO4CCyADKAIEIQAgA0EANgIEIAMgACABQQFqIgEQMSIADRcM4gILQcAAIQIM7AILIAEgBEYEQEHJACECDOwCCwJAA0ACQCABLQAAQQlrDhgAAqICogKpAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAgCiAgsgBCABQQFqIgFHDQALQckAIQIM7AILIAFBAWohASADQS9qLQAAQQFxDaUCIANBADYCHCADIAE2AhQgA0GXEDYCECADQQo2AgxBACECDOsCCyABIARHBEADQCABLQAAQSBHDRUgBCABQQFqIgFHDQALQfgAIQIM6wILQfgAIQIM6gILIANBAjoAKAw4C0EAIQIgA0EANgIcIANBvws2AhAgA0ECNgIMIAMgAUEBajYCFAzoAgtBACECDM4CC0ENIQIMzQILQRMhAgzMAgtBFSECDMsCC0EWIQIMygILQRghAgzJAgtBGSECDMgCC0EaIQIMxwILQRshAgzGAgtBHCECDMUCC0EdIQIMxAILQR4hAgzDAgtBHyECDMICC0EgIQIMwQILQSIhAgzAAgtBIyECDL8CC0ElIQIMvgILQeUAIQIMvQILIANBPTYCHCADIAE2AhQgAyAANgIMQQAhAgzVAgsgA0EbNgIcIAMgATYCFCADQaQcNgIQIANBFTYCDEEAIQIM1AILIANBIDYCHCADIAE2AhQgA0GYGjYCECADQRU2AgxBACECDNMCCyADQRM2AhwgAyABNgIUIANBmBo2AhAgA0EVNgIMQQAhAgzSAgsgA0ELNgIcIAMgATYCFCADQZgaNgIQIANBFTYCDEEAIQIM0QILIANBEDYCHCADIAE2AhQgA0GYGjYCECADQRU2AgxBACECDNACCyADQSA2AhwgAyABNgIUIANBpBw2AhAgA0EVNgIMQQAhAgzPAgsgA0ELNgIcIAMgATYCFCADQaQcNgIQIANBFTYCDEEAIQIMzgILIANBDDYCHCADIAE2AhQgA0GkHDYCECADQRU2AgxBACECDM0CC0EAIQIgA0EANgIcIAMgATYCFCADQd0ONgIQIANBEjYCDAzMAgsCQANAAkAgAS0AAEEKaw4EAAICAAILIAQgAUEBaiIBRw0AC0H9ASECDMwCCwJAAkAgAy0ANkEBRw0AQQAhAAJAIAMoAjgiAkUNACACKAJgIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB/AE2AhwgAyABNgIUIANB3Bk2AhAgA0EVNgIMQQAhAgzNAgtB3AEhAgyzAgsgA0EANgIcIAMgATYCFCADQfkLNgIQIANBHzYCDEEAIQIMywILAkACQCADLQAoQQFrDgIEAQALQdsBIQIMsgILQdQBIQIMsQILIANBAjoAMUEAIQACQCADKAI4IgJFDQAgAigCACICRQ0AIAMgAhEAACEACyAARQRAQd0BIQIMsQILIABBFUcEQCADQQA2AhwgAyABNgIUIANBtAw2AhAgA0EQNgIMQQAhAgzKAgsgA0H7ATYCHCADIAE2AhQgA0GBGjYCECADQRU2AgxBACECDMkCCyABIARGBEBB+gEhAgzJAgsgAS0AAEHIAEYNASADQQE6ACgLQcABIQIMrgILQdoBIQIMrQILIAEgBEcEQCADQQw2AgggAyABNgIEQdkBIQIMrQILQfkBIQIMxQILIAEgBEYEQEH4ASECDMUCCyABLQAAQcgARw0EIAFBAWohAUHYASECDKsCCyABIARGBEBB9wEhAgzEAgsCQAJAIAEtAABBxQBrDhAABQUFBQUFBQUFBQUFBQUBBQsgAUEBaiEBQdYBIQIMqwILIAFBAWohAUHXASECDKoCC0H2ASECIAEgBEYNwgIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABButUAai0AAEcNAyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMwwILIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAuIgBFBEBB4wEhAgyqAgsgA0H1ATYCHCADIAE2AhQgAyAANgIMQQAhAgzCAgtB9AEhAiABIARGDcECIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbjVAGotAABHDQIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADMICCyADQYEEOwEoIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAuIgANAwwCCyADQQA2AgALQQAhAiADQQA2AhwgAyABNgIUIANB5R82AhAgA0EINgIMDL8CC0HVASECDKUCCyADQfMBNgIcIAMgATYCFCADIAA2AgxBACECDL0CC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQ1uIABBFUcEQCADQQA2AhwgAyABNgIUIANBgg82AhAgA0EgNgIMQQAhAgy9AgsgA0GPATYCHCADIAE2AhQgA0HsGzYCECADQRU2AgxBACECDLwCCyABIARHBEAgA0ENNgIIIAMgATYCBEHTASECDKMCC0HyASECDLsCCyABIARGBEBB8QEhAgy7AgsCQAJAAkAgAS0AAEHIAGsOCwABCAgICAgICAgCCAsgAUEBaiEBQdABIQIMowILIAFBAWohAUHRASECDKICCyABQQFqIQFB0gEhAgyhAgtB8AEhAiABIARGDbkCIAMoAgAiACAEIAFraiEGIAEgAGtBAmohBQNAIAEtAAAgAEG11QBqLQAARw0EIABBAkYNAyAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy5AgtB7wEhAiABIARGDbgCIAMoAgAiACAEIAFraiEGIAEgAGtBAWohBQNAIAEtAAAgAEGz1QBqLQAARw0DIABBAUYNAiAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy4AgtB7gEhAiABIARGDbcCIAMoAgAiACAEIAFraiEGIAEgAGtBAmohBQNAIAEtAAAgAEGw1QBqLQAARw0CIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy3AgsgAygCBCEAIANCADcDACADIAAgBUEBaiIBECsiAEUNAiADQewBNgIcIAMgATYCFCADIAA2AgxBACECDLYCCyADQQA2AgALIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ2cAiADQe0BNgIcIAMgATYCFCADIAA2AgxBACECDLQCC0HPASECDJoCC0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMtAILQc4BIQIMmgILIANB6wE2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyyAgsgASAERgRAQesBIQIMsgILIAEtAABBL0YEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQbI4NgIQIANBCDYCDEEAIQIMsQILQc0BIQIMlwILIAEgBEcEQCADQQ42AgggAyABNgIEQcwBIQIMlwILQeoBIQIMrwILIAEgBEYEQEHpASECDK8CCyABLQAAQTBrIgBB/wFxQQpJBEAgAyAAOgAqIAFBAWohAUHLASECDJYCCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNlwIgA0HoATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgsgASAERgRAQecBIQIMrgILAkAgAS0AAEEuRgRAIAFBAWohAQwBCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNmAIgA0HmATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgtBygEhAgyUAgsgASAERgRAQeUBIQIMrQILQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNAiADQeIBNgIcIAMgATYCFCADIAA2AgxBACECDK8CCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNmgIgA0HjATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZgCIANB5AE2AhwgAyABNgIUIAMgADYCDAytAgtByQEhAgyTAgtBACEAAkAgAygCOCICRQ0AIAIoAkQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0GkDTYCECADQSE2AgxBACECDK0CC0HIASECDJMCCyADQeEBNgIcIAMgATYCFCADQdAaNgIQIANBFTYCDEEAIQIMqwILIAEgBEYEQEHhASECDKsCCwJAIAEtAABBIEYEQCADQQA7ATQgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GZETYCECADQQk2AgxBACECDKsCC0HHASECDJECCyABIARGBEBB4AEhAgyqAgsCQCABLQAAQTBrQf8BcSICQQpJBEAgAUEBaiEBAkAgAy8BNCIAQZkzSw0AIAMgAEEKbCIAOwE0IABB/v8DcSACQf//A3NLDQAgAyAAIAJqOwE0DAILQQAhAiADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMDKsCCyADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMQQAhAgyqAgtBxgEhAgyQAgsgASAERgRAQd8BIQIMqQILAkAgAS0AAEEwa0H/AXEiAkEKSQRAIAFBAWohAQJAIAMvATQiAEGZM0sNACADIABBCmwiADsBNCAAQf7/A3EgAkH//wNzSw0AIAMgACACajsBNAwCC0EAIQIgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDAyqAgsgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDEEAIQIMqQILQcUBIQIMjwILIAEgBEYEQEHeASECDKgCCwJAIAEtAABBMGtB/wFxIgJBCkkEQCABQQFqIQECQCADLwE0IgBBmTNLDQAgAyAAQQpsIgA7ATQgAEH+/wNxIAJB//8Dc0sNACADIAAgAmo7ATQMAgtBACECIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgwMqQILIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgxBACECDKgCC0HEASECDI4CCyABIARGBEBB3QEhAgynAgsCQAJAAkACQCABLQAAQQprDhcCAwMAAwMDAwMDAwMDAwMDAwMDAwMDAQMLIAFBAWoMBQsgAUEBaiEBQcMBIQIMjwILIAFBAWohASADQS9qLQAAQQFxDQggA0EANgIcIAMgATYCFCADQY0LNgIQIANBDTYCDEEAIQIMpwILIANBADYCHCADIAE2AhQgA0GNCzYCECADQQ02AgxBACECDKYCCyABIARHBEAgA0EPNgIIIAMgATYCBEEBIQIMjQILQdwBIQIMpQILAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0HbASECDKYCCyADKAIEIQAgA0EANgIEIAMgACABEC0iAEUEQCABQQFqIQEMBAsgA0HaATYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgylAgsgAygCBCEAIANBADYCBCADIAAgARAtIgANASABQQFqCyEBQcEBIQIMigILIANB2QE2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMogILQcIBIQIMiAILIANBL2otAABBAXENASADQQA2AhwgAyABNgIUIANB5Bw2AhAgA0EZNgIMQQAhAgygAgsgASAERgRAQdkBIQIMoAILAkACQAJAIAEtAABBCmsOBAECAgACCyABQQFqIQEMAgsgAUEBaiEBDAELIAMtAC5BwABxRQ0BC0EAIQACQCADKAI4IgJFDQAgAigCPCICRQ0AIAMgAhEAACEACyAARQ2gASAAQRVGBEAgA0HZADYCHCADIAE2AhQgA0G3GjYCECADQRU2AgxBACECDJ8CCyADQQA2AhwgAyABNgIUIANBgA02AhAgA0EbNgIMQQAhAgyeAgsgA0EANgIcIAMgATYCFCADQdwoNgIQIANBAjYCDEEAIQIMnQILIAEgBEcEQCADQQw2AgggAyABNgIEQb8BIQIMhAILQdgBIQIMnAILIAEgBEYEQEHXASECDJwCCwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAS0AAEHBAGsOFQABAgNaBAUGWlpaBwgJCgsMDQ4PEFoLIAFBAWohAUH7ACECDJICCyABQQFqIQFB/AAhAgyRAgsgAUEBaiEBQYEBIQIMkAILIAFBAWohAUGFASECDI8CCyABQQFqIQFBhgEhAgyOAgsgAUEBaiEBQYkBIQIMjQILIAFBAWohAUGKASECDIwCCyABQQFqIQFBjQEhAgyLAgsgAUEBaiEBQZYBIQIMigILIAFBAWohAUGXASECDIkCCyABQQFqIQFBmAEhAgyIAgsgAUEBaiEBQaUBIQIMhwILIAFBAWohAUGmASECDIYCCyABQQFqIQFBrAEhAgyFAgsgAUEBaiEBQbQBIQIMhAILIAFBAWohAUG3ASECDIMCCyABQQFqIQFBvgEhAgyCAgsgASAERgRAQdYBIQIMmwILIAEtAABBzgBHDUggAUEBaiEBQb0BIQIMgQILIAEgBEYEQEHVASECDJoCCwJAAkACQCABLQAAQcIAaw4SAEpKSkpKSkpKSgFKSkpKSkoCSgsgAUEBaiEBQbgBIQIMggILIAFBAWohAUG7ASECDIECCyABQQFqIQFBvAEhAgyAAgtB1AEhAiABIARGDZgCIAMoAgAiACAEIAFraiEFIAEgAGtBB2ohBgJAA0AgAS0AACAAQajVAGotAABHDUUgAEEHRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJkCCyADQQA2AgAgBkEBaiEBQRsMRQsgASAERgRAQdMBIQIMmAILAkACQCABLQAAQckAaw4HAEdHR0dHAUcLIAFBAWohAUG5ASECDP8BCyABQQFqIQFBugEhAgz+AQtB0gEhAiABIARGDZYCIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQabVAGotAABHDUMgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJcCCyADQQA2AgAgBkEBaiEBQQ8MQwtB0QEhAiABIARGDZUCIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQaTVAGotAABHDUIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJYCCyADQQA2AgAgBkEBaiEBQSAMQgtB0AEhAiABIARGDZQCIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQaHVAGotAABHDUEgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJUCCyADQQA2AgAgBkEBaiEBQRIMQQsgASAERgRAQc8BIQIMlAILAkACQCABLQAAQcUAaw4OAENDQ0NDQ0NDQ0NDQwFDCyABQQFqIQFBtQEhAgz7AQsgAUEBaiEBQbYBIQIM+gELQc4BIQIgASAERg2SAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGe1QBqLQAARw0/IABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyTAgsgA0EANgIAIAZBAWohAUEHDD8LQc0BIQIgASAERg2RAiADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGY1QBqLQAARw0+IABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAySAgsgA0EANgIAIAZBAWohAUEoDD4LIAEgBEYEQEHMASECDJECCwJAAkACQCABLQAAQcUAaw4RAEFBQUFBQUFBQQFBQUFBQQJBCyABQQFqIQFBsQEhAgz5AQsgAUEBaiEBQbIBIQIM+AELIAFBAWohAUGzASECDPcBC0HLASECIAEgBEYNjwIgAygCACIAIAQgAWtqIQUgASAAa0EGaiEGAkADQCABLQAAIABBkdUAai0AAEcNPCAAQQZGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMkAILIANBADYCACAGQQFqIQFBGgw8C0HKASECIAEgBEYNjgIgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBjdUAai0AAEcNOyAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMjwILIANBADYCACAGQQFqIQFBIQw7CyABIARGBEBByQEhAgyOAgsCQAJAIAEtAABBwQBrDhQAPT09PT09PT09PT09PT09PT09AT0LIAFBAWohAUGtASECDPUBCyABQQFqIQFBsAEhAgz0AQsgASAERgRAQcgBIQIMjQILAkACQCABLQAAQdUAaw4LADw8PDw8PDw8PAE8CyABQQFqIQFBrgEhAgz0AQsgAUEBaiEBQa8BIQIM8wELQccBIQIgASAERg2LAiADKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEGE1QBqLQAARw04IABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyMAgsgA0EANgIAIAZBAWohAUEqDDgLIAEgBEYEQEHGASECDIsCCyABLQAAQdAARw04IAFBAWohAUElDDcLQcUBIQIgASAERg2JAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGB1QBqLQAARw02IABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyKAgsgA0EANgIAIAZBAWohAUEODDYLIAEgBEYEQEHEASECDIkCCyABLQAAQcUARw02IAFBAWohAUGrASECDO8BCyABIARGBEBBwwEhAgyIAgsCQAJAAkACQCABLQAAQcIAaw4PAAECOTk5OTk5OTk5OTkDOQsgAUEBaiEBQacBIQIM8QELIAFBAWohAUGoASECDPABCyABQQFqIQFBqQEhAgzvAQsgAUEBaiEBQaoBIQIM7gELQcIBIQIgASAERg2GAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEH+1ABqLQAARw0zIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyHAgsgA0EANgIAIAZBAWohAUEUDDMLQcEBIQIgASAERg2FAiADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEH51ABqLQAARw0yIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyGAgsgA0EANgIAIAZBAWohAUErDDILQcABIQIgASAERg2EAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEH21ABqLQAARw0xIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyFAgsgA0EANgIAIAZBAWohAUEsDDELQb8BIQIgASAERg2DAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGh1QBqLQAARw0wIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyEAgsgA0EANgIAIAZBAWohAUERDDALQb4BIQIgASAERg2CAiADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEHy1ABqLQAARw0vIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyDAgsgA0EANgIAIAZBAWohAUEuDC8LIAEgBEYEQEG9ASECDIICCwJAAkACQAJAAkAgAS0AAEHBAGsOFQA0NDQ0NDQ0NDQ0ATQ0AjQ0AzQ0BDQLIAFBAWohAUGbASECDOwBCyABQQFqIQFBnAEhAgzrAQsgAUEBaiEBQZ0BIQIM6gELIAFBAWohAUGiASECDOkBCyABQQFqIQFBpAEhAgzoAQsgASAERgRAQbwBIQIMgQILAkACQCABLQAAQdIAaw4DADABMAsgAUEBaiEBQaMBIQIM6AELIAFBAWohAUEEDC0LQbsBIQIgASAERg3/ASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHw1ABqLQAARw0sIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyAAgsgA0EANgIAIAZBAWohAUEdDCwLIAEgBEYEQEG6ASECDP8BCwJAAkAgAS0AAEHJAGsOBwEuLi4uLgAuCyABQQFqIQFBoQEhAgzmAQsgAUEBaiEBQSIMKwsgASAERgRAQbkBIQIM/gELIAEtAABB0ABHDSsgAUEBaiEBQaABIQIM5AELIAEgBEYEQEG4ASECDP0BCwJAAkAgAS0AAEHGAGsOCwAsLCwsLCwsLCwBLAsgAUEBaiEBQZ4BIQIM5AELIAFBAWohAUGfASECDOMBC0G3ASECIAEgBEYN+wEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABB7NQAai0AAEcNKCAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM/AELIANBADYCACAGQQFqIQFBDQwoC0G2ASECIAEgBEYN+gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBodUAai0AAEcNJyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+wELIANBADYCACAGQQFqIQFBDAwnC0G1ASECIAEgBEYN+QEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB6tQAai0AAEcNJiAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+gELIANBADYCACAGQQFqIQFBAwwmC0G0ASECIAEgBEYN+AEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB6NQAai0AAEcNJSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+QELIANBADYCACAGQQFqIQFBJgwlCyABIARGBEBBswEhAgz4AQsCQAJAIAEtAABB1ABrDgIAAScLIAFBAWohAUGZASECDN8BCyABQQFqIQFBmgEhAgzeAQtBsgEhAiABIARGDfYBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQebUAGotAABHDSMgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPcBCyADQQA2AgAgBkEBaiEBQScMIwtBsQEhAiABIARGDfUBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQeTUAGotAABHDSIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPYBCyADQQA2AgAgBkEBaiEBQRwMIgtBsAEhAiABIARGDfQBIAMoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQd7UAGotAABHDSEgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPUBCyADQQA2AgAgBkEBaiEBQQYMIQtBrwEhAiABIARGDfMBIAMoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQdnUAGotAABHDSAgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPQBCyADQQA2AgAgBkEBaiEBQRkMIAsgASAERgRAQa4BIQIM8wELAkACQAJAAkAgAS0AAEEtaw4jACQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkASQkJCQkAiQkJAMkCyABQQFqIQFBjgEhAgzcAQsgAUEBaiEBQY8BIQIM2wELIAFBAWohAUGUASECDNoBCyABQQFqIQFBlQEhAgzZAQtBrQEhAiABIARGDfEBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQdfUAGotAABHDR4gAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPIBCyADQQA2AgAgBkEBaiEBQQsMHgsgASAERgRAQawBIQIM8QELAkACQCABLQAAQcEAaw4DACABIAsgAUEBaiEBQZABIQIM2AELIAFBAWohAUGTASECDNcBCyABIARGBEBBqwEhAgzwAQsCQAJAIAEtAABBwQBrDg8AHx8fHx8fHx8fHx8fHwEfCyABQQFqIQFBkQEhAgzXAQsgAUEBaiEBQZIBIQIM1gELIAEgBEYEQEGqASECDO8BCyABLQAAQcwARw0cIAFBAWohAUEKDBsLQakBIQIgASAERg3tASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHR1ABqLQAARw0aIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzuAQsgA0EANgIAIAZBAWohAUEeDBoLQagBIQIgASAERg3sASADKAIAIgAgBCABa2ohBSABIABrQQZqIQYCQANAIAEtAAAgAEHK1ABqLQAARw0ZIABBBkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAztAQsgA0EANgIAIAZBAWohAUEVDBkLQacBIQIgASAERg3rASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHH1ABqLQAARw0YIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzsAQsgA0EANgIAIAZBAWohAUEXDBgLQaYBIQIgASAERg3qASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHB1ABqLQAARw0XIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzrAQsgA0EANgIAIAZBAWohAUEYDBcLIAEgBEYEQEGlASECDOoBCwJAAkAgAS0AAEHJAGsOBwAZGRkZGQEZCyABQQFqIQFBiwEhAgzRAQsgAUEBaiEBQYwBIQIM0AELQaQBIQIgASAERg3oASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGm1QBqLQAARw0VIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzpAQsgA0EANgIAIAZBAWohAUEJDBULQaMBIQIgASAERg3nASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGk1QBqLQAARw0UIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzoAQsgA0EANgIAIAZBAWohAUEfDBQLQaIBIQIgASAERg3mASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEG+1ABqLQAARw0TIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAznAQsgA0EANgIAIAZBAWohAUECDBMLQaEBIQIgASAERg3lASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYDQCABLQAAIABBvNQAai0AAEcNESAAQQFGDQIgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM5QELIAEgBEYEQEGgASECDOUBC0EBIAEtAABB3wBHDREaIAFBAWohAUGHASECDMsBCyADQQA2AgAgBkEBaiEBQYgBIQIMygELQZ8BIQIgASAERg3iASADKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEGE1QBqLQAARw0PIABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzjAQsgA0EANgIAIAZBAWohAUEpDA8LQZ4BIQIgASAERg3hASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEG41ABqLQAARw0OIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAziAQsgA0EANgIAIAZBAWohAUEtDA4LIAEgBEYEQEGdASECDOEBCyABLQAAQcUARw0OIAFBAWohAUGEASECDMcBCyABIARGBEBBnAEhAgzgAQsCQAJAIAEtAABBzABrDggADw8PDw8PAQ8LIAFBAWohAUGCASECDMcBCyABQQFqIQFBgwEhAgzGAQtBmwEhAiABIARGDd4BIAMoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQbPUAGotAABHDQsgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADN8BCyADQQA2AgAgBkEBaiEBQSMMCwtBmgEhAiABIARGDd0BIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbDUAGotAABHDQogAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADN4BCyADQQA2AgAgBkEBaiEBQQAMCgsgASAERgRAQZkBIQIM3QELAkACQCABLQAAQcgAaw4IAAwMDAwMDAEMCyABQQFqIQFB/QAhAgzEAQsgAUEBaiEBQYABIQIMwwELIAEgBEYEQEGYASECDNwBCwJAAkAgAS0AAEHOAGsOAwALAQsLIAFBAWohAUH+ACECDMMBCyABQQFqIQFB/wAhAgzCAQsgASAERgRAQZcBIQIM2wELIAEtAABB2QBHDQggAUEBaiEBQQgMBwtBlgEhAiABIARGDdkBIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQazUAGotAABHDQYgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNoBCyADQQA2AgAgBkEBaiEBQQUMBgtBlQEhAiABIARGDdgBIAMoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQabUAGotAABHDQUgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNkBCyADQQA2AgAgBkEBaiEBQRYMBQtBlAEhAiABIARGDdcBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQaHVAGotAABHDQQgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNgBCyADQQA2AgAgBkEBaiEBQRAMBAsgASAERgRAQZMBIQIM1wELAkACQCABLQAAQcMAaw4MAAYGBgYGBgYGBgYBBgsgAUEBaiEBQfkAIQIMvgELIAFBAWohAUH6ACECDL0BC0GSASECIAEgBEYN1QEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBoNQAai0AAEcNAiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM1gELIANBADYCACAGQQFqIQFBJAwCCyADQQA2AgAMAgsgASAERgRAQZEBIQIM1AELIAEtAABBzABHDQEgAUEBaiEBQRMLOgApIAMoAgQhACADQQA2AgQgAyAAIAEQLiIADQIMAQtBACECIANBADYCHCADIAE2AhQgA0H+HzYCECADQQY2AgwM0QELQfgAIQIMtwELIANBkAE2AhwgAyABNgIUIAMgADYCDEEAIQIMzwELQQAhAAJAIAMoAjgiAkUNACACKAJAIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRg0BIANBADYCHCADIAE2AhQgA0GCDzYCECADQSA2AgxBACECDM4BC0H3ACECDLQBCyADQY8BNgIcIAMgATYCFCADQewbNgIQIANBFTYCDEEAIQIMzAELIAEgBEYEQEGPASECDMwBCwJAIAEtAABBIEYEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQZsfNgIQIANBBjYCDEEAIQIMzAELQQIhAgyyAQsDQCABLQAAQSBHDQIgBCABQQFqIgFHDQALQY4BIQIMygELIAEgBEYEQEGNASECDMoBCwJAIAEtAABBCWsOBEoAAEoAC0H1ACECDLABCyADLQApQQVGBEBB9gAhAgywAQtB9AAhAgyvAQsgASAERgRAQYwBIQIMyAELIANBEDYCCCADIAE2AgQMCgsgASAERgRAQYsBIQIMxwELAkAgAS0AAEEJaw4ERwAARwALQfMAIQIMrQELIAEgBEcEQCADQRA2AgggAyABNgIEQfEAIQIMrQELQYoBIQIMxQELAkAgASAERwRAA0AgAS0AAEGg0ABqLQAAIgBBA0cEQAJAIABBAWsOAkkABAtB8AAhAgyvAQsgBCABQQFqIgFHDQALQYgBIQIMxgELQYgBIQIMxQELIANBADYCHCADIAE2AhQgA0HbIDYCECADQQc2AgxBACECDMQBCyABIARGBEBBiQEhAgzEAQsCQAJAAkAgAS0AAEGg0gBqLQAAQQFrDgNGAgABC0HyACECDKwBCyADQQA2AhwgAyABNgIUIANBtBI2AhAgA0EHNgIMQQAhAgzEAQtB6gAhAgyqAQsgASAERwRAIAFBAWohAUHvACECDKoBC0GHASECDMIBCyAEIAEiAEYEQEGGASECDMIBCyAALQAAIgFBL0YEQCAAQQFqIQFB7gAhAgypAQsgAUEJayICQRdLDQEgACEBQQEgAnRBm4CABHENQQwBCyAEIAEiAEYEQEGFASECDMEBCyAALQAAQS9HDQAgAEEBaiEBDAMLQQAhAiADQQA2AhwgAyAANgIUIANB2yA2AhAgA0EHNgIMDL8BCwJAAkACQAJAAkADQCABLQAAQaDOAGotAAAiAEEFRwRAAkACQCAAQQFrDghHBQYHCAAEAQgLQesAIQIMrQELIAFBAWohAUHtACECDKwBCyAEIAFBAWoiAUcNAAtBhAEhAgzDAQsgAUEBagwUCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQdsANgIcIAMgATYCFCADIAA2AgxBACECDMEBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDMABCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQfoANgIcIAMgATYCFCADIAA2AgxBACECDL8BCyADQQA2AhwgAyABNgIUIANB+Q82AhAgA0EHNgIMQQAhAgy+AQsgASAERgRAQYMBIQIMvgELAkAgAS0AAEGgzgBqLQAAQQFrDgg+BAUGAAgCAwcLIAFBAWohAQtBAyECDKMBCyABQQFqDA0LQQAhAiADQQA2AhwgA0HREjYCECADQQc2AgwgAyABQQFqNgIUDLoBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQdsANgIcIAMgATYCFCADIAA2AgxBACECDLkBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDLgBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQfoANgIcIAMgATYCFCADIAA2AgxBACECDLcBCyADQQA2AhwgAyABNgIUIANB+Q82AhAgA0EHNgIMQQAhAgy2AQtB7AAhAgycAQsgASAERgRAQYIBIQIMtQELIAFBAWoMAgsgASAERgRAQYEBIQIMtAELIAFBAWoMAQsgASAERg0BIAFBAWoLIQFBBCECDJgBC0GAASECDLABCwNAIAEtAABBoMwAai0AACIAQQJHBEAgAEEBRwRAQekAIQIMmQELDDELIAQgAUEBaiIBRw0AC0H/ACECDK8BCyABIARGBEBB/gAhAgyvAQsCQCABLQAAQQlrDjcvAwYvBAYGBgYGBgYGBgYGBgYGBgYGBgUGBgIGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYABgsgAUEBagshAUEFIQIMlAELIAFBAWoMBgsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgyrAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyqAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0H6ADYCHCADIAE2AhQgAyAANgIMQQAhAgypAQsgA0EANgIcIAMgATYCFCADQY0UNgIQIANBBzYCDEEAIQIMqAELAkACQAJAAkADQCABLQAAQaDKAGotAAAiAEEFRwRAAkAgAEEBaw4GLgMEBQYABgtB6AAhAgyUAQsgBCABQQFqIgFHDQALQf0AIQIMqwELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMqgELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMqQELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB+gA2AhwgAyABNgIUIAMgADYCDEEAIQIMqAELIANBADYCHCADIAE2AhQgA0HkCDYCECADQQc2AgxBACECDKcBCyABIARGDQEgAUEBagshAUEGIQIMjAELQfwAIQIMpAELAkACQAJAAkADQCABLQAAQaDIAGotAAAiAEEFRwRAIABBAWsOBCkCAwQFCyAEIAFBAWoiAUcNAAtB+wAhAgynAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgymAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgylAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0H6ADYCHCADIAE2AhQgAyAANgIMQQAhAgykAQsgA0EANgIcIAMgATYCFCADQbwKNgIQIANBBzYCDEEAIQIMowELQc8AIQIMiQELQdEAIQIMiAELQecAIQIMhwELIAEgBEYEQEH6ACECDKABCwJAIAEtAABBCWsOBCAAACAACyABQQFqIQFB5gAhAgyGAQsgASAERgRAQfkAIQIMnwELAkAgAS0AAEEJaw4EHwAAHwALQQAhAAJAIAMoAjgiAkUNACACKAI4IgJFDQAgAyACEQAAIQALIABFBEBB4gEhAgyGAQsgAEEVRwRAIANBADYCHCADIAE2AhQgA0HJDTYCECADQRo2AgxBACECDJ8BCyADQfgANgIcIAMgATYCFCADQeoaNgIQIANBFTYCDEEAIQIMngELIAEgBEcEQCADQQ02AgggAyABNgIEQeQAIQIMhQELQfcAIQIMnQELIAEgBEYEQEH2ACECDJ0BCwJAAkACQCABLQAAQcgAaw4LAAELCwsLCwsLCwILCyABQQFqIQFB3QAhAgyFAQsgAUEBaiEBQeAAIQIMhAELIAFBAWohAUHjACECDIMBC0H1ACECIAEgBEYNmwEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBtdUAai0AAEcNCCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMnAELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgAEQCADQfQANgIcIAMgATYCFCADIAA2AgxBACECDJwBC0HiACECDIIBC0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMnAELQeEAIQIMggELIANB8wA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyaAQsgAy0AKSIAQSNrQQtJDQkCQCAAQQZLDQBBASAAdEHKAHFFDQAMCgtBACECIANBADYCHCADIAE2AhQgA0HtCTYCECADQQg2AgwMmQELQfIAIQIgASAERg2YASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGz1QBqLQAARw0FIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyZAQsgAygCBCEAIANCADcDACADIAAgBkEBaiIBECsiAARAIANB8QA2AhwgAyABNgIUIAMgADYCDEEAIQIMmQELQd8AIQIMfwtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJkBC0HeACECDH8LIANB8AA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyXAQsgAy0AKUEhRg0GIANBADYCHCADIAE2AhQgA0GRCjYCECADQQg2AgxBACECDJYBC0HvACECIAEgBEYNlQEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBsNUAai0AAEcNAiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMlgELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgBFDQIgA0HtADYCHCADIAE2AhQgAyAANgIMQQAhAgyVAQsgA0EANgIACyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNgAEgA0HuADYCHCADIAE2AhQgAyAANgIMQQAhAgyTAQtB3AAhAgx5C0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMkwELQdsAIQIMeQsgA0HsADYCHCADIAE2AhQgA0GAGzYCECADQRU2AgxBACECDJEBCyADLQApIgBBI0kNACAAQS5GDQAgA0EANgIcIAMgATYCFCADQckJNgIQIANBCDYCDEEAIQIMkAELQdoAIQIMdgsgASAERgRAQesAIQIMjwELAkAgAS0AAEEvRgRAIAFBAWohAQwBCyADQQA2AhwgAyABNgIUIANBsjg2AhAgA0EINgIMQQAhAgyPAQtB2QAhAgx1CyABIARHBEAgA0EONgIIIAMgATYCBEHYACECDHULQeoAIQIMjQELIAEgBEYEQEHpACECDI0BCyABLQAAQTBrIgBB/wFxQQpJBEAgAyAAOgAqIAFBAWohAUHXACECDHQLIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ16IANB6AA2AhwgAyABNgIUIAMgADYCDEEAIQIMjAELIAEgBEYEQEHnACECDIwBCwJAIAEtAABBLkYEQCABQQFqIQEMAQsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDXsgA0HmADYCHCADIAE2AhQgAyAANgIMQQAhAgyMAQtB1gAhAgxyCyABIARGBEBB5QAhAgyLAQtBACEAQQEhBUEBIQdBACECAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkAgAS0AAEEwaw4KCgkAAQIDBAUGCAsLQQIMBgtBAwwFC0EEDAQLQQUMAwtBBgwCC0EHDAELQQgLIQJBACEFQQAhBwwCC0EJIQJBASEAQQAhBUEAIQcMAQtBACEFQQEhAgsgAyACOgArIAFBAWohAQJAAkAgAy0ALkEQcQ0AAkACQAJAIAMtACoOAwEAAgQLIAdFDQMMAgsgAA0BDAILIAVFDQELIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ0CIANB4gA2AhwgAyABNgIUIAMgADYCDEEAIQIMjQELIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ19IANB4wA2AhwgAyABNgIUIAMgADYCDEEAIQIMjAELIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ17IANB5AA2AhwgAyABNgIUIAMgADYCDAyLAQtB1AAhAgxxCyADLQApQSJGDYYBQdMAIQIMcAtBACEAAkAgAygCOCICRQ0AIAIoAkQiAkUNACADIAIRAAAhAAsgAEUEQEHVACECDHALIABBFUcEQCADQQA2AhwgAyABNgIUIANBpA02AhAgA0EhNgIMQQAhAgyJAQsgA0HhADYCHCADIAE2AhQgA0HQGjYCECADQRU2AgxBACECDIgBCyABIARGBEBB4AAhAgyIAQsCQAJAAkACQAJAIAEtAABBCmsOBAEEBAAECyABQQFqIQEMAQsgAUEBaiEBIANBL2otAABBAXFFDQELQdIAIQIMcAsgA0EANgIcIAMgATYCFCADQbYRNgIQIANBCTYCDEEAIQIMiAELIANBADYCHCADIAE2AhQgA0G2ETYCECADQQk2AgxBACECDIcBCyABIARGBEBB3wAhAgyHAQsgAS0AAEEKRgRAIAFBAWohAQwJCyADLQAuQcAAcQ0IIANBADYCHCADIAE2AhQgA0G2ETYCECADQQI2AgxBACECDIYBCyABIARGBEBB3QAhAgyGAQsgAS0AACICQQ1GBEAgAUEBaiEBQdAAIQIMbQsgASEAIAJBCWsOBAUBAQUBCyAEIAEiAEYEQEHcACECDIUBCyAALQAAQQpHDQAgAEEBagwCC0EAIQIgA0EANgIcIAMgADYCFCADQcotNgIQIANBBzYCDAyDAQsgASAERgRAQdsAIQIMgwELAkAgAS0AAEEJaw4EAwAAAwALIAFBAWoLIQFBzgAhAgxoCyABIARGBEBB2gAhAgyBAQsgAS0AAEEJaw4EAAEBAAELQQAhAiADQQA2AhwgA0GaEjYCECADQQc2AgwgAyABQQFqNgIUDH8LIANBgBI7ASpBACEAAkAgAygCOCICRQ0AIAIoAjgiAkUNACADIAIRAAAhAAsgAEUNACAAQRVHDQEgA0HZADYCHCADIAE2AhQgA0HqGjYCECADQRU2AgxBACECDH4LQc0AIQIMZAsgA0EANgIcIAMgATYCFCADQckNNgIQIANBGjYCDEEAIQIMfAsgASAERgRAQdkAIQIMfAsgAS0AAEEgRw09IAFBAWohASADLQAuQQFxDT0gA0EANgIcIAMgATYCFCADQcIcNgIQIANBHjYCDEEAIQIMewsgASAERgRAQdgAIQIMewsCQAJAAkACQAJAIAEtAAAiAEEKaw4EAgMDAAELIAFBAWohAUEsIQIMZQsgAEE6Rw0BIANBADYCHCADIAE2AhQgA0HnETYCECADQQo2AgxBACECDH0LIAFBAWohASADQS9qLQAAQQFxRQ1zIAMtADJBgAFxRQRAIANBMmohAiADEDVBACEAAkAgAygCOCIGRQ0AIAYoAigiBkUNACADIAYRAAAhAAsCQAJAIAAOFk1MSwEBAQEBAQEBAQEBAQEBAQEBAQABCyADQSk2AhwgAyABNgIUIANBrBk2AhAgA0EVNgIMQQAhAgx+CyADQQA2AhwgAyABNgIUIANB5Qs2AhAgA0ERNgIMQQAhAgx9C0EAIQACQCADKAI4IgJFDQAgAigCXCICRQ0AIAMgAhEAACEACyAARQ1ZIABBFUcNASADQQU2AhwgAyABNgIUIANBmxs2AhAgA0EVNgIMQQAhAgx8C0HLACECDGILQQAhAiADQQA2AhwgAyABNgIUIANBkA42AhAgA0EUNgIMDHoLIAMgAy8BMkGAAXI7ATIMOwsgASAERwRAIANBETYCCCADIAE2AgRBygAhAgxgC0HXACECDHgLIAEgBEYEQEHWACECDHgLAkACQAJAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXFB4wBrDhMAQEBAQEBAQEBAQEBAAUBAQAIDQAsgAUEBaiEBQcYAIQIMYQsgAUEBaiEBQccAIQIMYAsgAUEBaiEBQcgAIQIMXwsgAUEBaiEBQckAIQIMXgtB1QAhAiAEIAEiAEYNdiAEIAFrIAMoAgAiAWohBiAAIAFrQQVqIQcDQCABQZDIAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQhBBCABQQVGDQoaIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADHYLQdQAIQIgBCABIgBGDXUgBCABayADKAIAIgFqIQYgACABa0EPaiEHA0AgAUGAyABqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0HQQMgAUEPRg0JGiABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAx1C0HTACECIAQgASIARg10IAQgAWsgAygCACIBaiEGIAAgAWtBDmohBwNAIAFB4scAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNBiABQQ5GDQcgAUEBaiEBIAQgAEEBaiIARw0ACyADIAY2AgAMdAtB0gAhAiAEIAEiAEYNcyAEIAFrIAMoAgAiAWohBSAAIAFrQQFqIQYDQCABQeDHAGotAAAgAC0AACIHQSByIAcgB0HBAGtB/wFxQRpJG0H/AXFHDQUgAUEBRg0CIAFBAWohASAEIABBAWoiAEcNAAsgAyAFNgIADHMLIAEgBEYEQEHRACECDHMLAkACQCABLQAAIgBBIHIgACAAQcEAa0H/AXFBGkkbQf8BcUHuAGsOBwA5OTk5OQE5CyABQQFqIQFBwwAhAgxaCyABQQFqIQFBxAAhAgxZCyADQQA2AgAgBkEBaiEBQcUAIQIMWAtB0AAhAiAEIAEiAEYNcCAEIAFrIAMoAgAiAWohBiAAIAFrQQlqIQcDQCABQdbHAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQJBAiABQQlGDQQaIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADHALQc8AIQIgBCABIgBGDW8gBCABayADKAIAIgFqIQYgACABa0EFaiEHA0AgAUHQxwBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBBUYNAiABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxvCyAAIQEgA0EANgIADDMLQQELOgAsIANBADYCACAHQQFqIQELQS0hAgxSCwJAA0AgAS0AAEHQxQBqLQAAQQFHDQEgBCABQQFqIgFHDQALQc0AIQIMawtBwgAhAgxRCyABIARGBEBBzAAhAgxqCyABLQAAQTpGBEAgAygCBCEAIANBADYCBCADIAAgARAwIgBFDTMgA0HLADYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgxqCyADQQA2AhwgAyABNgIUIANB5xE2AhAgA0EKNgIMQQAhAgxpCwJAAkAgAy0ALEECaw4CAAEnCyADQTNqLQAAQQJxRQ0mIAMtAC5BAnENJiADQQA2AhwgAyABNgIUIANBphQ2AhAgA0ELNgIMQQAhAgxpCyADLQAyQSBxRQ0lIAMtAC5BAnENJSADQQA2AhwgAyABNgIUIANBvRM2AhAgA0EPNgIMQQAhAgxoC0EAIQACQCADKAI4IgJFDQAgAigCSCICRQ0AIAMgAhEAACEACyAARQRAQcEAIQIMTwsgAEEVRwRAIANBADYCHCADIAE2AhQgA0GmDzYCECADQRw2AgxBACECDGgLIANBygA2AhwgAyABNgIUIANBhRw2AhAgA0EVNgIMQQAhAgxnCyABIARHBEAgASECA0AgBCACIgFrQRBOBEAgAUEQaiEC/Qz/////////////////////IAH9AAAAIg1BB/1sIA39DODg4ODg4ODg4ODg4ODg4OD9bv0MX19fX19fX19fX19fX19fX/0mIA39DAkJCQkJCQkJCQkJCQkJCQn9I/1Q/VL9ZEF/c2giAEEQRg0BIAAgAWohAQwYCyABIARGBEBBxAAhAgxpCyABLQAAQcDBAGotAABBAUcNFyAEIAFBAWoiAkcNAAtBxAAhAgxnC0HEACECDGYLIAEgBEcEQANAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXEiAEEJRg0AIABBIEYNAAJAAkACQAJAIABB4wBrDhMAAwMDAwMDAwEDAwMDAwMDAwMCAwsgAUEBaiEBQTYhAgxSCyABQQFqIQFBNyECDFELIAFBAWohAUE4IQIMUAsMFQsgBCABQQFqIgFHDQALQTwhAgxmC0E8IQIMZQsgASAERgRAQcgAIQIMZQsgA0ESNgIIIAMgATYCBAJAAkACQAJAAkAgAy0ALEEBaw4EFAABAgkLIAMtADJBIHENA0HgASECDE8LAkAgAy8BMiIAQQhxRQ0AIAMtAChBAUcNACADLQAuQQhxRQ0CCyADIABB9/sDcUGABHI7ATIMCwsgAyADLwEyQRByOwEyDAQLIANBADYCBCADIAEgARAxIgAEQCADQcEANgIcIAMgADYCDCADIAFBAWo2AhRBACECDGYLIAFBAWohAQxYCyADQQA2AhwgAyABNgIUIANB9BM2AhAgA0EENgIMQQAhAgxkC0HHACECIAEgBEYNYyADKAIAIgAgBCABa2ohBSABIABrQQZqIQYCQANAIABBwMUAai0AACABLQAAQSByRw0BIABBBkYNSiAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAxkCyADQQA2AgAMBQsCQCABIARHBEADQCABLQAAQcDDAGotAAAiAEEBRwRAIABBAkcNAyABQQFqIQEMBQsgBCABQQFqIgFHDQALQcUAIQIMZAtBxQAhAgxjCwsgA0EAOgAsDAELQQshAgxHC0E/IQIMRgsCQAJAA0AgAS0AACIAQSBHBEACQCAAQQprDgQDBQUDAAsgAEEsRg0DDAQLIAQgAUEBaiIBRw0AC0HGACECDGALIANBCDoALAwOCyADLQAoQQFHDQIgAy0ALkEIcQ0CIAMoAgQhACADQQA2AgQgAyAAIAEQMSIABEAgA0HCADYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgxfCyABQQFqIQEMUAtBOyECDEQLAkADQCABLQAAIgBBIEcgAEEJR3ENASAEIAFBAWoiAUcNAAtBwwAhAgxdCwtBPCECDEILAkACQCABIARHBEADQCABLQAAIgBBIEcEQCAAQQprDgQDBAQDBAsgBCABQQFqIgFHDQALQT8hAgxdC0E/IQIMXAsgAyADLwEyQSByOwEyDAoLIAMoAgQhACADQQA2AgQgAyAAIAEQMSIARQ1OIANBPjYCHCADIAE2AhQgAyAANgIMQQAhAgxaCwJAIAEgBEcEQANAIAEtAABBwMMAai0AACIAQQFHBEAgAEECRg0DDAwLIAQgAUEBaiIBRw0AC0E3IQIMWwtBNyECDFoLIAFBAWohAQwEC0E7IQIgBCABIgBGDVggBCABayADKAIAIgFqIQYgACABa0EFaiEHAkADQCABQZDIAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQEgAUEFRgRAQQchAQw/CyABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxZCyADQQA2AgAgACEBDAULQTohAiAEIAEiAEYNVyAEIAFrIAMoAgAiAWohBiAAIAFrQQhqIQcCQANAIAFBtMEAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNASABQQhGBEBBBSEBDD4LIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADFgLIANBADYCACAAIQEMBAtBOSECIAQgASIARg1WIAQgAWsgAygCACIBaiEGIAAgAWtBA2ohBwJAA0AgAUGwwQBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBA0YEQEEGIQEMPQsgAUEBaiEBIAQgAEEBaiIARw0ACyADIAY2AgAMVwsgA0EANgIAIAAhAQwDCwJAA0AgAS0AACIAQSBHBEAgAEEKaw4EBwQEBwILIAQgAUEBaiIBRw0AC0E4IQIMVgsgAEEsRw0BIAFBAWohAEEBIQECQAJAAkACQAJAIAMtACxBBWsOBAMBAgQACyAAIQEMBAtBAiEBDAELQQQhAQsgA0EBOgAsIAMgAy8BMiABcjsBMiAAIQEMAQsgAyADLwEyQQhyOwEyIAAhAQtBPiECDDsLIANBADoALAtBOSECDDkLIAEgBEYEQEE2IQIMUgsCQAJAAkACQAJAIAEtAABBCmsOBAACAgECCyADKAIEIQAgA0EANgIEIAMgACABEDEiAEUNAiADQTM2AhwgAyABNgIUIAMgADYCDEEAIQIMVQsgAygCBCEAIANBADYCBCADIAAgARAxIgBFBEAgAUEBaiEBDAYLIANBMjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgxUCyADLQAuQQFxBEBB3wEhAgw7CyADKAIEIQAgA0EANgIEIAMgACABEDEiAA0BDEkLQTQhAgw5CyADQTU2AhwgAyABNgIUIAMgADYCDEEAIQIMUQtBNSECDDcLIANBL2otAABBAXENACADQQA2AhwgAyABNgIUIANB6xY2AhAgA0EZNgIMQQAhAgxPC0EzIQIMNQsgASAERgRAQTIhAgxOCwJAIAEtAABBCkYEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQZIXNgIQIANBAzYCDEEAIQIMTgtBMiECDDQLIAEgBEYEQEExIQIMTQsCQCABLQAAIgBBCUYNACAAQSBGDQBBASECAkAgAy0ALEEFaw4EBgQFAA0LIAMgAy8BMkEIcjsBMgwMCyADLQAuQQFxRQ0BIAMtACxBCEcNACADQQA6ACwLQT0hAgwyCyADQQA2AhwgAyABNgIUIANBwhY2AhAgA0EKNgIMQQAhAgxKC0ECIQIMAQtBBCECCyADQQE6ACwgAyADLwEyIAJyOwEyDAYLIAEgBEYEQEEwIQIMRwsgAS0AAEEKRgRAIAFBAWohAQwBCyADLQAuQQFxDQAgA0EANgIcIAMgATYCFCADQdwoNgIQIANBAjYCDEEAIQIMRgtBMCECDCwLIAFBAWohAUExIQIMKwsgASAERgRAQS8hAgxECyABLQAAIgBBCUcgAEEgR3FFBEAgAUEBaiEBIAMtAC5BAXENASADQQA2AhwgAyABNgIUIANBlxA2AhAgA0EKNgIMQQAhAgxEC0EBIQICQAJAAkACQAJAAkAgAy0ALEECaw4HBQQEAwECAAQLIAMgAy8BMkEIcjsBMgwDC0ECIQIMAQtBBCECCyADQQE6ACwgAyADLwEyIAJyOwEyC0EvIQIMKwsgA0EANgIcIAMgATYCFCADQYQTNgIQIANBCzYCDEEAIQIMQwtB4QEhAgwpCyABIARGBEBBLiECDEILIANBADYCBCADQRI2AgggAyABIAEQMSIADQELQS4hAgwnCyADQS02AhwgAyABNgIUIAMgADYCDEEAIQIMPwtBACEAAkAgAygCOCICRQ0AIAIoAkwiAkUNACADIAIRAAAhAAsgAEUNACAAQRVHDQEgA0HYADYCHCADIAE2AhQgA0GzGzYCECADQRU2AgxBACECDD4LQcwAIQIMJAsgA0EANgIcIAMgATYCFCADQbMONgIQIANBHTYCDEEAIQIMPAsgASAERgRAQc4AIQIMPAsgAS0AACIAQSBGDQIgAEE6Rg0BCyADQQA6ACxBCSECDCELIAMoAgQhACADQQA2AgQgAyAAIAEQMCIADQEMAgsgAy0ALkEBcQRAQd4BIQIMIAsgAygCBCEAIANBADYCBCADIAAgARAwIgBFDQIgA0EqNgIcIAMgADYCDCADIAFBAWo2AhRBACECDDgLIANBywA2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMNwsgAUEBaiEBQcAAIQIMHQsgAUEBaiEBDCwLIAEgBEYEQEErIQIMNQsCQCABLQAAQQpGBEAgAUEBaiEBDAELIAMtAC5BwABxRQ0GCyADLQAyQYABcQRAQQAhAAJAIAMoAjgiAkUNACACKAJcIgJFDQAgAyACEQAAIQALIABFDRIgAEEVRgRAIANBBTYCHCADIAE2AhQgA0GbGzYCECADQRU2AgxBACECDDYLIANBADYCHCADIAE2AhQgA0GQDjYCECADQRQ2AgxBACECDDULIANBMmohAiADEDVBACEAAkAgAygCOCIGRQ0AIAYoAigiBkUNACADIAYRAAAhAAsgAA4WAgEABAQEBAQEBAQEBAQEBAQEBAQEAwQLIANBAToAMAsgAiACLwEAQcAAcjsBAAtBKyECDBgLIANBKTYCHCADIAE2AhQgA0GsGTYCECADQRU2AgxBACECDDALIANBADYCHCADIAE2AhQgA0HlCzYCECADQRE2AgxBACECDC8LIANBADYCHCADIAE2AhQgA0GlCzYCECADQQI2AgxBACECDC4LQQEhByADLwEyIgVBCHFFBEAgAykDIEIAUiEHCwJAIAMtADAEQEEBIQAgAy0AKUEFRg0BIAVBwABxRSAHcUUNAQsCQCADLQAoIgJBAkYEQEEBIQAgAy8BNCIGQeUARg0CQQAhACAFQcAAcQ0CIAZB5ABGDQIgBkHmAGtBAkkNAiAGQcwBRg0CIAZBsAJGDQIMAQtBACEAIAVBwABxDQELQQIhACAFQQhxDQAgBUGABHEEQAJAIAJBAUcNACADLQAuQQpxDQBBBSEADAILQQQhAAwBCyAFQSBxRQRAIAMQNkEAR0ECdCEADAELQQBBAyADKQMgUBshAAsgAEEBaw4FAgAHAQMEC0ERIQIMEwsgA0EBOgAxDCkLQQAhAgJAIAMoAjgiAEUNACAAKAIwIgBFDQAgAyAAEQAAIQILIAJFDSYgAkEVRgRAIANBAzYCHCADIAE2AhQgA0HSGzYCECADQRU2AgxBACECDCsLQQAhAiADQQA2AhwgAyABNgIUIANB3Q42AhAgA0ESNgIMDCoLIANBADYCHCADIAE2AhQgA0H5IDYCECADQQ82AgxBACECDCkLQQAhAAJAIAMoAjgiAkUNACACKAIwIgJFDQAgAyACEQAAIQALIAANAQtBDiECDA4LIABBFUYEQCADQQI2AhwgAyABNgIUIANB0hs2AhAgA0EVNgIMQQAhAgwnCyADQQA2AhwgAyABNgIUIANB3Q42AhAgA0ESNgIMQQAhAgwmC0EqIQIMDAsgASAERwRAIANBCTYCCCADIAE2AgRBKSECDAwLQSYhAgwkCyADIAMpAyAiDCAEIAFrrSIKfSILQgAgCyAMWBs3AyAgCiAMVARAQSUhAgwkCyADKAIEIQAgA0EANgIEIAMgACABIAynaiIBEDIiAEUNACADQQU2AhwgAyABNgIUIAMgADYCDEEAIQIMIwtBDyECDAkLQgAhCgJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCABLQAAQTBrDjcXFgABAgMEBQYHFBQUFBQUFAgJCgsMDRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUDg8QERITFAtCAiEKDBYLQgMhCgwVC0IEIQoMFAtCBSEKDBMLQgYhCgwSC0IHIQoMEQtCCCEKDBALQgkhCgwPC0IKIQoMDgtCCyEKDA0LQgwhCgwMC0INIQoMCwtCDiEKDAoLQg8hCgwJC0IKIQoMCAtCCyEKDAcLQgwhCgwGC0INIQoMBQtCDiEKDAQLQg8hCgwDCyADQQA2AhwgAyABNgIUIANBnxU2AhAgA0EMNgIMQQAhAgwhCyABIARGBEBBIiECDCELQgAhCgJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAS0AAEEwaw43FRQAAQIDBAUGBxYWFhYWFhYICQoLDA0WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFg4PEBESExYLQgIhCgwUC0IDIQoMEwtCBCEKDBILQgUhCgwRC0IGIQoMEAtCByEKDA8LQgghCgwOC0IJIQoMDQtCCiEKDAwLQgshCgwLC0IMIQoMCgtCDSEKDAkLQg4hCgwIC0IPIQoMBwtCCiEKDAYLQgshCgwFC0IMIQoMBAtCDSEKDAMLQg4hCgwCC0IPIQoMAQtCASEKCyABQQFqIQEgAykDICILQv//////////D1gEQCADIAtCBIYgCoQ3AyAMAgsgA0EANgIcIAMgATYCFCADQbUJNgIQIANBDDYCDEEAIQIMHgtBJyECDAQLQSghAgwDCyADIAE6ACwgA0EANgIAIAdBAWohAUEMIQIMAgsgA0EANgIAIAZBAWohAUEKIQIMAQsgAUEBaiEBQQghAgwACwALQQAhAiADQQA2AhwgAyABNgIUIANBsjg2AhAgA0EINgIMDBcLQQAhAiADQQA2AhwgAyABNgIUIANBgxE2AhAgA0EJNgIMDBYLQQAhAiADQQA2AhwgAyABNgIUIANB3wo2AhAgA0EJNgIMDBULQQAhAiADQQA2AhwgAyABNgIUIANB7RA2AhAgA0EJNgIMDBQLQQAhAiADQQA2AhwgAyABNgIUIANB0hE2AhAgA0EJNgIMDBMLQQAhAiADQQA2AhwgAyABNgIUIANBsjg2AhAgA0EINgIMDBILQQAhAiADQQA2AhwgAyABNgIUIANBgxE2AhAgA0EJNgIMDBELQQAhAiADQQA2AhwgAyABNgIUIANB3wo2AhAgA0EJNgIMDBALQQAhAiADQQA2AhwgAyABNgIUIANB7RA2AhAgA0EJNgIMDA8LQQAhAiADQQA2AhwgAyABNgIUIANB0hE2AhAgA0EJNgIMDA4LQQAhAiADQQA2AhwgAyABNgIUIANBuRc2AhAgA0EPNgIMDA0LQQAhAiADQQA2AhwgAyABNgIUIANBuRc2AhAgA0EPNgIMDAwLQQAhAiADQQA2AhwgAyABNgIUIANBmRM2AhAgA0ELNgIMDAsLQQAhAiADQQA2AhwgAyABNgIUIANBnQk2AhAgA0ELNgIMDAoLQQAhAiADQQA2AhwgAyABNgIUIANBlxA2AhAgA0EKNgIMDAkLQQAhAiADQQA2AhwgAyABNgIUIANBsRA2AhAgA0EKNgIMDAgLQQAhAiADQQA2AhwgAyABNgIUIANBux02AhAgA0ECNgIMDAcLQQAhAiADQQA2AhwgAyABNgIUIANBlhY2AhAgA0ECNgIMDAYLQQAhAiADQQA2AhwgAyABNgIUIANB+Rg2AhAgA0ECNgIMDAULQQAhAiADQQA2AhwgAyABNgIUIANBxBg2AhAgA0ECNgIMDAQLIANBAjYCHCADIAE2AhQgA0GpHjYCECADQRY2AgxBACECDAMLQd4AIQIgASAERg0CIAlBCGohByADKAIAIQUCQAJAIAEgBEcEQCAFQZbIAGohCCAEIAVqIAFrIQYgBUF/c0EKaiIFIAFqIQADQCABLQAAIAgtAABHBEBBAiEIDAMLIAVFBEBBACEIIAAhAQwDCyAFQQFrIQUgCEEBaiEIIAQgAUEBaiIBRw0ACyAGIQUgBCEBCyAHQQE2AgAgAyAFNgIADAELIANBADYCACAHIAg2AgALIAcgATYCBCAJKAIMIQACQAJAIAkoAghBAWsOAgQBAAsgA0EANgIcIANBwh42AhAgA0EXNgIMIAMgAEEBajYCFEEAIQIMAwsgA0EANgIcIAMgADYCFCADQdceNgIQIANBCTYCDEEAIQIMAgsgASAERgRAQSghAgwCCyADQQk2AgggAyABNgIEQSchAgwBCyABIARGBEBBASECDAELA0ACQAJAAkAgAS0AAEEKaw4EAAEBAAELIAFBAWohAQwBCyABQQFqIQEgAy0ALkEgcQ0AQQAhAiADQQA2AhwgAyABNgIUIANBoSE2AhAgA0EFNgIMDAILQQEhAiABIARHDQALCyAJQRBqJAAgAkUEQCADKAIMIQAMAQsgAyACNgIcQQAhACADKAIEIgFFDQAgAyABIAQgAygCCBEBACIBRQ0AIAMgBDYCFCADIAE2AgwgASEACyAAC74CAQJ/IABBADoAACAAQeQAaiIBQQFrQQA6AAAgAEEAOgACIABBADoAASABQQNrQQA6AAAgAUECa0EAOgAAIABBADoAAyABQQRrQQA6AABBACAAa0EDcSIBIABqIgBBADYCAEHkACABa0F8cSICIABqIgFBBGtBADYCAAJAIAJBCUkNACAAQQA2AgggAEEANgIEIAFBCGtBADYCACABQQxrQQA2AgAgAkEZSQ0AIABBADYCGCAAQQA2AhQgAEEANgIQIABBADYCDCABQRBrQQA2AgAgAUEUa0EANgIAIAFBGGtBADYCACABQRxrQQA2AgAgAiAAQQRxQRhyIgJrIgFBIEkNACAAIAJqIQADQCAAQgA3AxggAEIANwMQIABCADcDCCAAQgA3AwAgAEEgaiEAIAFBIGsiAUEfSw0ACwsLVgEBfwJAIAAoAgwNAAJAAkACQAJAIAAtADEOAwEAAwILIAAoAjgiAUUNACABKAIwIgFFDQAgACABEQAAIgENAwtBAA8LAAsgAEHKGTYCEEEOIQELIAELGgAgACgCDEUEQCAAQd4fNgIQIABBFTYCDAsLFAAgACgCDEEVRgRAIABBADYCDAsLFAAgACgCDEEWRgRAIABBADYCDAsLBwAgACgCDAsHACAAKAIQCwkAIAAgATYCEAsHACAAKAIUCysAAkAgAEEnTw0AQv//////CSAArYhCAYNQDQAgAEECdEHQOGooAgAPCwALFwAgAEEvTwRAAAsgAEECdEHsOWooAgALvwkBAX9B9C0hAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB5ABrDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0HqLA8LQZgmDwtB7TEPC0GgNw8LQckpDwtBtCkPC0GWLQ8LQesrDwtBojUPC0HbNA8LQeApDwtB4yQPC0HVJA8LQe4kDwtB5iUPC0HKNA8LQdA3DwtBqjUPC0H1LA8LQfYmDwtBgiIPC0HyMw8LQb4oDwtB5zcPC0HNIQ8LQcAhDwtBuCUPC0HLJQ8LQZYkDwtBjzQPC0HNNQ8LQd0qDwtB7jMPC0GcNA8LQZ4xDwtB9DUPC0HlIg8LQa8lDwtBmTEPC0GyNg8LQfk2DwtBxDIPC0HdLA8LQYIxDwtBwTEPC0GNNw8LQckkDwtB7DYPC0HnKg8LQcgjDwtB4iEPC0HJNw8LQaUiDwtBlCIPC0HbNg8LQd41DwtBhiYPC0G8Kw8LQYsyDwtBoCMPC0H2MA8LQYAsDwtBiSsPC0GkJg8LQfIjDwtBgSgPC0GrMg8LQesnDwtBwjYPC0GiJA8LQc8qDwtB3CMPC0GHJw8LQeQ0DwtBtyIPC0GtMQ8LQdUiDwtBrzQPC0HeJg8LQdYyDwtB9DQPC0GBOA8LQfQ3DwtBkjYPC0GdJw8LQYIpDwtBjSMPC0HXMQ8LQb01DwtBtDcPC0HYMA8LQbYnDwtBmjgPC0GnKg8LQcQnDwtBriMPC0H1Ig8LAAtByiYhAQsgAQsXACAAIAAvAS5B/v8DcSABQQBHcjsBLgsaACAAIAAvAS5B/f8DcSABQQBHQQF0cjsBLgsaACAAIAAvAS5B+/8DcSABQQBHQQJ0cjsBLgsaACAAIAAvAS5B9/8DcSABQQBHQQN0cjsBLgsaACAAIAAvAS5B7/8DcSABQQBHQQR0cjsBLgsaACAAIAAvAS5B3/8DcSABQQBHQQV0cjsBLgsaACAAIAAvAS5Bv/8DcSABQQBHQQZ0cjsBLgsaACAAIAAvAS5B//4DcSABQQBHQQd0cjsBLgsaACAAIAAvAS5B//0DcSABQQBHQQh0cjsBLgsaACAAIAAvAS5B//sDcSABQQBHQQl0cjsBLgs+AQJ/AkAgACgCOCIDRQ0AIAMoAgQiA0UNACAAIAEgAiABayADEQEAIgRBf0cNACAAQeESNgIQQRghBAsgBAs+AQJ/AkAgACgCOCIDRQ0AIAMoAggiA0UNACAAIAEgAiABayADEQEAIgRBf0cNACAAQfwRNgIQQRghBAsgBAs+AQJ/AkAgACgCOCIDRQ0AIAMoAgwiA0UNACAAIAEgAiABayADEQEAIgRBf0cNACAAQewKNgIQQRghBAsgBAs+AQJ/AkAgACgCOCIDRQ0AIAMoAhAiA0UNACAAIAEgAiABayADEQEAIgRBf0cNACAAQfoeNgIQQRghBAsgBAs+AQJ/AkAgACgCOCIDRQ0AIAMoAhQiA0UNACAAIAEgAiABayADEQEAIgRBf0cNACAAQcsQNgIQQRghBAsgBAs+AQJ/AkAgACgCOCIDRQ0AIAMoAhgiA0UNACAAIAEgAiABayADEQEAIgRBf0cNACAAQbcfNgIQQRghBAsgBAs+AQJ/AkAgACgCOCIDRQ0AIAMoAhwiA0UNACAAIAEgAiABayADEQEAIgRBf0cNACAAQb8VNgIQQRghBAsgBAs+AQJ/AkAgACgCOCIDRQ0AIAMoAiwiA0UNACAAIAEgAiABayADEQEAIgRBf0cNACAAQf4INgIQQRghBAsgBAs+AQJ/AkAgACgCOCIDRQ0AIAMoAiAiA0UNACAAIAEgAiABayADEQEAIgRBf0cNACAAQYwdNgIQQRghBAsgBAs+AQJ/AkAgACgCOCIDRQ0AIAMoAiQiA0UNACAAIAEgAiABayADEQEAIgRBf0cNACAAQeYVNgIQQRghBAsgBAs4ACAAAn8gAC8BMkEUcUEURgRAQQEgAC0AKEEBRg0BGiAALwE0QeUARgwBCyAALQApQQVGCzoAMAtZAQJ/AkAgAC0AKEEBRg0AIAAvATQiAUHkAGtB5ABJDQAgAUHMAUYNACABQbACRg0AIAAvATIiAEHAAHENAEEBIQIgAEGIBHFBgARGDQAgAEEocUUhAgsgAguMAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQAgAC8BMiIBQQJxRQ0BDAILIAAvATIiAUEBcUUNAQtBASECIAAtAChBAUYNACAALwE0IgBB5ABrQeQASQ0AIABBzAFGDQAgAEGwAkYNACABQcAAcQ0AQQAhAiABQYgEcUGABEYNACABQShxQQBHIQILIAILcwAgAEEQav0MAAAAAAAAAAAAAAAAAAAAAP0LAwAgAP0MAAAAAAAAAAAAAAAAAAAAAP0LAwAgAEEwav0MAAAAAAAAAAAAAAAAAAAAAP0LAwAgAEEgav0MAAAAAAAAAAAAAAAAAAAAAP0LAwAgAEH9ATYCHAsGACAAEDoLmi0BC38jAEEQayIKJABB3NUAKAIAIglFBEBBnNkAKAIAIgVFBEBBqNkAQn83AgBBoNkAQoCAhICAgMAANwIAQZzZACAKQQhqQXBxQdiq1aoFcyIFNgIAQbDZAEEANgIAQYDZAEEANgIAC0GE2QBBwNkENgIAQdTVAEHA2QQ2AgBB6NUAIAU2AgBB5NUAQX82AgBBiNkAQcCmAzYCAANAIAFBgNYAaiABQfTVAGoiAjYCACACIAFB7NUAaiIDNgIAIAFB+NUAaiADNgIAIAFBiNYAaiABQfzVAGoiAzYCACADIAI2AgAgAUGQ1gBqIAFBhNYAaiICNgIAIAIgAzYCACABQYzWAGogAjYCACABQSBqIgFBgAJHDQALQczZBEGBpgM2AgBB4NUAQazZACgCADYCAEHQ1QBBgKYDNgIAQdzVAEHI2QQ2AgBBzP8HQTg2AgBByNkEIQkLAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEHsAU0EQEHE1QAoAgAiBkEQIABBE2pBcHEgAEELSRsiBEEDdiIAdiIBQQNxBEACQCABQQFxIAByQQFzIgJBA3QiAEHs1QBqIgEgAEH01QBqKAIAIgAoAggiA0YEQEHE1QAgBkF+IAJ3cTYCAAwBCyABIAM2AgggAyABNgIMCyAAQQhqIQEgACACQQN0IgJBA3I2AgQgACACaiIAIAAoAgRBAXI2AgQMEQtBzNUAKAIAIgggBE8NASABBEACQEECIAB0IgJBACACa3IgASAAdHFoIgBBA3QiAkHs1QBqIgEgAkH01QBqKAIAIgIoAggiA0YEQEHE1QAgBkF+IAB3cSIGNgIADAELIAEgAzYCCCADIAE2AgwLIAIgBEEDcjYCBCAAQQN0IgAgBGshBSAAIAJqIAU2AgAgAiAEaiIEIAVBAXI2AgQgCARAIAhBeHFB7NUAaiEAQdjVACgCACEDAn9BASAIQQN2dCIBIAZxRQRAQcTVACABIAZyNgIAIAAMAQsgACgCCAsiASADNgIMIAAgAzYCCCADIAA2AgwgAyABNgIICyACQQhqIQFB2NUAIAQ2AgBBzNUAIAU2AgAMEQtByNUAKAIAIgtFDQEgC2hBAnRB9NcAaigCACIAKAIEQXhxIARrIQUgACECA0ACQCACKAIQIgFFBEAgAkEUaigCACIBRQ0BCyABKAIEQXhxIARrIgMgBUkhAiADIAUgAhshBSABIAAgAhshACABIQIMAQsLIAAoAhghCSAAKAIMIgMgAEcEQEHU1QAoAgAaIAMgACgCCCIBNgIIIAEgAzYCDAwQCyAAQRRqIgIoAgAiAUUEQCAAKAIQIgFFDQMgAEEQaiECCwNAIAIhByABIgNBFGoiAigCACIBDQAgA0EQaiECIAMoAhAiAQ0ACyAHQQA2AgAMDwtBfyEEIABBv39LDQAgAEETaiIBQXBxIQRByNUAKAIAIghFDQBBACAEayEFAkACQAJAAn9BACAEQYACSQ0AGkEfIARB////B0sNABogBEEmIAFBCHZnIgBrdkEBcSAAQQF0a0E+agsiBkECdEH01wBqKAIAIgJFBEBBACEBQQAhAwwBC0EAIQEgBEEZIAZBAXZrQQAgBkEfRxt0IQBBACEDA0ACQCACKAIEQXhxIARrIgcgBU8NACACIQMgByIFDQBBACEFIAIhAQwDCyABIAJBFGooAgAiByAHIAIgAEEddkEEcWpBEGooAgAiAkYbIAEgBxshASAAQQF0IQAgAg0ACwsgASADckUEQEEAIQNBAiAGdCIAQQAgAGtyIAhxIgBFDQMgAGhBAnRB9NcAaigCACEBCyABRQ0BCwNAIAEoAgRBeHEgBGsiAiAFSSEAIAIgBSAAGyEFIAEgAyAAGyEDIAEoAhAiAAR/IAAFIAFBFGooAgALIgENAAsLIANFDQAgBUHM1QAoAgAgBGtPDQAgAygCGCEHIAMgAygCDCIARwRAQdTVACgCABogACADKAIIIgE2AgggASAANgIMDA4LIANBFGoiAigCACIBRQRAIAMoAhAiAUUNAyADQRBqIQILA0AgAiEGIAEiAEEUaiICKAIAIgENACAAQRBqIQIgACgCECIBDQALIAZBADYCAAwNC0HM1QAoAgAiAyAETwRAQdjVACgCACEBAkAgAyAEayICQRBPBEAgASAEaiIAIAJBAXI2AgQgASADaiACNgIAIAEgBEEDcjYCBAwBCyABIANBA3I2AgQgASADaiIAIAAoAgRBAXI2AgRBACEAQQAhAgtBzNUAIAI2AgBB2NUAIAA2AgAgAUEIaiEBDA8LQdDVACgCACIDIARLBEAgBCAJaiIAIAMgBGsiAUEBcjYCBEHc1QAgADYCAEHQ1QAgATYCACAJIARBA3I2AgQgCUEIaiEBDA8LQQAhASAEAn9BnNkAKAIABEBBpNkAKAIADAELQajZAEJ/NwIAQaDZAEKAgISAgIDAADcCAEGc2QAgCkEMakFwcUHYqtWqBXM2AgBBsNkAQQA2AgBBgNkAQQA2AgBBgIAECyIAIARBxwBqIgVqIgZBACAAayIHcSICTwRAQbTZAEEwNgIADA8LAkBB/NgAKAIAIgFFDQBB9NgAKAIAIgggAmohACAAIAFNIAAgCEtxDQBBACEBQbTZAEEwNgIADA8LQYDZAC0AAEEEcQ0EAkACQCAJBEBBhNkAIQEDQCABKAIAIgAgCU0EQCAAIAEoAgRqIAlLDQMLIAEoAggiAQ0ACwtBABA7IgBBf0YNBSACIQZBoNkAKAIAIgFBAWsiAyAAcQRAIAIgAGsgACADakEAIAFrcWohBgsgBCAGTw0FIAZB/v///wdLDQVB/NgAKAIAIgMEQEH02AAoAgAiByAGaiEBIAEgB00NBiABIANLDQYLIAYQOyIBIABHDQEMBwsgBiADayAHcSIGQf7///8HSw0EIAYQOyEAIAAgASgCACABKAIEakYNAyAAIQELAkAgBiAEQcgAak8NACABQX9GDQBBpNkAKAIAIgAgBSAGa2pBACAAa3EiAEH+////B0sEQCABIQAMBwsgABA7QX9HBEAgACAGaiEGIAEhAAwHC0EAIAZrEDsaDAQLIAEiAEF/Rw0FDAMLQQAhAwwMC0EAIQAMCgsgAEF/Rw0CC0GA2QBBgNkAKAIAQQRyNgIACyACQf7///8HSw0BIAIQOyEAQQAQOyEBIABBf0YNASABQX9GDQEgACABTw0BIAEgAGsiBiAEQThqTQ0BC0H02ABB9NgAKAIAIAZqIgE2AgBB+NgAKAIAIAFJBEBB+NgAIAE2AgALAkACQAJAQdzVACgCACICBEBBhNkAIQEDQCAAIAEoAgAiAyABKAIEIgVqRg0CIAEoAggiAQ0ACwwCC0HU1QAoAgAiAUEARyAAIAFPcUUEQEHU1QAgADYCAAtBACEBQYjZACAGNgIAQYTZACAANgIAQeTVAEF/NgIAQejVAEGc2QAoAgA2AgBBkNkAQQA2AgADQCABQYDWAGogAUH01QBqIgI2AgAgAiABQezVAGoiAzYCACABQfjVAGogAzYCACABQYjWAGogAUH81QBqIgM2AgAgAyACNgIAIAFBkNYAaiABQYTWAGoiAjYCACACIAM2AgAgAUGM1gBqIAI2AgAgAUEgaiIBQYACRw0AC0F4IABrQQ9xIgEgAGoiAiAGQThrIgMgAWsiAUEBcjYCBEHg1QBBrNkAKAIANgIAQdDVACABNgIAQdzVACACNgIAIAAgA2pBODYCBAwCCyAAIAJNDQAgAiADSQ0AIAEoAgxBCHENAEF4IAJrQQ9xIgAgAmoiA0HQ1QAoAgAgBmoiByAAayIAQQFyNgIEIAEgBSAGajYCBEHg1QBBrNkAKAIANgIAQdDVACAANgIAQdzVACADNgIAIAIgB2pBODYCBAwBCyAAQdTVACgCAEkEQEHU1QAgADYCAAsgACAGaiEDQYTZACEBAkACQAJAA0AgAyABKAIARwRAIAEoAggiAQ0BDAILCyABLQAMQQhxRQ0BC0GE2QAhAQNAIAEoAgAiAyACTQRAIAMgASgCBGoiBSACSw0DCyABKAIIIQEMAAsACyABIAA2AgAgASABKAIEIAZqNgIEIABBeCAAa0EPcWoiCSAEQQNyNgIEIANBeCADa0EPcWoiBiAEIAlqIgRrIQEgAiAGRgRAQdzVACAENgIAQdDVAEHQ1QAoAgAgAWoiADYCACAEIABBAXI2AgQMCAtB2NUAKAIAIAZGBEBB2NUAIAQ2AgBBzNUAQczVACgCACABaiIANgIAIAQgAEEBcjYCBCAAIARqIAA2AgAMCAsgBigCBCIFQQNxQQFHDQYgBUF4cSEIIAVB/wFNBEAgBUEDdiEDIAYoAggiACAGKAIMIgJGBEBBxNUAQcTVACgCAEF+IAN3cTYCAAwHCyACIAA2AgggACACNgIMDAYLIAYoAhghByAGIAYoAgwiAEcEQCAAIAYoAggiAjYCCCACIAA2AgwMBQsgBkEUaiICKAIAIgVFBEAgBigCECIFRQ0EIAZBEGohAgsDQCACIQMgBSIAQRRqIgIoAgAiBQ0AIABBEGohAiAAKAIQIgUNAAsgA0EANgIADAQLQXggAGtBD3EiASAAaiIHIAZBOGsiAyABayIBQQFyNgIEIAAgA2pBODYCBCACIAVBNyAFa0EPcWpBP2siAyADIAJBEGpJGyIDQSM2AgRB4NUAQazZACgCADYCAEHQ1QAgATYCAEHc1QAgBzYCACADQRBqQYzZACkCADcCACADQYTZACkCADcCCEGM2QAgA0EIajYCAEGI2QAgBjYCAEGE2QAgADYCAEGQ2QBBADYCACADQSRqIQEDQCABQQc2AgAgBSABQQRqIgFLDQALIAIgA0YNACADIAMoAgRBfnE2AgQgAyADIAJrIgU2AgAgAiAFQQFyNgIEIAVB/wFNBEAgBUF4cUHs1QBqIQACf0HE1QAoAgAiAUEBIAVBA3Z0IgNxRQRAQcTVACABIANyNgIAIAAMAQsgACgCCAsiASACNgIMIAAgAjYCCCACIAA2AgwgAiABNgIIDAELQR8hASAFQf///wdNBEAgBUEmIAVBCHZnIgBrdkEBcSAAQQF0a0E+aiEBCyACIAE2AhwgAkIANwIQIAFBAnRB9NcAaiEAQcjVACgCACIDQQEgAXQiBnFFBEAgACACNgIAQcjVACADIAZyNgIAIAIgADYCGCACIAI2AgggAiACNgIMDAELIAVBGSABQQF2a0EAIAFBH0cbdCEBIAAoAgAhAwJAA0AgAyIAKAIEQXhxIAVGDQEgAUEddiEDIAFBAXQhASAAIANBBHFqQRBqIgYoAgAiAw0ACyAGIAI2AgAgAiAANgIYIAIgAjYCDCACIAI2AggMAQsgACgCCCIBIAI2AgwgACACNgIIIAJBADYCGCACIAA2AgwgAiABNgIIC0HQ1QAoAgAiASAETQ0AQdzVACgCACIAIARqIgIgASAEayIBQQFyNgIEQdDVACABNgIAQdzVACACNgIAIAAgBEEDcjYCBCAAQQhqIQEMCAtBACEBQbTZAEEwNgIADAcLQQAhAAsgB0UNAAJAIAYoAhwiAkECdEH01wBqIgMoAgAgBkYEQCADIAA2AgAgAA0BQcjVAEHI1QAoAgBBfiACd3E2AgAMAgsgB0EQQRQgBygCECAGRhtqIAA2AgAgAEUNAQsgACAHNgIYIAYoAhAiAgRAIAAgAjYCECACIAA2AhgLIAZBFGooAgAiAkUNACAAQRRqIAI2AgAgAiAANgIYCyABIAhqIQEgBiAIaiIGKAIEIQULIAYgBUF+cTYCBCABIARqIAE2AgAgBCABQQFyNgIEIAFB/wFNBEAgAUF4cUHs1QBqIQACf0HE1QAoAgAiAkEBIAFBA3Z0IgFxRQRAQcTVACABIAJyNgIAIAAMAQsgACgCCAsiASAENgIMIAAgBDYCCCAEIAA2AgwgBCABNgIIDAELQR8hBSABQf///wdNBEAgAUEmIAFBCHZnIgBrdkEBcSAAQQF0a0E+aiEFCyAEIAU2AhwgBEIANwIQIAVBAnRB9NcAaiEAQcjVACgCACICQQEgBXQiA3FFBEAgACAENgIAQcjVACACIANyNgIAIAQgADYCGCAEIAQ2AgggBCAENgIMDAELIAFBGSAFQQF2a0EAIAVBH0cbdCEFIAAoAgAhAAJAA0AgACICKAIEQXhxIAFGDQEgBUEddiEAIAVBAXQhBSACIABBBHFqQRBqIgMoAgAiAA0ACyADIAQ2AgAgBCACNgIYIAQgBDYCDCAEIAQ2AggMAQsgAigCCCIAIAQ2AgwgAiAENgIIIARBADYCGCAEIAI2AgwgBCAANgIICyAJQQhqIQEMAgsCQCAHRQ0AAkAgAygCHCIBQQJ0QfTXAGoiAigCACADRgRAIAIgADYCACAADQFByNUAIAhBfiABd3EiCDYCAAwCCyAHQRBBFCAHKAIQIANGG2ogADYCACAARQ0BCyAAIAc2AhggAygCECIBBEAgACABNgIQIAEgADYCGAsgA0EUaigCACIBRQ0AIABBFGogATYCACABIAA2AhgLAkAgBUEPTQRAIAMgBCAFaiIAQQNyNgIEIAAgA2oiACAAKAIEQQFyNgIEDAELIAMgBGoiAiAFQQFyNgIEIAMgBEEDcjYCBCACIAVqIAU2AgAgBUH/AU0EQCAFQXhxQezVAGohAAJ/QcTVACgCACIBQQEgBUEDdnQiBXFFBEBBxNUAIAEgBXI2AgAgAAwBCyAAKAIICyIBIAI2AgwgACACNgIIIAIgADYCDCACIAE2AggMAQtBHyEBIAVB////B00EQCAFQSYgBUEIdmciAGt2QQFxIABBAXRrQT5qIQELIAIgATYCHCACQgA3AhAgAUECdEH01wBqIQBBASABdCIEIAhxRQRAIAAgAjYCAEHI1QAgBCAIcjYCACACIAA2AhggAiACNgIIIAIgAjYCDAwBCyAFQRkgAUEBdmtBACABQR9HG3QhASAAKAIAIQQCQANAIAQiACgCBEF4cSAFRg0BIAFBHXYhBCABQQF0IQEgACAEQQRxakEQaiIGKAIAIgQNAAsgBiACNgIAIAIgADYCGCACIAI2AgwgAiACNgIIDAELIAAoAggiASACNgIMIAAgAjYCCCACQQA2AhggAiAANgIMIAIgATYCCAsgA0EIaiEBDAELAkAgCUUNAAJAIAAoAhwiAUECdEH01wBqIgIoAgAgAEYEQCACIAM2AgAgAw0BQcjVACALQX4gAXdxNgIADAILIAlBEEEUIAkoAhAgAEYbaiADNgIAIANFDQELIAMgCTYCGCAAKAIQIgEEQCADIAE2AhAgASADNgIYCyAAQRRqKAIAIgFFDQAgA0EUaiABNgIAIAEgAzYCGAsCQCAFQQ9NBEAgACAEIAVqIgFBA3I2AgQgACABaiIBIAEoAgRBAXI2AgQMAQsgACAEaiIHIAVBAXI2AgQgACAEQQNyNgIEIAUgB2ogBTYCACAIBEAgCEF4cUHs1QBqIQFB2NUAKAIAIQMCf0EBIAhBA3Z0IgIgBnFFBEBBxNUAIAIgBnI2AgAgAQwBCyABKAIICyICIAM2AgwgASADNgIIIAMgATYCDCADIAI2AggLQdjVACAHNgIAQczVACAFNgIACyAAQQhqIQELIApBEGokACABC0MAIABFBEA/AEEQdA8LAkAgAEH//wNxDQAgAEEASA0AIABBEHZAACIAQX9GBEBBtNkAQTA2AgBBfw8LIABBEHQPCwALC5lCIgBBgAgLDQEAAAAAAAAAAgAAAAMAQZgICwUEAAAABQBBqAgLCQYAAAAHAAAACABB5AgLwjJJbnZhbGlkIGNoYXIgaW4gdXJsIHF1ZXJ5AFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fYm9keQBDb250ZW50LUxlbmd0aCBvdmVyZmxvdwBDaHVuayBzaXplIG92ZXJmbG93AEludmFsaWQgbWV0aG9kIGZvciBIVFRQL3gueCByZXF1ZXN0AEludmFsaWQgbWV0aG9kIGZvciBSVFNQL3gueCByZXF1ZXN0AEV4cGVjdGVkIFNPVVJDRSBtZXRob2QgZm9yIElDRS94LnggcmVxdWVzdABJbnZhbGlkIGNoYXIgaW4gdXJsIGZyYWdtZW50IHN0YXJ0AEV4cGVjdGVkIGRvdABTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3N0YXR1cwBJbnZhbGlkIHJlc3BvbnNlIHN0YXR1cwBFeHBlY3RlZCBMRiBhZnRlciBoZWFkZXJzAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMAVXNlciBjYWxsYmFjayBlcnJvcgBgb25fcmVzZXRgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19oZWFkZXJgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3Byb3RvY29sX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fcHJvdG9jb2wARW1wdHkgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyYWN0ZXIgaW4gQ29udGVudC1MZW5ndGgAVHJhbnNmZXItRW5jb2RpbmcgY2FuJ3QgYmUgcHJlc2VudCB3aXRoIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgc2l6ZQBFeHBlY3RlZCBMRiBhZnRlciBjaHVuayBzaXplAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBVbmV4cGVjdGVkIHdoaXRlc3BhY2UgYWZ0ZXIgaGVhZGVyIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgaGVhZGVyIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgTEYgYWZ0ZXIgaGVhZGVyIHZhbHVlAEludmFsaWQgYFRyYW5zZmVyLUVuY29kaW5nYCBoZWFkZXIgdmFsdWUATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciBjaHVuayBleHRlbnNpb24gdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZSB2YWx1ZQBJbnZhbGlkIHF1b3RlZC1wYWlyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fcHJvdG9jb2xfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciByZXNwb25zZSBsaW5lAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBuYW1lAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgZXh0ZW5zaW9uIG5hbWUASW52YWxpZCBzdGF0dXMgY29kZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABNaXNzaW5nIGV4cGVjdGVkIENSIGFmdGVyIGNodW5rIGRhdGEARXhwZWN0ZWQgTEYgYWZ0ZXIgY2h1bmsgZGF0YQBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AARGF0YSBhZnRlciBgQ29ubmVjdGlvbjogY2xvc2VgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBRVUVSWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAEV4cGVjdGVkIExGIGFmdGVyIENSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX1BST1RPQ09MX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19DT01QTEVURQBIUEVfQ0JfSEVBREVSX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9OQU1FX0NPTVBMRVRFAEhQRV9DQl9NRVNTQUdFX0NPTVBMRVRFAEhQRV9DQl9NRVRIT0RfQ09NUExFVEUASFBFX0NCX0hFQURFUl9GSUVMRF9DT01QTEVURQBERUxFVEUASFBFX0lOVkFMSURfRU9GX1NUQVRFAElOVkFMSURfU1NMX0NFUlRJRklDQVRFAFBBVVNFAE5PX1JFU1BPTlNFAFVOU1VQUE9SVEVEX01FRElBX1RZUEUAR09ORQBOT1RfQUNDRVBUQUJMRQBTRVJWSUNFX1VOQVZBSUxBQkxFAFJBTkdFX05PVF9TQVRJU0ZJQUJMRQBPUklHSU5fSVNfVU5SRUFDSEFCTEUAUkVTUE9OU0VfSVNfU1RBTEUAUFVSR0UATUVSR0UAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRQBSRVFVRVNUX0hFQURFUl9UT09fTEFSR0UAUEFZTE9BRF9UT09fTEFSR0UASU5TVUZGSUNJRU5UX1NUT1JBR0UASFBFX1BBVVNFRF9VUEdSQURFAEhQRV9QQVVTRURfSDJfVVBHUkFERQBTT1VSQ0UAQU5OT1VOQ0UAVFJBQ0UASFBFX1VORVhQRUNURURfU1BBQ0UAREVTQ1JJQkUAVU5TVUJTQ1JJQkUAUkVDT1JEAEhQRV9JTlZBTElEX01FVEhPRABOT1RfRk9VTkQAUFJPUEZJTkQAVU5CSU5EAFJFQklORABVTkFVVEhPUklaRUQATUVUSE9EX05PVF9BTExPV0VEAEhUVFBfVkVSU0lPTl9OT1RfU1VQUE9SVEVEAEFMUkVBRFlfUkVQT1JURUQAQUNDRVBURUQATk9UX0lNUExFTUVOVEVEAExPT1BfREVURUNURUQASFBFX0NSX0VYUEVDVEVEAEhQRV9MRl9FWFBFQ1RFRABDUkVBVEVEAElNX1VTRUQASFBFX1BBVVNFRABUSU1FT1VUX09DQ1VSRUQAUEFZTUVOVF9SRVFVSVJFRABQUkVDT05ESVRJT05fUkVRVUlSRUQAUFJPWFlfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATkVUV09SS19BVVRIRU5USUNBVElPTl9SRVFVSVJFRABMRU5HVEhfUkVRVUlSRUQAU1NMX0NFUlRJRklDQVRFX1JFUVVJUkVEAFVQR1JBREVfUkVRVUlSRUQAUEFHRV9FWFBJUkVEAFBSRUNPTkRJVElPTl9GQUlMRUQARVhQRUNUQVRJT05fRkFJTEVEAFJFVkFMSURBVElPTl9GQUlMRUQAU1NMX0hBTkRTSEFLRV9GQUlMRUQATE9DS0VEAFRSQU5TRk9STUFUSU9OX0FQUExJRUQATk9UX01PRElGSUVEAE5PVF9FWFRFTkRFRABCQU5EV0lEVEhfTElNSVRfRVhDRUVERUQAU0lURV9JU19PVkVSTE9BREVEAEhFQUQARXhwZWN0ZWQgSFRUUC8sIFJUU1AvIG9yIElDRS8A5xUAAK8VAACkEgAAkhoAACYWAACeFAAA2xkAAHkVAAB+EgAA/hQAADYVAAALFgAA2BYAAPMSAABCGAAArBYAABIVAAAUFwAA7xcAAEgUAABxFwAAshoAAGsZAAB+GQAANRQAAIIaAABEFwAA/RYAAB4YAACHFwAAqhkAAJMSAAAHGAAALBcAAMoXAACkFwAA5xUAAOcVAABYFwAAOxgAAKASAAAtHAAAwxEAAEgRAADeEgAAQhMAAKQZAAD9EAAA9xUAAKUVAADvFgAA+BkAAEoWAABWFgAA9RUAAAoaAAAIGgAAARoAAKsVAABCEgAA1xAAAEwRAAAFGQAAVBYAAB4RAADKGQAAyBkAAE4WAAD/GAAAcRQAAPAVAADuFQAAlBkAAPwVAAC/GQAAmxkAAHwUAABDEQAAcBgAAJUUAAAnFAAAGRQAANUSAADUGQAARBYAAPcQAEG5OwsBAQBB0DsL4AEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBBuj0LBAEAAAIAQdE9C14DBAMDAwMDAAADAwADAwADAwMDAwMDAwMDAAUAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAwADAEG6PwsEAQAAAgBB0T8LXgMAAwMDAwMAAAMDAAMDAAMDAwMDAwMDAwMABAAFAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwADAAMAQbDBAAsNbG9zZWVlcC1hbGl2ZQBBycEACwEBAEHgwQAL4AEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBBycMACwEBAEHgwwAL5wEBAQEBAQEBAQEBAQECAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAWNodW5rZWQAQfHFAAteAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQBB0McACyFlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AQYDIAAsgcmFuc2Zlci1lbmNvZGluZ3BncmFkZQ0KDQpTTQ0KDQoAQanIAAsFAQIAAQMAQcDIAAtfBAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAQanKAAsFAQIAAQMAQcDKAAtfBAUFBgUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAQanMAAsEAQAAAQBBwcwAC14CAgACAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAEGpzgALBQECAAEDAEHAzgALXwQFAAAFBQUFBQUFBQUFBQYFBQUFBQUFBQUFBQUABQAHCAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQAFAAUABQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAAAAFAEGp0AALBQEBAAEBAEHA0AALAQEAQdrQAAtBAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQanSAAsFAQEAAQEAQcDSAAsBAQBBytIACwYCAAAAAAIAQeHSAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBBoNQAC50BTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRVVFUllPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFVFRQQ0VUU1BBRFRQLw=="; + var wasmBuffer; + Object.defineProperty(module2, "exports", { + get: () => { + return wasmBuffer ? wasmBuffer : wasmBuffer = Buffer3.from(wasmBase64, "base64"); + } + }); } }); @@ -3377,10 +4298,9 @@ var require_constants3 = __commonJS({ ] ); var badPortsSet = new Set(badPorts); - var referrerPolicy = ( + var referrerPolicyTokens = ( /** @type {const} */ [ - "", "no-referrer", "no-referrer-when-downgrade", "same-origin", @@ -3391,7 +4311,14 @@ var require_constants3 = __commonJS({ "unsafe-url" ] ); - var referrerPolicySet = new Set(referrerPolicy); + var referrerPolicy = ( + /** @type {const} */ + [ + "", + ...referrerPolicyTokens + ] + ); + var referrerPolicyTokensSet = new Set(referrerPolicyTokens); var requestRedirect = ( /** @type {const} */ ["follow", "manual", "error"] @@ -3484,7 +4411,7 @@ var require_constants3 = __commonJS({ corsSafeListedMethodsSet, safeMethodsSet, forbiddenMethodsSet, - referrerPolicySet + referrerPolicyTokens: referrerPolicyTokensSet }; } }); @@ -3525,65 +4452,33 @@ var require_global = __commonJS({ } }); -// node_modules/undici/lib/web/fetch/data-url.js -var require_data_url = __commonJS({ - "node_modules/undici/lib/web/fetch/data-url.js"(exports2, module2) { +// node_modules/undici/lib/encoding/index.js +var require_encoding = __commonJS({ + "node_modules/undici/lib/encoding/index.js"(exports2, module2) { "use strict"; - var assert = require("node:assert"); - var encoder = new TextEncoder(); - var HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+\-.^_|~A-Za-z0-9]+$/; - var HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/; - var ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g; - var HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/; - function dataURLProcessor(dataURL) { - assert(dataURL.protocol === "data:"); - let input = URLSerializer(dataURL, true); - input = input.slice(5); - const position = { position: 0 }; - let mimeType = collectASequenceOfCodePointsFast( - ",", - input, - position - ); - const mimeTypeLength = mimeType.length; - mimeType = removeASCIIWhitespace(mimeType, true, true); - if (position.position >= input.length) { - return "failure"; - } - position.position++; - const encodedBody = input.slice(mimeTypeLength + 1); - let body = stringPercentDecode(encodedBody); - if (/;(\u0020){0,}base64$/i.test(mimeType)) { - const stringBody = isomorphicDecode(body); - body = forgivingBase64(stringBody); - if (body === "failure") { - return "failure"; - } - mimeType = mimeType.slice(0, -6); - mimeType = mimeType.replace(/(\u0020)+$/, ""); - mimeType = mimeType.slice(0, -1); - } - if (mimeType.startsWith(";")) { - mimeType = "text/plain" + mimeType; - } - let mimeTypeRecord = parseMIMEType(mimeType); - if (mimeTypeRecord === "failure") { - mimeTypeRecord = parseMIMEType("text/plain;charset=US-ASCII"); - } - return { mimeType: mimeTypeRecord, body }; - } - function URLSerializer(url2, excludeFragment = false) { - if (!excludeFragment) { - return url2.href; + var textDecoder = new TextDecoder(); + function utf8DecodeBytes(buffer) { + if (buffer.length === 0) { + return ""; } - const href = url2.href; - const hashLength = url2.hash.length; - const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength); - if (!hashLength && href.endsWith("#")) { - return serialized.slice(0, -1); + if (buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191) { + buffer = buffer.subarray(3); } - return serialized; + const output = textDecoder.decode(buffer); + return output; } + module2.exports = { + utf8DecodeBytes + }; + } +}); + +// node_modules/undici/lib/web/infra/index.js +var require_infra = __commonJS({ + "node_modules/undici/lib/web/infra/index.js"(exports2, module2) { + "use strict"; + var assert = require("node:assert"); + var { utf8DecodeBytes } = require_encoding(); function collectASequenceOfCodePoints(condition, input, position) { let result = ""; while (position.position < input.length && condition(input[position.position])) { @@ -3602,33 +4497,188 @@ var require_data_url = __commonJS({ position.position = idx; return input.slice(start, position.position); } - function stringPercentDecode(input) { - const bytes = encoder.encode(input); - return percentDecode(bytes); - } - function isHexCharByte(byte) { - return byte >= 48 && byte <= 57 || byte >= 65 && byte <= 70 || byte >= 97 && byte <= 102; - } - function hexByteToNumber(byte) { - return ( - // 0-9 - byte >= 48 && byte <= 57 ? byte - 48 : (byte & 223) - 55 - ); + var ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g; + var nonASCIIRegex = /[^\x00-\x7F]/; + function asciiLowercase(str) { + return nonASCIIRegex.test(str) ? str.replace(/[A-Z]+/g, (upper) => upper.toLowerCase()) : str.toLowerCase(); } - function percentDecode(input) { - const length = input.length; - const output = new Uint8Array(length); - let j = 0; - for (let i = 0; i < length; ++i) { - const byte = input[i]; - if (byte !== 37) { - output[j++] = byte; - } else if (byte === 37 && !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2]))) { - output[j++] = 37; - } else { + function forgivingBase64(data) { + data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, ""); + let dataLength = data.length; + if (dataLength % 4 === 0) { + if (data.charCodeAt(dataLength - 1) === 61) { + --dataLength; + if (data.charCodeAt(dataLength - 1) === 61) { + --dataLength; + } + } + } + if (dataLength % 4 === 1) { + 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); + } + function isASCIIWhitespace(char) { + return char === 9 || // \t + char === 10 || // \n + char === 12 || // \f + char === 13 || // \r + char === 32; + } + function isomorphicDecode(input) { + 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; + } + var invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/; + function isomorphicEncode(input) { + assert(!invalidIsomorphicEncodeValueRegex.test(input)); + return input; + } + function parseJSONFromBytes(bytes) { + return JSON.parse(utf8DecodeBytes(bytes)); + } + function removeASCIIWhitespace(str, leading = true, trailing = true) { + return removeChars(str, leading, trailing, isASCIIWhitespace); + } + 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); + } + function serializeJavascriptValueToJSONString(value) { + const result = JSON.stringify(value); + if (result === void 0) { + throw new TypeError("Value is not JSON serializable"); + } + assert(typeof result === "string"); + return result; + } + module2.exports = { + asciiLowercase, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + forgivingBase64, + isASCIIWhitespace, + isomorphicDecode, + isomorphicEncode, + parseJSONFromBytes, + removeASCIIWhitespace, + removeChars, + serializeJavascriptValueToJSONString + }; + } +}); + +// node_modules/undici/lib/web/fetch/data-url.js +var require_data_url = __commonJS({ + "node_modules/undici/lib/web/fetch/data-url.js"(exports2, module2) { + "use strict"; + var assert = require("node:assert"); + var { forgivingBase64, collectASequenceOfCodePoints, collectASequenceOfCodePointsFast, isomorphicDecode, removeASCIIWhitespace, removeChars } = require_infra(); + var encoder2 = new TextEncoder(); + var HTTP_TOKEN_CODEPOINTS = /^[-!#$%&'*+.^_|~A-Za-z0-9]+$/u; + var HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/u; + var HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/u; + function dataURLProcessor(dataURL) { + assert(dataURL.protocol === "data:"); + let input = URLSerializer(dataURL, true); + input = input.slice(5); + const position = { position: 0 }; + let mimeType = collectASequenceOfCodePointsFast( + ",", + input, + position + ); + const mimeTypeLength = mimeType.length; + mimeType = removeASCIIWhitespace(mimeType, true, true); + if (position.position >= input.length) { + return "failure"; + } + position.position++; + const encodedBody = input.slice(mimeTypeLength + 1); + let body = stringPercentDecode(encodedBody); + if (/;(?:\u0020*)base64$/ui.test(mimeType)) { + const stringBody = isomorphicDecode(body); + body = forgivingBase64(stringBody); + if (body === "failure") { + return "failure"; + } + mimeType = mimeType.slice(0, -6); + mimeType = mimeType.replace(/(\u0020+)$/u, ""); + mimeType = mimeType.slice(0, -1); + } + if (mimeType.startsWith(";")) { + mimeType = "text/plain" + mimeType; + } + let mimeTypeRecord = parseMIMEType(mimeType); + if (mimeTypeRecord === "failure") { + mimeTypeRecord = parseMIMEType("text/plain;charset=US-ASCII"); + } + return { mimeType: mimeTypeRecord, body }; + } + function URLSerializer(url2, excludeFragment = false) { + if (!excludeFragment) { + return url2.href; + } + const href = url2.href; + const hashLength = url2.hash.length; + const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength); + if (!hashLength && href.endsWith("#")) { + return serialized.slice(0, -1); + } + return serialized; + } + function stringPercentDecode(input) { + const bytes = encoder2.encode(input); + return percentDecode(bytes); + } + function isHexCharByte(byte) { + return byte >= 48 && byte <= 57 || byte >= 65 && byte <= 70 || byte >= 97 && byte <= 102; + } + function hexByteToNumber(byte) { + return ( + // 0-9 + byte >= 48 && byte <= 57 ? byte - 48 : (byte & 223) - 55 + ); + } + function percentDecode(input) { + const length = input.length; + const output = new Uint8Array(length); + let j = 0; + let i = 0; + while (i < length) { + const byte = input[i]; + if (byte !== 37) { + output[j++] = byte; + } else if (byte === 37 && !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2]))) { + output[j++] = 37; + } else { output[j++] = hexByteToNumber(input[i + 1]) << 4 | hexByteToNumber(input[i + 2]); i += 2; } + ++i; } return length === j ? output : output.subarray(0, j); } @@ -3643,7 +4693,7 @@ var require_data_url = __commonJS({ if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { return "failure"; } - if (position.position > input.length) { + if (position.position >= input.length) { return "failure"; } position.position++; @@ -3686,7 +4736,7 @@ var require_data_url = __commonJS({ } position.position++; } - if (position.position > input.length) { + if (position.position >= input.length) { break; } let parameterValue = null; @@ -3714,27 +4764,7 @@ var require_data_url = __commonJS({ } return mimeType; } - function forgivingBase64(data) { - data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, ""); - let dataLength = data.length; - if (dataLength % 4 === 0) { - if (data.charCodeAt(dataLength - 1) === 61) { - --dataLength; - if (data.charCodeAt(dataLength - 1) === 61) { - --dataLength; - } - } - } - if (dataLength % 4 === 1) { - 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); - } - function collectAnHTTPQuotedString(input, position, extractValue) { + function collectAnHTTPQuotedString(input, position, extractValue = false) { const positionStart = position.position; let value = ""; assert(input[position.position] === '"'); @@ -3776,7 +4806,7 @@ var require_data_url = __commonJS({ serialization += name; serialization += "="; if (!HTTP_TOKEN_CODEPOINTS.test(value)) { - value = value.replace(/(\\|")/g, "\\$1"); + value = value.replace(/[\\"]/ug, "\\$&"); value = '"' + value; value += '"'; } @@ -3790,39 +4820,6 @@ var require_data_url = __commonJS({ function removeHTTPWhitespace(str, leading = true, trailing = true) { return removeChars(str, leading, trailing, isHTTPWhiteSpace); } - function isASCIIWhitespace(char) { - return char === 13 || char === 10 || char === 9 || char === 12 || char === 32; - } - function removeASCIIWhitespace(str, leading = true, trailing = true) { - return removeChars(str, leading, trailing, isASCIIWhitespace); - } - 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); - } - function isomorphicDecode(input) { - 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; - } function minimizeSupportedMimeType(mimeType) { switch (mimeType.essence) { case "application/ecmascript": @@ -3862,40 +4859,149 @@ var require_data_url = __commonJS({ module2.exports = { dataURLProcessor, URLSerializer, - collectASequenceOfCodePoints, - collectASequenceOfCodePointsFast, stringPercentDecode, parseMIMEType, collectAnHTTPQuotedString, serializeAMimeType, - removeChars, removeHTTPWhitespace, minimizeSupportedMimeType, - HTTP_TOKEN_CODEPOINTS, - isomorphicDecode + HTTP_TOKEN_CODEPOINTS + }; + } +}); + +// node_modules/undici/lib/util/runtime-features.js +var require_runtime_features = __commonJS({ + "node_modules/undici/lib/util/runtime-features.js"(exports2, module2) { + "use strict"; + var lazyLoaders = { + __proto__: null, + "node:crypto": () => require("node:crypto"), + "node:sqlite": () => require("node:sqlite"), + "node:worker_threads": () => require("node:worker_threads"), + "node:zlib": () => require("node:zlib") + }; + function detectRuntimeFeatureByNodeModule(moduleName) { + try { + lazyLoaders[moduleName](); + return true; + } catch (err) { + if (err.code !== "ERR_UNKNOWN_BUILTIN_MODULE" && err.code !== "ERR_NO_CRYPTO") { + throw err; + } + return false; + } + } + function detectRuntimeFeatureByExportedProperty(moduleName, property) { + const module3 = lazyLoaders[moduleName](); + return typeof module3[property] !== "undefined"; + } + var runtimeFeaturesByExportedProperty = ( + /** @type {const} */ + ["markAsUncloneable", "zstd"] + ); + var exportedPropertyLookup = { + markAsUncloneable: ["node:worker_threads", "markAsUncloneable"], + zstd: ["node:zlib", "createZstdDecompress"] + }; + var runtimeFeaturesAsNodeModule = ( + /** @type {const} */ + ["crypto", "sqlite"] + ); + var features = ( + /** @type {const} */ + [ + ...runtimeFeaturesAsNodeModule, + ...runtimeFeaturesByExportedProperty + ] + ); + function detectRuntimeFeature(feature) { + if (runtimeFeaturesAsNodeModule.includes( + /** @type {RuntimeFeatureByNodeModule} */ + feature + )) { + return detectRuntimeFeatureByNodeModule(`node:${feature}`); + } else if (runtimeFeaturesByExportedProperty.includes( + /** @type {RuntimeFeatureByExportedProperty} */ + feature + )) { + const [moduleName, property] = exportedPropertyLookup[feature]; + return detectRuntimeFeatureByExportedProperty(moduleName, property); + } + throw new TypeError(`unknown feature: ${feature}`); + } + var RuntimeFeatures = class { + /** @type {Map} */ + #map = /* @__PURE__ */ new Map(); + /** + * Clears all cached feature detections. + */ + clear() { + this.#map.clear(); + } + /** + * @param {Feature} feature + * @returns {boolean} + */ + has(feature) { + return this.#map.get(feature) ?? this.#detectRuntimeFeature(feature); + } + /** + * @param {Feature} feature + * @param {boolean} value + */ + set(feature, value) { + if (features.includes(feature) === false) { + throw new TypeError(`unknown feature: ${feature}`); + } + this.#map.set(feature, value); + } + /** + * @param {Feature} feature + * @returns {boolean} + */ + #detectRuntimeFeature(feature) { + const result = detectRuntimeFeature(feature); + this.#map.set(feature, result); + return result; + } }; + var instance8 = new RuntimeFeatures(); + module2.exports.runtimeFeatures = instance8; + module2.exports.default = instance8; } }); -// node_modules/undici/lib/web/fetch/webidl.js +// node_modules/undici/lib/web/webidl/index.js var require_webidl = __commonJS({ - "node_modules/undici/lib/web/fetch/webidl.js"(exports2, module2) { + "node_modules/undici/lib/web/webidl/index.js"(exports2, module2) { "use strict"; + var assert = require("node:assert"); var { types: types2, inspect } = require("node:util"); - var { markAsUncloneable } = require("node:worker_threads"); - var { toUSVString } = require_util(); - var webidl = {}; - webidl.converters = {}; - webidl.util = {}; - webidl.errors = {}; + var { runtimeFeatures } = require_runtime_features(); + var UNDEFINED = 1; + var BOOLEAN = 2; + var STRING = 3; + var SYMBOL = 4; + var NUMBER = 5; + var BIGINT = 6; + var NULL = 7; + var OBJECT = 8; + var FunctionPrototypeSymbolHasInstance = Function.call.bind(Function.prototype[Symbol.hasInstance]); + var webidl = { + converters: {}, + util: {}, + errors: {}, + is: {} + }; webidl.errors.exception = function(message) { return new TypeError(`${message.header}: ${message.message}`); }; - webidl.errors.conversionFailed = function(context5) { - const plural = context5.types.length === 1 ? "" : " one of"; - const message = `${context5.argument} could not be converted to${plural}: ${context5.types.join(", ")}.`; + webidl.errors.conversionFailed = function(opts) { + const plural = opts.types.length === 1 ? "" : " one of"; + const message = `${opts.argument} could not be converted to${plural}: ${opts.types.join(", ")}.`; return webidl.errors.exception({ - header: context5.prefix, + header: opts.prefix, message }); }; @@ -3905,20 +5011,22 @@ var require_webidl = __commonJS({ message: `"${context5.value}" is an invalid ${context5.type}.` }); }; - 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"; - throw err; - } - } else { - if (V?.[Symbol.toStringTag] !== I.prototype[Symbol.toStringTag]) { + webidl.brandCheck = function(V, I) { + if (!FunctionPrototypeSymbolHasInstance(I, V)) { + const err = new TypeError("Illegal invocation"); + err.code = "ERR_INVALID_THIS"; + throw err; + } + }; + webidl.brandCheckMultiple = function(List3) { + const prototypes = List3.map((c) => webidl.util.MakeTypeAssertion(c)); + return (V) => { + if (prototypes.every((typeCheck) => !typeCheck(V))) { const err = new TypeError("Illegal invocation"); err.code = "ERR_INVALID_THIS"; throw err; } - } + }; }; webidl.argumentLengthCheck = function({ length }, min, ctx) { if (length < min) { @@ -3934,32 +5042,65 @@ var require_webidl = __commonJS({ message: "Illegal constructor" }); }; + webidl.util.MakeTypeAssertion = function(I) { + return (O) => FunctionPrototypeSymbolHasInstance(I, O); + }; webidl.util.Type = function(V) { switch (typeof V) { case "undefined": - return "Undefined"; + return UNDEFINED; case "boolean": - return "Boolean"; + return BOOLEAN; case "string": - return "String"; + return STRING; case "symbol": - return "Symbol"; + return SYMBOL; case "number": - return "Number"; + return NUMBER; case "bigint": - return "BigInt"; + return BIGINT; case "function": case "object": { if (V === null) { - return "Null"; + return NULL; } - return "Object"; + return OBJECT; } } }; - webidl.util.markAsUncloneable = markAsUncloneable || (() => { - }); - webidl.util.ConvertToInt = function(V, bitLength, signedness, opts) { + webidl.util.Types = { + UNDEFINED, + BOOLEAN, + STRING, + SYMBOL, + NUMBER, + BIGINT, + NULL, + OBJECT + }; + webidl.util.TypeValueToString = function(o) { + switch (webidl.util.Type(o)) { + 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 NULL: + return "Null"; + case OBJECT: + return "Object"; + } + }; + webidl.util.markAsUncloneable = runtimeFeatures.has("markAsUncloneable") ? require("node:worker_threads").markAsUncloneable : () => { + }; + webidl.util.ConvertToInt = function(V, bitLength, signedness, flags) { let upperBound; let lowerBound; if (bitLength === 64) { @@ -3973,14 +5114,14 @@ var require_webidl = __commonJS({ lowerBound = 0; upperBound = Math.pow(2, bitLength) - 1; } else { - lowerBound = Math.pow(-2, bitLength) - 1; + lowerBound = -Math.pow(2, bitLength - 1); upperBound = Math.pow(2, bitLength - 1) - 1; } let x = Number(V); if (x === 0) { x = 0; } - if (opts?.enforceRange === true) { + if (webidl.util.HasFlag(flags, webidl.attributes.EnforceRange)) { if (Number.isNaN(x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY) { throw webidl.errors.exception({ header: "Integer conversion", @@ -3996,7 +5137,7 @@ var require_webidl = __commonJS({ } return x; } - if (!Number.isNaN(x) && opts?.clamp === true) { + if (!Number.isNaN(x) && webidl.util.HasFlag(flags, webidl.attributes.Clamp)) { x = Math.min(Math.max(x, lowerBound), upperBound); if (Math.floor(x) % 2 === 0) { x = Math.floor(x); @@ -4010,7 +5151,7 @@ var require_webidl = __commonJS({ } x = webidl.util.IntegerPart(x); x = x % Math.pow(2, bitLength); - if (signedness === "signed" && x >= Math.pow(2, bitLength) - 1) { + if (signedness === "signed" && x >= Math.pow(2, bitLength - 1)) { return x - Math.pow(2, bitLength); } return x; @@ -4025,19 +5166,36 @@ var require_webidl = __commonJS({ webidl.util.Stringify = function(V) { const type = webidl.util.Type(V); switch (type) { - case "Symbol": + case SYMBOL: return `Symbol(${V.description})`; - case "Object": + case OBJECT: return inspect(V); - case "String": + case STRING: return `"${V}"`; + case BIGINT: + return `${V}n`; default: return `${V}`; } }; + webidl.util.IsResizableArrayBuffer = function(V) { + if (types2.isArrayBuffer(V)) { + return V.resizable; + } + if (types2.isSharedArrayBuffer(V)) { + return V.growable; + } + throw webidl.errors.exception({ + header: "IsResizableArrayBuffer", + message: `"${webidl.util.Stringify(V)}" is not an array buffer.` + }); + }; + webidl.util.HasFlag = function(flags, attributes) { + return typeof flags === "number" && (flags & attributes) === attributes; + }; webidl.sequenceConverter = function(converter) { return (V, prefix, argument, Iterable) => { - if (webidl.util.Type(V) !== "Object") { + if (webidl.util.Type(V) !== OBJECT) { throw webidl.errors.exception({ header: prefix, message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.` @@ -4064,18 +5222,19 @@ var require_webidl = __commonJS({ }; webidl.recordConverter = function(keyConverter, valueConverter) { return (O, prefix, argument) => { - if (webidl.util.Type(O) !== "Object") { + if (webidl.util.Type(O) !== OBJECT) { throw webidl.errors.exception({ header: prefix, - message: `${argument} ("${webidl.util.Type(O)}") is not an Object.` + message: `${argument} ("${webidl.util.TypeValueToString(O)}") is not an Object.` }); } const result = {}; if (!types2.isProxy(O)) { const keys2 = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)]; for (const key of keys2) { - const typedKey = keyConverter(key, prefix, argument); - const typedValue = valueConverter(O[key], prefix, argument); + const keyName = webidl.util.Stringify(key); + const typedKey = keyConverter(key, prefix, `Key ${keyName} in ${argument}`); + const typedValue = valueConverter(O[key], prefix, `${argument}[${keyName}]`); result[typedKey] = typedValue; } return result; @@ -4092,24 +5251,22 @@ var require_webidl = __commonJS({ return result; }; }; - webidl.interfaceConverter = function(i) { - return (V, prefix, argument, opts) => { - if (opts?.strict !== false && !(V instanceof i)) { + webidl.interfaceConverter = function(TypeCheck, name) { + return (V, prefix, argument) => { + if (!TypeCheck(V)) { throw webidl.errors.exception({ header: prefix, - message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${i.name}.` + message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${name}.` }); } return V; }; }; webidl.dictionaryConverter = function(converters) { + converters.sort((a, b) => (a.key > b.key) - (a.key < b.key)); return (dictionary, prefix, argument) => { - const type = webidl.util.Type(dictionary); const dict = {}; - if (type === "Null" || type === "Undefined") { - return dict; - } else if (type !== "Object") { + if (dictionary != null && webidl.util.Type(dictionary) !== OBJECT) { throw webidl.errors.exception({ header: prefix, message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` @@ -4118,17 +5275,17 @@ var require_webidl = __commonJS({ for (const options of converters) { const { key, defaultValue, required, converter } = options; if (required === true) { - if (!Object.hasOwn(dictionary, key)) { + if (dictionary == null || !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"); - if (hasDefault && value !== null) { - value ??= defaultValue(); + let value = dictionary?.[key]; + const hasDefault = defaultValue !== void 0; + if (hasDefault && value === void 0) { + value = defaultValue(); } if (required || hasDefault || value !== void 0) { value = converter(value, prefix, `${argument}.${key}`); @@ -4152,8 +5309,42 @@ var require_webidl = __commonJS({ return converter(V, prefix, argument); }; }; - webidl.converters.DOMString = function(V, prefix, argument, opts) { - if (V === null && opts?.legacyNullToEmptyString) { + webidl.is.USVString = function(value) { + return typeof value === "string" && value.isWellFormed(); + }; + webidl.is.ReadableStream = webidl.util.MakeTypeAssertion(ReadableStream); + webidl.is.Blob = webidl.util.MakeTypeAssertion(Blob); + webidl.is.URLSearchParams = webidl.util.MakeTypeAssertion(URLSearchParams); + webidl.is.File = webidl.util.MakeTypeAssertion(File); + webidl.is.URL = webidl.util.MakeTypeAssertion(URL); + webidl.is.AbortSignal = webidl.util.MakeTypeAssertion(AbortSignal); + webidl.is.MessagePort = webidl.util.MakeTypeAssertion(MessagePort); + webidl.is.BufferSource = function(V) { + return types2.isArrayBuffer(V) || ArrayBuffer.isView(V) && types2.isArrayBuffer(V.buffer); + }; + webidl.util.getCopyOfBytesHeldByBufferSource = function(bufferSource) { + const jsBufferSource = bufferSource; + let jsArrayBuffer = jsBufferSource; + let offset = 0; + let length = 0; + if (types2.isTypedArray(jsBufferSource) || types2.isDataView(jsBufferSource)) { + jsArrayBuffer = jsBufferSource.buffer; + offset = jsBufferSource.byteOffset; + length = jsBufferSource.byteLength; + } else { + assert(types2.isAnyArrayBuffer(jsBufferSource)); + length = jsBufferSource.byteLength; + } + if (jsArrayBuffer.detached) { + return new Uint8Array(0); + } + const bytes = new Uint8Array(length); + const view = new Uint8Array(jsArrayBuffer, offset, length); + bytes.set(view); + return bytes; + }; + webidl.converters.DOMString = function(V, prefix, argument, flags) { + if (V === null && webidl.util.HasFlag(flags, webidl.attributes.LegacyNullToEmptyString)) { return ""; } if (typeof V === "symbol") { @@ -4165,7 +5356,13 @@ var require_webidl = __commonJS({ return String(V); }; webidl.converters.ByteString = function(V, prefix, argument) { - const x = webidl.converters.DOMString(V, prefix, argument); + if (typeof V === "symbol") { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} is a symbol, which cannot be converted to a ByteString.` + }); + } + const x = String(V); for (let index2 = 0; index2 < x.length; index2++) { if (x.charCodeAt(index2) > 255) { throw new TypeError( @@ -4175,7 +5372,12 @@ var require_webidl = __commonJS({ } return x; }; - webidl.converters.USVString = toUSVString; + webidl.converters.USVString = function(value) { + if (typeof value === "string") { + return value.toWellFormed(); + } + return `${value}`.toWellFormed(); + }; webidl.converters.boolean = function(V) { const x = Boolean(V); return x; @@ -4184,100 +5386,154 @@ var require_webidl = __commonJS({ return V; }; webidl.converters["long long"] = function(V, prefix, argument) { - const x = webidl.util.ConvertToInt(V, 64, "signed", void 0, prefix, argument); + const x = webidl.util.ConvertToInt(V, 64, "signed", 0, prefix, argument); return x; }; webidl.converters["unsigned long long"] = function(V, prefix, argument) { - const x = webidl.util.ConvertToInt(V, 64, "unsigned", void 0, prefix, argument); + const x = webidl.util.ConvertToInt(V, 64, "unsigned", 0, prefix, argument); return x; }; webidl.converters["unsigned long"] = function(V, prefix, argument) { - const x = webidl.util.ConvertToInt(V, 32, "unsigned", void 0, prefix, argument); + const x = webidl.util.ConvertToInt(V, 32, "unsigned", 0, prefix, argument); return x; }; - webidl.converters["unsigned short"] = function(V, prefix, argument, opts) { - const x = webidl.util.ConvertToInt(V, 16, "unsigned", opts, prefix, argument); + webidl.converters["unsigned short"] = function(V, prefix, argument, flags) { + const x = webidl.util.ConvertToInt(V, 16, "unsigned", flags, prefix, argument); return x; }; - webidl.converters.ArrayBuffer = function(V, prefix, argument, opts) { - if (webidl.util.Type(V) !== "Object" || !types2.isAnyArrayBuffer(V)) { + webidl.converters.ArrayBuffer = function(V, prefix, argument, flags) { + if (webidl.util.Type(V) !== OBJECT || !types2.isArrayBuffer(V)) { throw webidl.errors.conversionFailed({ prefix, argument: `${argument} ("${webidl.util.Stringify(V)}")`, types: ["ArrayBuffer"] }); } - if (opts?.allowShared === false && types2.isSharedArrayBuffer(V)) { + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V)) { throw webidl.errors.exception({ - header: "ArrayBuffer", - message: "SharedArrayBuffer is not allowed." + header: prefix, + message: `${argument} cannot be a resizable ArrayBuffer.` }); } - if (V.resizable || V.growable) { + return V; + }; + webidl.converters.SharedArrayBuffer = function(V, prefix, argument, flags) { + if (webidl.util.Type(V) !== OBJECT || !types2.isSharedArrayBuffer(V)) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ["SharedArrayBuffer"] + }); + } + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V)) { throw webidl.errors.exception({ - header: "ArrayBuffer", - message: "Received a resizable ArrayBuffer." + header: prefix, + message: `${argument} cannot be a resizable SharedArrayBuffer.` }); } return V; }; - webidl.converters.TypedArray = function(V, T, prefix, name, opts) { - if (webidl.util.Type(V) !== "Object" || !types2.isTypedArray(V) || V.constructor.name !== T.name) { + webidl.converters.TypedArray = function(V, T, prefix, argument, flags) { + if (webidl.util.Type(V) !== OBJECT || !types2.isTypedArray(V) || V.constructor.name !== T.name) { throw webidl.errors.conversionFailed({ prefix, - argument: `${name} ("${webidl.util.Stringify(V)}")`, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, types: [T.name] }); } - if (opts?.allowShared === false && types2.isSharedArrayBuffer(V.buffer)) { + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types2.isSharedArrayBuffer(V.buffer)) { throw webidl.errors.exception({ - header: "ArrayBuffer", - message: "SharedArrayBuffer is not allowed." + header: prefix, + message: `${argument} cannot be a view on a shared array buffer.` }); } - if (V.buffer.resizable || V.buffer.growable) { + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) { throw webidl.errors.exception({ - header: "ArrayBuffer", - message: "Received a resizable ArrayBuffer." + header: prefix, + message: `${argument} cannot be a view on a resizable array buffer.` }); } return V; }; - webidl.converters.DataView = function(V, prefix, name, opts) { - if (webidl.util.Type(V) !== "Object" || !types2.isDataView(V)) { + webidl.converters.DataView = function(V, prefix, argument, flags) { + if (webidl.util.Type(V) !== OBJECT || !types2.isDataView(V)) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ["DataView"] + }); + } + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types2.isSharedArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: prefix, - message: `${name} is not a DataView.` + message: `${argument} cannot be a view on a shared array buffer.` }); } - if (opts?.allowShared === false && types2.isSharedArrayBuffer(V.buffer)) { + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) { throw webidl.errors.exception({ - header: "ArrayBuffer", - message: "SharedArrayBuffer is not allowed." + header: prefix, + message: `${argument} cannot be a view on a resizable array buffer.` }); } - if (V.buffer.resizable || V.buffer.growable) { + return V; + }; + webidl.converters.ArrayBufferView = function(V, prefix, argument, flags) { + if (webidl.util.Type(V) !== OBJECT || !types2.isArrayBufferView(V)) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ["ArrayBufferView"] + }); + } + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types2.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} cannot be a view on a shared array buffer.` + }); + } + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) { throw webidl.errors.exception({ - header: "ArrayBuffer", - message: "Received a resizable ArrayBuffer." + header: prefix, + message: `${argument} cannot be a view on a resizable array buffer.` }); } return V; }; - webidl.converters.BufferSource = function(V, prefix, name, opts) { - if (types2.isAnyArrayBuffer(V)) { - return webidl.converters.ArrayBuffer(V, prefix, name, { ...opts, allowShared: false }); + webidl.converters.BufferSource = function(V, prefix, argument, flags) { + if (types2.isArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, prefix, argument, flags); + } + if (types2.isArrayBufferView(V)) { + flags &= ~webidl.attributes.AllowShared; + return webidl.converters.ArrayBufferView(V, prefix, argument, flags); + } + if (types2.isSharedArrayBuffer(V)) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} cannot be a SharedArrayBuffer.` + }); + } + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ["ArrayBuffer", "ArrayBufferView"] + }); + }; + webidl.converters.AllowSharedBufferSource = function(V, prefix, argument, flags) { + if (types2.isArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, prefix, argument, flags); } - if (types2.isTypedArray(V)) { - return webidl.converters.TypedArray(V, V.constructor, prefix, name, { ...opts, allowShared: false }); + if (types2.isSharedArrayBuffer(V)) { + return webidl.converters.SharedArrayBuffer(V, prefix, argument, flags); } - if (types2.isDataView(V)) { - return webidl.converters.DataView(V, prefix, name, { ...opts, allowShared: false }); + if (types2.isArrayBufferView(V)) { + flags |= webidl.attributes.AllowShared; + return webidl.converters.ArrayBufferView(V, prefix, argument, flags); } throw webidl.errors.conversionFailed({ prefix, - argument: `${name} ("${webidl.util.Stringify(V)}")`, - types: ["BufferSource"] + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ["ArrayBuffer", "SharedArrayBuffer", "ArrayBufferView"] }); }; webidl.converters["sequence"] = webidl.sequenceConverter( @@ -4290,6 +5546,28 @@ var require_webidl = __commonJS({ webidl.converters.ByteString, webidl.converters.ByteString ); + webidl.converters.Blob = webidl.interfaceConverter(webidl.is.Blob, "Blob"); + webidl.converters.AbortSignal = webidl.interfaceConverter( + webidl.is.AbortSignal, + "AbortSignal" + ); + webidl.converters.EventHandlerNonNull = function(V) { + if (webidl.util.Type(V) !== OBJECT) { + return null; + } + if (typeof V === "function") { + return V; + } + return () => { + }; + }; + webidl.attributes = { + Clamp: 1 << 0, + EnforceRange: 1 << 1, + AllowShared: 1 << 2, + AllowResizable: 1 << 3, + LegacyNullToEmptyString: 1 << 4 + }; module2.exports = { webidl }; @@ -4302,22 +5580,15 @@ var require_util2 = __commonJS({ "use strict"; var { Transform: Transform5 } = require("node:stream"); var zlib3 = require("node:zlib"); - var { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require_constants3(); + var { redirectStatusSet, referrerPolicyTokens, badPortsSet } = require_constants3(); var { getGlobalOrigin } = require_global(); - var { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = require_data_url(); - var { performance: performance6 } = require("node:perf_hooks"); - var { isBlobLike, ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = require_util(); + var { collectAnHTTPQuotedString, parseMIMEType } = require_data_url(); + var { performance: performance8 } = require("node:perf_hooks"); + var { ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = require_util(); var assert = require("node:assert"); var { isUint8Array } = require("node:util/types"); var { webidl } = require_webidl(); - var supportedHashes = []; - var crypto3; - try { - crypto3 = require("node:crypto"); - const possibleRelevantHashes = ["sha256", "sha384", "sha512"]; - supportedHashes = crypto3.getHashes().filter((hash2) => possibleRelevantHashes.includes(hash2)); - } catch { - } + var { isomorphicEncode, collectASequenceOfCodePoints, removeChars } = require_infra(); function responseURL(response) { const urlList = response.urlList; const length = urlList.length; @@ -4380,11 +5651,10 @@ var require_util2 = __commonJS({ function isValidHeaderValue(potentialValue) { return (potentialValue[0] === " " || potentialValue[0] === " " || potentialValue[potentialValue.length - 1] === " " || potentialValue[potentialValue.length - 1] === " " || potentialValue.includes("\n") || potentialValue.includes("\r") || potentialValue.includes("\0")) === false; } - function setRequestReferrerPolicyOnRedirect(request3, actualResponse) { - const { headersList } = actualResponse; - const policyHeader = (headersList.get("referrer-policy", true) ?? "").split(","); + function parseReferrerPolicy(actualResponse) { + const policyHeader = (actualResponse.headersList.get("referrer-policy", true) ?? "").split(","); let policy = ""; - if (policyHeader.length > 0) { + if (policyHeader.length) { for (let i = policyHeader.length; i !== 0; i--) { const token = policyHeader[i - 1].trim(); if (referrerPolicyTokens.has(token)) { @@ -4393,6 +5663,10 @@ var require_util2 = __commonJS({ } } } + return policy; + } + function setRequestReferrerPolicyOnRedirect(request3, actualResponse) { + const policy = parseReferrerPolicy(actualResponse); if (policy !== "") { request3.referrerPolicy = policy; } @@ -4464,7 +5738,7 @@ var require_util2 = __commonJS({ }; } function coarsenedSharedCurrentTime(crossOriginIsolatedCapability) { - return coarsenTime(performance6.now(), crossOriginIsolatedCapability); + return coarsenTime(performance8.now(), crossOriginIsolatedCapability); } function createOpaqueTimingInfo(timingInfo) { return { @@ -4501,7 +5775,7 @@ var require_util2 = __commonJS({ return "no-referrer"; } referrerSource = new URL(globalOrigin); - } else if (request3.referrer instanceof URL) { + } else if (webidl.is.URL(request3.referrer)) { referrerSource = request3.referrer; } let referrerURL = stripURLForReferrer(referrerSource); @@ -4509,17 +5783,23 @@ var require_util2 = __commonJS({ if (referrerURL.toString().length > 4096) { referrerURL = referrerOrigin; } - const areSameOrigin = sameOrigin(request3, referrerURL); - const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(request3.url); switch (policy) { + case "no-referrer": + return "no-referrer"; case "origin": - return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true); + if (referrerOrigin != null) { + return referrerOrigin; + } + return 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": { + const currentURL = requestCurrentURL(request3); + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerOrigin; + } case "strict-origin-when-cross-origin": { const currentURL = requestCurrentURL(request3); if (sameOrigin(referrerURL, currentURL)) { @@ -4530,157 +5810,83 @@ var require_util2 = __commonJS({ } 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: - return isNonPotentiallyTrustWorthy ? "no-referrer" : referrerOrigin; + case "same-origin": + if (sameOrigin(request3, referrerURL)) { + return referrerURL; + } + return "no-referrer"; + case "origin-when-cross-origin": + if (sameOrigin(request3, referrerURL)) { + return referrerURL; + } + return referrerOrigin; + case "no-referrer-when-downgrade": { + const currentURL = requestCurrentURL(request3); + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerURL; + } } } - function stripURLForReferrer(url2, originOnly) { - assert(url2 instanceof URL); + function stripURLForReferrer(url2, originOnly = false) { + assert(webidl.is.URL(url2)); url2 = new URL(url2); - if (url2.protocol === "file:" || url2.protocol === "about:" || url2.protocol === "blank:") { + if (urlIsLocal(url2)) { return "no-referrer"; } url2.username = ""; url2.password = ""; url2.hash = ""; - if (originOnly) { + if (originOnly === true) { url2.pathname = ""; url2.search = ""; } return url2; } - function isURLPotentiallyTrustworthy(url2) { - if (!(url2 instanceof URL)) { + var isPotentialleTrustworthyIPv4 = RegExp.prototype.test.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/); + var isPotentiallyTrustworthyIPv6 = RegExp.prototype.test.bind(/^(?:(?:0{1,4}:){7}|(?:0{1,4}:){1,6}:|::)0{0,3}1$/); + function isOriginIPPotentiallyTrustworthy(origin) { + if (origin.includes(":")) { + if (origin[0] === "[" && origin[origin.length - 1] === "]") { + origin = origin.slice(1, -1); + } + return isPotentiallyTrustworthyIPv6(origin); + } + return isPotentialleTrustworthyIPv4(origin); + } + function isOriginPotentiallyTrustworthy(origin) { + if (origin == null || origin === "null") { return false; } - if (url2.href === "about:blank" || url2.href === "about:srcdoc") { + origin = new URL(origin); + if (origin.protocol === "https:" || origin.protocol === "wss:") { return true; } - if (url2.protocol === "data:") return true; - if (url2.protocol === "file:") return true; - return isOriginPotentiallyTrustworthy(url2.origin); - function isOriginPotentiallyTrustworthy(origin) { - if (origin == null || origin === "null") return false; - const originAsURL = new URL(origin); - if (originAsURL.protocol === "https:" || originAsURL.protocol === "wss:") { - 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; - } - return false; - } - } - function bytesMatch(bytes, metadataList) { - if (crypto3 === void 0) { + if (isOriginIPPotentiallyTrustworthy(origin.hostname)) { return true; } - const parsedMetadata = parseMetadata(metadataList); - if (parsedMetadata === "no metadata") { + if (origin.hostname === "localhost" || origin.hostname === "localhost.") { return true; } - if (parsedMetadata.length === 0) { + if (origin.hostname.endsWith(".localhost") || origin.hostname.endsWith(".localhost.")) { return true; } - const strongest = getStrongestMetadata(parsedMetadata); - const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest); - for (const item of metadata) { - const algorithm = item.algo; - const expectedValue = item.hash; - let actualValue = crypto3.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); - } - } - if (compareBase64Mixed(actualValue, expectedValue)) { - return true; - } + if (origin.protocol === "file:") { + return true; } return false; } - var parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i; - function parseMetadata(metadata) { - const result = []; - let empty = true; - for (const token of metadata.split(" ")) { - empty = false; - const parsedToken = parseHashWithOptions.exec(token); - if (parsedToken === null || parsedToken.groups === void 0 || parsedToken.groups.algo === void 0) { - continue; - } - const algorithm = parsedToken.groups.algo.toLowerCase(); - if (supportedHashes.includes(algorithm)) { - result.push(parsedToken.groups); - } - } - if (empty === true) { - return "no metadata"; - } - return result; - } - function getStrongestMetadata(metadataList) { - let algorithm = metadataList[0].algo; - if (algorithm[3] === "5") { - return algorithm; - } - for (let i = 1; i < metadataList.length; ++i) { - const metadata = metadataList[i]; - if (metadata.algo[3] === "5") { - algorithm = "sha512"; - break; - } else if (algorithm[3] === "3") { - continue; - } 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; - } - function compareBase64Mixed(actualValue, expectedValue) { - if (actualValue.length !== expectedValue.length) { + function isURLPotentiallyTrustworthy(url2) { + if (!webidl.is.URL(url2)) { 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; - } + if (url2.href === "about:blank" || url2.href === "about:srcdoc") { + return true; } - return true; + if (url2.protocol === "data:") return true; + if (url2.protocol === "blob:") return true; + return isOriginPotentiallyTrustworthy(url2.origin); } function tryUpgradeRequestToAPotentiallyTrustworthyURL(request3) { } @@ -4693,15 +5899,6 @@ var require_util2 = __commonJS({ } return false; } - function createDeferredPromise() { - let res; - let rej; - const promise = new Promise((resolve14, reject) => { - res = resolve14; - rej = reject; - }); - return { promise, resolve: res, reject: rej }; - } function isAborted(fetchParams) { return fetchParams.controller.state === "aborted"; } @@ -4711,14 +5908,6 @@ var require_util2 = __commonJS({ function normalizeMethod(method) { return normalizedMethodRecordsBase[method.toLowerCase()] ?? method; } - function serializeJavascriptValueToJSONString(value) { - const result = JSON.stringify(value); - if (result === void 0) { - throw new TypeError("Value is not JSON serializable"); - } - assert(typeof result === "string"); - return result; - } var esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())); function createIterator(name, kInternalIterator, keyIndex = 0, valueIndex = 1) { class FastIterableIterator { @@ -4745,7 +5934,7 @@ var require_util2 = __commonJS({ ); } const index2 = this.#index; - const values = this.#target[kInternalIterator]; + const values = kInternalIterator(this.#target); const len = values.length; if (index2 >= len) { return { @@ -4846,25 +6035,16 @@ var require_util2 = __commonJS({ } }); } - async function fullyReadBody(body, processBody, processBodyError) { + function fullyReadBody(body, processBody, processBodyError) { const successSteps = processBody; const errorSteps = processBodyError; - let reader; try { - reader = body.stream.getReader(); - } catch (e) { - errorSteps(e); - return; - } - try { - successSteps(await readAllBytes(reader)); + const reader = body.stream.getReader(); + readAllBytes(reader, successSteps, errorSteps); } catch (e) { errorSteps(e); } } - function isReadableStreamLike(stream2) { - return stream2 instanceof ReadableStream || stream2[Symbol.toStringTag] === "ReadableStream" && typeof stream2.tee === "function"; - } function readableStreamClose(controller) { try { controller.close(); @@ -4875,24 +6055,25 @@ var require_util2 = __commonJS({ } } } - var invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/; - function isomorphicEncode(input) { - assert(!invalidIsomorphicEncodeValueRegex.test(input)); - return input; - } - async function readAllBytes(reader) { - const bytes = []; - let byteLength = 0; - while (true) { - const { done, value: chunk } = await reader.read(); - if (done) { - return Buffer.concat(bytes, byteLength); - } - if (!isUint8Array(chunk)) { - throw new TypeError("Received non-Uint8Array chunk"); - } - bytes.push(chunk); - byteLength += chunk.length; + async function readAllBytes(reader, successSteps, failureSteps) { + try { + const bytes = []; + let byteLength = 0; + do { + const { done, value: chunk } = await reader.read(); + if (done) { + successSteps(Buffer.concat(bytes, byteLength)); + return; + } + if (!isUint8Array(chunk)) { + failureSteps(new TypeError("Received non-Uint8Array chunk")); + return; + } + bytes.push(chunk); + byteLength += chunk.length; + } while (true); + } catch (e) { + failureSteps(e); } } function urlIsLocal(url2) { @@ -5086,16 +6267,14 @@ var require_util2 = __commonJS({ } return gettingDecodingSplitting(value); } - var textDecoder = new TextDecoder(); - function utf8DecodeBytes(buffer) { - if (buffer.length === 0) { - return ""; - } - if (buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191) { - buffer = buffer.subarray(3); - } - const output = textDecoder.decode(buffer); - return output; + function hasAuthenticationEntry(request3) { + return false; + } + function includesCredentials(url2) { + return !!(url2.username || url2.password); + } + function isTraversableNavigable(navigable) { + return navigable != null && navigable !== "client" && navigable !== "no-traversable"; } var EnvironmentSettingsObjectBase = class { get baseUrl() { @@ -5114,7 +6293,6 @@ var require_util2 = __commonJS({ isAborted, isCancelled, isValidEncodedURL, - createDeferredPromise, ReadableStreamFrom, tryUpgradeRequestToAPotentiallyTrustworthyURL, clampAndCoarsenConnectionTimingInfo, @@ -5134,129 +6312,46 @@ var require_util2 = __commonJS({ 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 - }; - } -}); - -// node_modules/undici/lib/web/fetch/symbols.js -var require_symbols2 = __commonJS({ - "node_modules/undici/lib/web/fetch/symbols.js"(exports2, module2) { - "use strict"; - module2.exports = { - kUrl: /* @__PURE__ */ Symbol("url"), - kHeaders: /* @__PURE__ */ Symbol("headers"), - kSignal: /* @__PURE__ */ Symbol("signal"), - kState: /* @__PURE__ */ Symbol("state"), - kDispatcher: /* @__PURE__ */ Symbol("dispatcher") + environmentSettingsObject, + isOriginIPPotentiallyTrustworthy, + hasAuthenticationEntry, + includesCredentials, + isTraversableNavigable }; } }); -// node_modules/undici/lib/web/fetch/file.js -var require_file = __commonJS({ - "node_modules/undici/lib/web/fetch/file.js"(exports2, module2) { - "use strict"; - var { Blob: Blob2, File: File2 } = require("node:buffer"); - var { kState } = require_symbols2(); - var { webidl } = require_webidl(); - var FileLike = class _FileLike { - constructor(blobLike, fileName, options = {}) { - const n = fileName; - const t = options.type; - const d = options.lastModified ?? Date.now(); - 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(Blob2); - function isFileLike(object2) { - return object2 instanceof File2 || object2 && (typeof object2.stream === "function" || typeof object2.arrayBuffer === "function") && object2[Symbol.toStringTag] === "File"; - } - module2.exports = { FileLike, isFileLike }; - } -}); - // node_modules/undici/lib/web/fetch/formdata.js var require_formdata = __commonJS({ "node_modules/undici/lib/web/fetch/formdata.js"(exports2, module2) { "use strict"; - var { isBlobLike, iteratorMixin } = require_util2(); - var { kState } = require_symbols2(); + var { iteratorMixin } = require_util2(); var { kEnumerableProperty } = require_util(); - var { FileLike, isFileLike } = require_file(); var { webidl } = require_webidl(); - var { File: NativeFile } = require("node:buffer"); var nodeUtil = require("node:util"); - var File2 = globalThis.File ?? NativeFile; var FormData2 = class _FormData { - constructor(form) { + #state = []; + constructor(form = void 0) { webidl.util.markAsUncloneable(this); if (form !== void 0) { throw webidl.errors.conversionFailed({ @@ -5265,81 +6360,82 @@ var require_formdata = __commonJS({ types: ["undefined"] }); } - this[kState] = []; } append(name, value, filename = void 0) { 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'" - ); + name = webidl.converters.USVString(name); + if (arguments.length === 3 || webidl.is.Blob(value)) { + value = webidl.converters.Blob(value, prefix, "value"); + if (filename !== void 0) { + filename = webidl.converters.USVString(filename); + } + } else { + value = webidl.converters.USVString(value); } - 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") : void 0; const entry = makeEntry(name, value, filename); - this[kState].push(entry); + this.#state.push(entry); } delete(name) { webidl.brandCheck(this, _FormData); const prefix = "FormData.delete"; webidl.argumentLengthCheck(arguments, 1, prefix); - name = webidl.converters.USVString(name, prefix, "name"); - this[kState] = this[kState].filter((entry) => entry.name !== name); + name = webidl.converters.USVString(name); + this.#state = this.#state.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"); - const idx = this[kState].findIndex((entry) => entry.name === name); + name = webidl.converters.USVString(name); + const idx = this.#state.findIndex((entry) => entry.name === name); if (idx === -1) { return null; } - return this[kState][idx].value; + return this.#state[idx].value; } getAll(name) { webidl.brandCheck(this, _FormData); const prefix = "FormData.getAll"; webidl.argumentLengthCheck(arguments, 1, prefix); - name = webidl.converters.USVString(name, prefix, "name"); - return this[kState].filter((entry) => entry.name === name).map((entry) => entry.value); + name = webidl.converters.USVString(name); + return this.#state.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"); - return this[kState].findIndex((entry) => entry.name === name) !== -1; + name = webidl.converters.USVString(name); + return this.#state.findIndex((entry) => entry.name === name) !== -1; } set(name, value, filename = void 0) { 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'" - ); + name = webidl.converters.USVString(name); + if (arguments.length === 3 || webidl.is.Blob(value)) { + value = webidl.converters.Blob(value, prefix, "value"); + if (filename !== void 0) { + filename = webidl.converters.USVString(filename); + } + } else { + value = webidl.converters.USVString(value); } - 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") : void 0; const entry = makeEntry(name, value, filename); - const idx = this[kState].findIndex((entry2) => entry2.name === name); + const idx = this.#state.findIndex((entry2) => entry2.name === name); if (idx !== -1) { - this[kState] = [ - ...this[kState].slice(0, idx), + this.#state = [ + ...this.#state.slice(0, idx), entry, - ...this[kState].slice(idx + 1).filter((entry2) => entry2.name !== name) + ...this.#state.slice(idx + 1).filter((entry2) => entry2.name !== name) ]; } else { - this[kState].push(entry); + this.#state.push(entry); } } [nodeUtil.inspect.custom](depth, options) { - const state = this[kState].reduce((a, b) => { + const state = this.#state.reduce((a, b) => { if (a[b.name]) { if (Array.isArray(a[b.name])) { a[b.name].push(b.value); @@ -5356,8 +6452,24 @@ var require_formdata = __commonJS({ const output = nodeUtil.formatWithOptions(options, state); return `FormData ${output.slice(output.indexOf("]") + 2)}`; } + /** + * @param {FormData} formData + */ + static getFormDataState(formData) { + return formData.#state; + } + /** + * @param {FormData} formData + * @param {any[]} newState + */ + static setFormDataState(formData, newState) { + formData.#state = newState; + } }; - iteratorMixin("FormData", FormData2, kState, "name", "value"); + var { getFormDataState, setFormDataState } = FormData2; + Reflect.deleteProperty(FormData2, "getFormDataState"); + Reflect.deleteProperty(FormData2, "setFormDataState"); + iteratorMixin("FormData", FormData2, getFormDataState, "name", "value"); Object.defineProperties(FormData2.prototype, { append: kEnumerableProperty, delete: kEnumerableProperty, @@ -5373,20 +6485,21 @@ var require_formdata = __commonJS({ function makeEntry(name, value, filename) { if (typeof value === "string") { } else { - if (!isFileLike(value)) { - value = value instanceof Blob ? new File2([value], "blob", { type: value.type }) : new FileLike(value, "blob", { type: value.type }); + if (!webidl.is.File(value)) { + value = new File([value], "blob", { type: value.type }); } if (filename !== void 0) { const options = { type: value.type, lastModified: value.lastModified }; - value = value instanceof NativeFile ? new File2([value], filename, options) : new FileLike(value, filename, options); + value = new File([value], filename, options); } } return { name, value }; } - module2.exports = { FormData: FormData2, makeEntry }; + webidl.is.FormData = webidl.util.MakeTypeAssertion(FormData2); + module2.exports = { FormData: FormData2, makeEntry, setFormDataState }; } }); @@ -5394,18 +6507,15 @@ var require_formdata = __commonJS({ var require_formdata_parser = __commonJS({ "node_modules/undici/lib/web/fetch/formdata-parser.js"(exports2, module2) { "use strict"; - var { isUSVString, bufferToLowerCasedHeaderName } = require_util(); - var { utf8DecodeBytes } = require_util2(); - var { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = require_data_url(); - var { isFileLike } = require_file(); + var { bufferToLowerCasedHeaderName } = require_util(); + var { HTTP_TOKEN_CODEPOINTS } = require_data_url(); var { makeEntry } = require_formdata(); + var { webidl } = require_webidl(); var assert = require("node:assert"); - var { File: NodeFile } = require("node:buffer"); - var File2 = globalThis.File ?? NodeFile; - var formDataNameBuffer = Buffer.from('form-data; name="'); - var filenameBuffer = Buffer.from("; filename"); + var { isomorphicDecode } = require_infra(); var dd = Buffer.from("--"); - var ddcrlf = Buffer.from("--\r\n"); + var decoder2 = new TextDecoder(); + var decoderIgnoreBOM = new TextDecoder("utf-8", { ignoreBOM: true }); function isAsciiString(chars) { for (let i = 0; i < chars.length; ++i) { if ((chars.charCodeAt(i) & ~127) !== 0) { @@ -5431,45 +6541,37 @@ var require_formdata_parser = __commonJS({ assert(mimeType !== "failure" && mimeType.essence === "multipart/form-data"); const boundaryString = mimeType.parameters.get("boundary"); if (boundaryString === void 0) { - return "failure"; + throw parsingError("missing boundary in content-type header"); } const boundary = Buffer.from(`--${boundaryString}`, "utf8"); const entryList = []; const position = { position: 0 }; - while (input[position.position] === 13 && input[position.position + 1] === 10) { - position.position += 2; - } - let trailing = input.length; - while (input[trailing - 1] === 10 && input[trailing - 2] === 13) { - trailing -= 2; - } - if (trailing !== input.length) { - input = input.subarray(0, trailing); + const firstBoundaryIndex = input.indexOf(boundary); + if (firstBoundaryIndex === -1) { + throw parsingError("no boundary found in multipart body"); } + position.position = firstBoundaryIndex; while (true) { if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) { position.position += boundary.length; } else { - return "failure"; + throw parsingError("expected a value starting with -- and the boundary"); } - if (position.position === input.length - 2 && bufferStartsWith(input, dd, position) || position.position === input.length - 4 && bufferStartsWith(input, ddcrlf, position)) { + if (bufferStartsWith(input, dd, position)) { return entryList; } if (input[position.position] !== 13 || input[position.position + 1] !== 10) { - return "failure"; + throw parsingError("expected CRLF"); } position.position += 2; const result = parseMultipartFormDataHeaders(input, position); - if (result === "failure") { - return "failure"; - } let { name, filename, contentType, encoding } = result; position.position += 2; let body; { const boundaryIndex = input.indexOf(boundary.subarray(2), position.position); if (boundaryIndex === -1) { - return "failure"; + throw parsingError("expected boundary after body"); } body = input.subarray(position.position, boundaryIndex - 4); position.position += body.length; @@ -5478,7 +6580,7 @@ var require_formdata_parser = __commonJS({ } } if (input[position.position] !== 13 || input[position.position + 1] !== 10) { - return "failure"; + throw parsingError("expected CRLF"); } else { position.position += 2; } @@ -5488,15 +6590,87 @@ var require_formdata_parser = __commonJS({ if (!isAsciiString(contentType)) { contentType = ""; } - value = new File2([body], filename, { type: contentType }); + value = new File([body], filename, { type: contentType }); } else { - value = utf8DecodeBytes(Buffer.from(body)); + value = decoderIgnoreBOM.decode(Buffer.from(body)); } - assert(isUSVString(name)); - assert(typeof value === "string" && isUSVString(value) || isFileLike(value)); + assert(webidl.is.USVString(name)); + assert(typeof value === "string" && webidl.is.USVString(value) || webidl.is.File(value)); entryList.push(makeEntry(name, value, filename)); } } + function parseContentDispositionAttribute(input, position) { + if (input[position.position] === 59) { + position.position++; + } + collectASequenceOfBytes( + (char) => char === 32 || char === 9, + input, + position + ); + const attributeName = collectASequenceOfBytes( + (char) => isToken2(char) && char !== 61 && char !== 42, + // not = or * + input, + position + ); + if (attributeName.length === 0) { + return null; + } + const attrNameStr = attributeName.toString("ascii").toLowerCase(); + const isExtended = input[position.position] === 42; + if (isExtended) { + position.position++; + } + if (input[position.position] !== 61) { + return null; + } + position.position++; + collectASequenceOfBytes( + (char) => char === 32 || char === 9, + input, + position + ); + let value; + if (isExtended) { + const headerValue = collectASequenceOfBytes( + (char) => char !== 32 && char !== 13 && char !== 10 && char !== 59, + // not space, CRLF, or ; + input, + position + ); + if (headerValue[0] !== 117 && headerValue[0] !== 85 || // u or U + headerValue[1] !== 116 && headerValue[1] !== 84 || // t or T + headerValue[2] !== 102 && headerValue[2] !== 70 || // f or F + headerValue[3] !== 45 || // - + headerValue[4] !== 56) { + throw parsingError("unknown encoding, expected utf-8''"); + } + value = decodeURIComponent(decoder2.decode(headerValue.subarray(7))); + } else if (input[position.position] === 34) { + position.position++; + const quotedValue = collectASequenceOfBytes( + (char) => char !== 10 && char !== 13 && char !== 34, + // not LF, CR, or " + input, + position + ); + if (input[position.position] !== 34) { + throw parsingError("Closing quote not found"); + } + position.position++; + value = decoder2.decode(quotedValue).replace(/%0A/ig, "\n").replace(/%0D/ig, "\r").replace(/%22/g, '"'); + } else { + const tokenValue = collectASequenceOfBytes( + (char) => isToken2(char) && char !== 59, + // not ; + input, + position + ); + value = decoder2.decode(tokenValue); + } + return { name: attrNameStr, value, extended: isExtended }; + } function parseMultipartFormDataHeaders(input, position) { let name = null; let filename = null; @@ -5505,7 +6679,7 @@ var require_formdata_parser = __commonJS({ while (true) { if (input[position.position] === 13 && input[position.position + 1] === 10) { if (name === null) { - return "failure"; + throw parsingError("header name is null"); } return { name, filename, contentType, encoding }; } @@ -5516,10 +6690,10 @@ var require_formdata_parser = __commonJS({ ); headerName = removeChars(headerName, true, true, (char) => char === 9 || char === 32); if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) { - return "failure"; + throw parsingError("header name does not match the field-name token production"); } if (input[position.position] !== 58) { - return "failure"; + throw parsingError("expected :"); } position.position++; collectASequenceOfBytes( @@ -5530,29 +6704,34 @@ var require_formdata_parser = __commonJS({ switch (bufferToLowerCasedHeaderName(headerName)) { case "content-disposition": { name = filename = null; - if (!bufferStartsWith(input, formDataNameBuffer, position)) { - return "failure"; - } - position.position += 17; - name = parseMultipartFormDataName(input, position); - if (name === null) { - return "failure"; + let filenameIsExtended = false; + const dispositionType = collectASequenceOfBytes( + (char) => isToken2(char), + input, + position + ); + if (dispositionType.toString("ascii").toLowerCase() !== "form-data") { + throw parsingError("expected form-data for content-disposition header"); } - if (bufferStartsWith(input, filenameBuffer, position)) { - let check = position.position + filenameBuffer.length; - if (input[check] === 42) { - position.position += 1; - check += 1; - } - if (input[check] !== 61 || input[check + 1] !== 34) { - return "failure"; + while (position.position < input.length && (input[position.position] !== 13 || input[position.position + 1] !== 10)) { + const attribute = parseContentDispositionAttribute(input, position); + if (!attribute) { + break; } - position.position += 12; - filename = parseMultipartFormDataName(input, position); - if (filename === null) { - return "failure"; + if (attribute.name === "name") { + name = attribute.value; + } else if (attribute.name === "filename") { + if (attribute.extended) { + filename = attribute.value; + filenameIsExtended = true; + } else if (!filenameIsExtended) { + filename = attribute.value; + } } } + if (name === null) { + throw parsingError("name attribute is required in content-disposition header"); + } break; } case "content-type": { @@ -5583,28 +6762,13 @@ var require_formdata_parser = __commonJS({ ); } } - if (input[position.position] !== 13 && input[position.position + 1] !== 10) { - return "failure"; + if (input[position.position] !== 13 || input[position.position + 1] !== 10) { + throw parsingError("expected CRLF"); } else { position.position += 2; } } } - function parseMultipartFormDataName(input, position) { - assert(input[position.position - 1] === 34); - let name = collectASequenceOfBytes( - (char) => char !== 10 && char !== 13 && char !== 34, - input, - position - ); - if (input[position.position] !== 34) { - return null; - } else { - position.position++; - } - name = new TextDecoder().decode(name).replace(/%0A/ig, "\n").replace(/%0D/ig, "\r").replace(/%22/g, '"'); - return name; - } function collectASequenceOfBytes(condition, input, position) { let start = position.position; while (start < input.length && condition(input[start])) { @@ -5634,6 +6798,34 @@ var require_formdata_parser = __commonJS({ } return true; } + function parsingError(cause) { + return new TypeError("Failed to parse body as FormData.", { cause: new TypeError(cause) }); + } + function isCTL(char) { + return char <= 31 || char === 127; + } + function isTSpecial(char) { + return char === 40 || // ( + char === 41 || // ) + char === 60 || // < + char === 62 || // > + char === 64 || // @ + char === 44 || // , + char === 59 || // ; + char === 58 || // : + char === 92 || // \ + char === 34 || // " + char === 47 || // / + char === 91 || // [ + char === 93 || // ] + char === 63 || // ? + char === 61; + } + function isToken2(char) { + return char <= 127 && // ascii + char !== 32 && // space + char !== 9 && !isCTL(char) && !isTSpecial(char); + } module2.exports = { multipartFormDataParser, validateBoundary @@ -5641,71 +6833,77 @@ var require_formdata_parser = __commonJS({ } }); +// node_modules/undici/lib/util/promise.js +var require_promise = __commonJS({ + "node_modules/undici/lib/util/promise.js"(exports2, module2) { + "use strict"; + function createDeferredPromise() { + let res; + let rej; + const promise = new Promise((resolve15, reject) => { + res = resolve15; + rej = reject; + }); + return { promise, resolve: res, reject: rej }; + } + module2.exports = { + createDeferredPromise + }; + } +}); + // node_modules/undici/lib/web/fetch/body.js var require_body = __commonJS({ "node_modules/undici/lib/web/fetch/body.js"(exports2, module2) { "use strict"; - var util3 = require_util(); + var util4 = require_util(); var { ReadableStreamFrom, - isBlobLike, - isReadableStreamLike, readableStreamClose, - createDeferredPromise, fullyReadBody, - extractMimeType, - utf8DecodeBytes + extractMimeType } = require_util2(); - var { FormData: FormData2 } = require_formdata(); - var { kState } = require_symbols2(); + var { FormData: FormData2, setFormDataState } = require_formdata(); var { webidl } = require_webidl(); - var { Blob: Blob2 } = require("node:buffer"); var assert = require("node:assert"); var { isErrored, isDisturbed } = require("node:stream"); - var { isArrayBuffer } = require("node:util/types"); + var { isUint8Array } = require("node:util/types"); var { serializeAMimeType } = require_data_url(); var { multipartFormDataParser } = require_formdata_parser(); - var random; - try { - const crypto3 = require("node:crypto"); - random = (max) => crypto3.randomInt(0, max); - } catch { - random = (max) => Math.floor(Math.random(max)); - } + var { createDeferredPromise } = require_promise(); + var { parseJSONFromBytes } = require_infra(); + var { utf8DecodeBytes } = require_encoding(); + var { runtimeFeatures } = require_runtime_features(); + var random = runtimeFeatures.has("crypto") ? require("node:crypto").randomInt : (max) => Math.floor(Math.random() * max); var textEncoder = new TextEncoder(); function noop3() { } - var hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf("v18") !== 0; - var streamRegistry; - if (hasFinalizationRegistry) { - streamRegistry = new FinalizationRegistry((weakRef) => { - const stream2 = weakRef.deref(); - if (stream2 && !stream2.locked && !isDisturbed(stream2) && !isErrored(stream2)) { - stream2.cancel("Response object has been garbage collected").catch(noop3); - } - }); - } + var streamRegistry = new FinalizationRegistry((weakRef) => { + const stream2 = weakRef.deref(); + if (stream2 && !stream2.locked && !isDisturbed(stream2) && !isErrored(stream2)) { + stream2.cancel("Response object has been garbage collected").catch(noop3); + } + }); function extractBody(object2, keepalive = false) { let stream2 = null; - if (object2 instanceof ReadableStream) { + let controller = null; + if (webidl.is.ReadableStream(object2)) { stream2 = object2; - } else if (isBlobLike(object2)) { + } else if (webidl.is.Blob(object2)) { stream2 = object2.stream(); } else { stream2 = new ReadableStream({ - async pull(controller) { - const buffer = typeof source === "string" ? textEncoder.encode(source) : source; - if (buffer.byteLength) { - controller.enqueue(buffer); - } - queueMicrotask(() => readableStreamClose(controller)); + pull() { }, - start() { + start(c) { + controller = c; + }, + cancel() { }, type: "bytes" }); } - assert(isReadableStreamLike(stream2)); + assert(webidl.is.ReadableStream(stream2)); let action = null; let source = null; let length = null; @@ -5713,18 +6911,16 @@ var require_body = __commonJS({ if (typeof object2 === "string") { source = object2; type = "text/plain;charset=UTF-8"; - } else if (object2 instanceof URLSearchParams) { + } else if (webidl.is.URLSearchParams(object2)) { source = object2.toString(); type = "application/x-www-form-urlencoded;charset=UTF-8"; - } else if (isArrayBuffer(object2)) { - source = new Uint8Array(object2.slice()); - } else if (ArrayBuffer.isView(object2)) { - source = new Uint8Array(object2.buffer.slice(object2.byteOffset, object2.byteOffset + object2.byteLength)); - } else if (util3.isFormDataLike(object2)) { + } else if (webidl.is.BufferSource(object2)) { + source = webidl.util.getCopyOfBytesHeldByBufferSource(object2); + } else if (webidl.is.FormData(object2)) { const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, "0")}`; const prefix = `--${boundary}\r Content-Disposition: form-data`; - const escape3 = (str) => str.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); + const formdataEscape = (str) => str.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, "\r\n"); const blobParts = []; const rn = new Uint8Array([13, 10]); @@ -5732,14 +6928,14 @@ Content-Disposition: form-data`; let hasUnknownSizeValue = false; for (const [name, value] of object2) { if (typeof value === "string") { - const chunk2 = textEncoder.encode(prefix + `; name="${escape3(normalizeLinefeeds(name))}"\r + const chunk2 = textEncoder.encode(prefix + `; name="${formdataEscape(normalizeLinefeeds(name))}"\r \r ${normalizeLinefeeds(value)}\r `); blobParts.push(chunk2); length += chunk2.byteLength; } else { - const chunk2 = textEncoder.encode(`${prefix}; name="${escape3(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape3(value.name)}"` : "") + `\r + const chunk2 = textEncoder.encode(`${prefix}; name="${formdataEscape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${formdataEscape(value.name)}"` : "") + `\r Content-Type: ${value.type || "application/octet-stream"}\r \r `); @@ -5769,7 +6965,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r } }; type = `multipart/form-data; boundary=${boundary}`; - } else if (isBlobLike(object2)) { + } else if (webidl.is.Blob(object2)) { source = object2; length = object2.size; if (object2.type) { @@ -5779,57 +6975,49 @@ Content-Type: ${value.type || "application/octet-stream"}\r if (keepalive) { throw new TypeError("keepalive"); } - if (util3.isDisturbed(object2) || object2.locked) { + if (util4.isDisturbed(object2) || object2.locked) { throw new TypeError( "Response body object should not be disturbed or locked" ); } - stream2 = object2 instanceof ReadableStream ? object2 : ReadableStreamFrom(object2); + stream2 = webidl.is.ReadableStream(object2) ? object2 : ReadableStreamFrom(object2); } - if (typeof source === "string" || util3.isBuffer(source)) { - length = Buffer.byteLength(source); + if (typeof source === "string" || isUint8Array(source)) { + action = () => { + length = typeof source === "string" ? Buffer.byteLength(source) : source.length; + return source; + }; } if (action != null) { - let iterator2; - stream2 = new ReadableStream({ - async start() { - iterator2 = action(object2)[Symbol.asyncIterator](); - }, - async pull(controller) { - const { value, done } = await iterator2.next(); - if (done) { - queueMicrotask(() => { - controller.close(); - controller.byobRequest?.respond(0); - }); - } else { - if (!isErrored(stream2)) { - const buffer = new Uint8Array(value); - if (buffer.byteLength) { - controller.enqueue(buffer); - } + ; + (async () => { + const result = action(); + const iterator2 = result?.[Symbol.asyncIterator]?.(); + if (iterator2) { + for await (const bytes of iterator2) { + if (isErrored(stream2)) break; + if (bytes.length) { + controller.enqueue(new Uint8Array(bytes)); } } - return controller.desiredSize > 0; - }, - async cancel(reason) { - await iterator2.return(); - }, - type: "bytes" - }); + } else if (result?.length && !isErrored(stream2)) { + controller.enqueue(typeof result === "string" ? textEncoder.encode(result) : new Uint8Array(result)); + } + queueMicrotask(() => readableStreamClose(controller)); + })(); } const body = { stream: stream2, source, length }; return [body, type]; } function safelyExtractBody(object2, keepalive = false) { - if (object2 instanceof ReadableStream) { - assert(!util3.isDisturbed(object2), "The body has already been consumed."); + if (webidl.is.ReadableStream(object2)) { + assert(!util4.isDisturbed(object2), "The body has already been consumed."); assert(!object2.locked, "The stream is locked."); } return extractBody(object2, keepalive); } - function cloneBody(instance, body) { - const [out1, out2] = body.stream.tee(); + function cloneBody(body) { + const { 0: out1, 1: out2 } = body.stream.tee(); body.stream = out1; return { stream: out2, @@ -5837,47 +7025,39 @@ Content-Type: ${value.type || "application/octet-stream"}\r source: body.source }; } - function throwIfAborted(state) { - if (state.aborted) { - throw new DOMException("The operation was aborted.", "AbortError"); - } - } - function bodyMixinMethods(instance) { + function bodyMixinMethods(instance8, getInternalState) { const methods = { blob() { return consumeBody(this, (bytes) => { - let mimeType = bodyMimeType(this); + let mimeType = bodyMimeType(getInternalState(this)); if (mimeType === null) { mimeType = ""; } else if (mimeType) { mimeType = serializeAMimeType(mimeType); } - return new Blob2([bytes], { type: mimeType }); - }, instance); + return new Blob([bytes], { type: mimeType }); + }, instance8, getInternalState); }, arrayBuffer() { return consumeBody(this, (bytes) => { return new Uint8Array(bytes).buffer; - }, instance); + }, instance8, getInternalState); }, text() { - return consumeBody(this, utf8DecodeBytes, instance); + return consumeBody(this, utf8DecodeBytes, instance8, getInternalState); }, json() { - return consumeBody(this, parseJSONFromBytes, instance); + return consumeBody(this, parseJSONFromBytes, instance8, getInternalState); }, formData() { return consumeBody(this, (value) => { - const mimeType = bodyMimeType(this); + const mimeType = bodyMimeType(getInternalState(this)); if (mimeType !== null) { switch (mimeType.essence) { case "multipart/form-data": { const parsed = multipartFormDataParser(value, mimeType); - if (parsed === "failure") { - throw new TypeError("Failed to parse body as FormData."); - } const fd = new FormData2(); - fd[kState] = parsed; + setFormDataState(fd, parsed); return fd; } case "application/x-www-form-urlencoded": { @@ -5893,27 +7073,31 @@ Content-Type: ${value.type || "application/octet-stream"}\r throw new TypeError( 'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".' ); - }, instance); + }, instance8, getInternalState); }, bytes() { return consumeBody(this, (bytes) => { return new Uint8Array(bytes); - }, instance); + }, instance8, getInternalState); } }; return methods; } - function mixinBody(prototype) { - Object.assign(prototype.prototype, bodyMixinMethods(prototype)); + function mixinBody(prototype, getInternalState) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype, getInternalState)); } - async function consumeBody(object2, convertBytesToJSValue, instance) { - webidl.brandCheck(object2, instance); + function consumeBody(object2, convertBytesToJSValue, instance8, getInternalState) { + try { + webidl.brandCheck(object2, instance8); + } catch (e) { + return Promise.reject(e); + } + object2 = getInternalState(object2); if (bodyUnusable(object2)) { - throw new TypeError("Body is unusable: Body has already been read"); + return Promise.reject(new TypeError("Body is unusable: Body has already been read")); } - throwIfAborted(object2[kState]); const promise = createDeferredPromise(); - const errorSteps = (error3) => promise.reject(error3); + const errorSteps = promise.reject; const successSteps = (data) => { try { promise.resolve(convertBytesToJSValue(data)); @@ -5921,22 +7105,19 @@ Content-Type: ${value.type || "application/octet-stream"}\r errorSteps(e); } }; - if (object2[kState].body == null) { + if (object2.body == null) { successSteps(Buffer.allocUnsafe(0)); return promise.promise; } - await fullyReadBody(object2[kState].body, successSteps, errorSteps); + fullyReadBody(object2.body, successSteps, errorSteps); return promise.promise; } function bodyUnusable(object2) { - const body = object2[kState].body; - return body != null && (body.stream.locked || util3.isDisturbed(body.stream)); - } - function parseJSONFromBytes(bytes) { - return JSON.parse(utf8DecodeBytes(bytes)); + const body = object2.body; + return body != null && (body.stream.locked || util4.isDisturbed(body.stream)); } function bodyMimeType(requestOrResponse) { - const headers = requestOrResponse[kState].headersList; + const headers = requestOrResponse.headersList; const mimeType = extractMimeType(headers); if (mimeType === "failure") { return null; @@ -5949,7 +7130,6 @@ Content-Type: ${value.type || "application/octet-stream"}\r cloneBody, mixinBody, streamRegistry, - hasFinalizationRegistry, bodyUnusable }; } @@ -5960,7 +7140,7 @@ var require_client_h1 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h1.js"(exports2, module2) { "use strict"; var assert = require("node:assert"); - var util3 = require_util(); + var util4 = require_util(); var { channels } = require_diagnostics(); var timers = require_timers(); var { @@ -6007,70 +7187,127 @@ var require_client_h1 = __commonJS({ kMaxResponseSize, kOnError, kResume, - kHTTPContext + kHTTPContext, + kClosed } = require_symbols(); var constants = require_constants2(); var EMPTY_BUF = Buffer.alloc(0); var FastBuffer = Buffer[Symbol.species]; - var addListener = util3.addListener; - var removeAllListeners = util3.removeAllListeners; + var removeAllListeners = util4.removeAllListeners; var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; - async function lazyllhttp() { + function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; let mod; - try { - mod = await WebAssembly.compile(require_llhttp_simd_wasm()); - } catch (e) { - mod = await WebAssembly.compile(llhttpWasmData || require_llhttp_wasm()); + let useWasmSIMD = true; + if (process.arch === "ppc64") { + const [major, minor] = process.versions.node.split(".").map((n) => parseInt(n, 10)); + if (major < 24 || major === 24 && minor < 12) { + useWasmSIMD = false; + } + } + if (process.env.UNDICI_NO_WASM_SIMD === "1") { + useWasmSIMD = false; + } else if (process.env.UNDICI_NO_WASM_SIMD === "0") { + useWasmSIMD = true; } - return await WebAssembly.instantiate(mod, { + if (useWasmSIMD) { + try { + mod = new WebAssembly.Module(require_llhttp_simd_wasm()); + } catch { + } + } + if (!mod) { + mod = new WebAssembly.Module(llhttpWasmData || require_llhttp_wasm()); + } + return new WebAssembly.Instance(mod, { env: { - /* eslint-disable camelcase */ + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ wasm_on_url: (p, at, len) => { return 0; }, + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ 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; + return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)); }, + /** + * @param {number} p + * @returns {number} + */ wasm_on_message_begin: (p) => { assert(currentParser.ptr === p); - return currentParser.onMessageBegin() || 0; + return currentParser.onMessageBegin(); }, + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ 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; + return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)); }, + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ 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; + return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)); }, + /** + * @param {number} p + * @param {number} statusCode + * @param {0|1} upgrade + * @param {0|1} shouldKeepAlive + * @returns {number} + */ wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { assert(currentParser.ptr === p); - return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0; + return currentParser.onHeadersComplete(statusCode, upgrade === 1, shouldKeepAlive === 1); }, + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ 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; + return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)); }, + /** + * @param {number} p + * @returns {number} + */ wasm_on_message_complete: (p) => { assert(currentParser.ptr === p); - return currentParser.onMessageComplete() || 0; + return currentParser.onMessageComplete(); } - /* eslint-enable camelcase */ } }); } var llhttpInstance = null; - var llhttpPromise = lazyllhttp(); - llhttpPromise.catch(); var currentParser = null; var currentBufferRef = null; var currentBufferSize = 0; @@ -6081,16 +7318,21 @@ var require_client_h1 = __commonJS({ var TIMEOUT_BODY = 4 | USE_FAST_TIMER; var TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER; var Parser = class { + /** + * @param {import('./client.js')} client + * @param {import('net').Socket} socket + * @param {*} llhttp + */ constructor(client, socket, { exports: exports3 }) { - assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0); this.llhttp = exports3; this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE); this.client = client; this.socket = socket; this.timeout = null; + this.timeoutWeakRef = new WeakRef(this); this.timeoutValue = null; this.timeoutType = null; - this.statusCode = null; + this.statusCode = 0; this.statusText = ""; this.upgrade = false; this.headers = []; @@ -6113,10 +7355,10 @@ var require_client_h1 = __commonJS({ } if (delay2) { if (type & USE_FAST_TIMER) { - this.timeout = timers.setFastTimeout(onParserTimeout, delay2, new WeakRef(this)); + this.timeout = timers.setFastTimeout(onParserTimeout, delay2, this.timeoutWeakRef); } else { - this.timeout = setTimeout(onParserTimeout, delay2, new WeakRef(this)); - this.timeout.unref(); + this.timeout = setTimeout(onParserTimeout, delay2, this.timeoutWeakRef); + this.timeout?.unref(); } } this.timeoutValue = delay2; @@ -6132,7 +7374,7 @@ var require_client_h1 = __commonJS({ return; } assert(this.ptr != null); - assert(currentParser == null); + assert(currentParser === null); this.llhttp.llhttp_resume(this.ptr); assert(this.timeoutType === TIMEOUT_BODY); if (this.timeout) { @@ -6153,45 +7395,45 @@ var require_client_h1 = __commonJS({ this.execute(chunk); } } - execute(data) { + /** + * @param {Buffer} chunk + */ + execute(chunk) { + assert(currentParser === null); assert(this.ptr != null); - assert(currentParser == null); assert(!this.paused); const { socket, llhttp } = this; - if (data.length > currentBufferSize) { + if (chunk.length > currentBufferSize) { if (currentBufferPtr) { llhttp.free(currentBufferPtr); } - currentBufferSize = Math.ceil(data.length / 4096) * 4096; + currentBufferSize = Math.ceil(chunk.length / 4096) * 4096; currentBufferPtr = llhttp.malloc(currentBufferSize); } - new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data); + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(chunk); try { let ret; try { - currentBufferRef = data; + currentBufferRef = chunk; currentParser = this; - ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length); - } catch (err) { - throw err; + ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length); } 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); + const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr); if (ret === constants.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); + this.onUpgrade(data); } else if (ret === constants.ERROR.PAUSED) { this.paused = true; - socket.unshift(body); + socket.unshift(data); } else { - throw this.createError(ret, body); + throw this.createError(ret, data); } } } catch (err) { - util3.destroy(socket, err); + util4.destroy(socket, err); } } finish() { @@ -6229,8 +7471,8 @@ var require_client_h1 = __commonJS({ return new HTTPParserError(message, constants.ERROR[ret], data); } destroy() { + assert(currentParser === null); assert(this.ptr != null); - assert(currentParser == null); this.llhttp.llhttp_free(this.ptr); this.ptr = null; this.timeout && timers.clearTimeout(this.timeout); @@ -6239,16 +7481,24 @@ var require_client_h1 = __commonJS({ this.timeoutType = null; this.paused = false; } + /** + * @param {Buffer} buf + * @returns {0} + */ onStatus(buf) { this.statusText = buf.toString(); + return 0; } + /** + * @returns {0|-1} + */ onMessageBegin() { const { socket, client } = this; if (socket.destroyed) { return -1; } if (client[kRunning] === 0) { - util3.destroy(socket, new SocketError("bad response", util3.getSocketInfo(socket))); + util4.destroy(socket, new SocketError("bad response", util4.getSocketInfo(socket))); return -1; } const request3 = client[kQueue][client[kRunningIdx]]; @@ -6256,7 +7506,12 @@ var require_client_h1 = __commonJS({ return -1; } request3.onResponseStarted(); + return 0; } + /** + * @param {Buffer} buf + * @returns {number} + */ onHeaderField(buf) { const len = this.headers.length; if ((len & 1) === 0) { @@ -6265,7 +7520,12 @@ var require_client_h1 = __commonJS({ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]); } this.trackHeader(buf.length); + return 0; } + /** + * @param {Buffer} buf + * @returns {number} + */ onHeaderValue(buf) { let len = this.headers.length; if ((len & 1) === 1) { @@ -6276,25 +7536,32 @@ var require_client_h1 = __commonJS({ } const key = this.headers[len - 2]; if (key.length === 10) { - const headerName = util3.bufferToLowerCasedHeaderName(key); + const headerName = util4.bufferToLowerCasedHeaderName(key); if (headerName === "keep-alive") { this.keepAlive += buf.toString(); } else if (headerName === "connection") { this.connection += buf.toString(); } - } else if (key.length === 14 && util3.bufferToLowerCasedHeaderName(key) === "content-length") { + } else if (key.length === 14 && util4.bufferToLowerCasedHeaderName(key) === "content-length") { this.contentLength += buf.toString(); } this.trackHeader(buf.length); + return 0; } + /** + * @param {number} len + */ trackHeader(len) { this.headersSize += len; if (this.headersSize >= this.headersMaxSize) { - util3.destroy(this.socket, new HeadersOverflowError()); + util4.destroy(this.socket, new HeadersOverflowError()); } } + /** + * @param {Buffer} head + */ onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode } = this; + const { upgrade, client, socket, headers, statusCode, statusText } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6303,9 +7570,9 @@ var require_client_h1 = __commonJS({ const request3 = client[kQueue][client[kRunningIdx]]; assert(request3); assert(request3.upgrade || request3.method === "CONNECT"); - this.statusCode = null; + this.statusCode = 0; this.statusText = ""; - this.shouldKeepAlive = null; + this.shouldKeepAlive = false; this.headers = []; this.headersSize = 0; socket.unshift(head); @@ -6319,19 +7586,26 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request3.onUpgrade(statusCode, headers, socket); + request3.onUpgrade(statusCode, headers, socket, statusText); } catch (err) { - util3.destroy(socket, err); + util4.errorRequest(client, request3, err); + util4.destroy(socket, err); } client[kResume](); } + /** + * @param {number} statusCode + * @param {boolean} upgrade + * @param {boolean} shouldKeepAlive + * @returns {number} + */ onHeadersComplete(statusCode, upgrade, shouldKeepAlive) { const { client, socket, headers, statusText } = this; if (socket.destroyed) { return -1; } if (client[kRunning] === 0) { - util3.destroy(socket, new SocketError("bad response", util3.getSocketInfo(socket))); + util4.destroy(socket, new SocketError("bad response", util4.getSocketInfo(socket))); return -1; } const request3 = client[kQueue][client[kRunningIdx]]; @@ -6341,11 +7615,11 @@ var require_client_h1 = __commonJS({ assert(!this.upgrade); assert(this.statusCode < 200); if (statusCode === 100) { - util3.destroy(socket, new SocketError("bad response", util3.getSocketInfo(socket))); + util4.destroy(socket, new SocketError("bad response", util4.getSocketInfo(socket))); return -1; } if (upgrade && !request3.upgrade) { - util3.destroy(socket, new SocketError("bad upgrade", util3.getSocketInfo(socket))); + util4.destroy(socket, new SocketError("bad upgrade", util4.getSocketInfo(socket))); return -1; } assert(this.timeoutType === TIMEOUT_HEADERS); @@ -6374,7 +7648,7 @@ var require_client_h1 = __commonJS({ this.headers = []; this.headersSize = 0; if (this.shouldKeepAlive && client[kPipelining]) { - const keepAliveTimeout = this.keepAlive ? util3.parseKeepAliveTimeout(this.keepAlive) : null; + const keepAliveTimeout = this.keepAlive ? util4.parseKeepAliveTimeout(this.keepAlive) : null; if (keepAliveTimeout != null) { const timeout = Math.min( keepAliveTimeout - client[kKeepAliveTimeoutThreshold], @@ -6407,6 +7681,10 @@ var require_client_h1 = __commonJS({ } return pause ? constants.ERROR.PAUSED : 0; } + /** + * @param {Buffer} buf + * @returns {number} + */ onBody(buf) { const { client, socket, statusCode, maxResponseSize } = this; if (socket.destroyed) { @@ -6422,27 +7700,31 @@ var require_client_h1 = __commonJS({ } assert(statusCode >= 200); if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { - util3.destroy(socket, new ResponseExceededMaxSizeError()); + util4.destroy(socket, new ResponseExceededMaxSizeError()); return -1; } this.bytesRead += buf.length; if (request3.onData(buf) === false) { return constants.ERROR.PAUSED; } + return 0; } + /** + * @returns {number} + */ onMessageComplete() { const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this; if (socket.destroyed && (!statusCode || shouldKeepAlive)) { return -1; } if (upgrade) { - return; + return 0; } assert(statusCode >= 100); assert((this.headers.length & 1) === 0); const request3 = client[kQueue][client[kRunningIdx]]; assert(request3); - this.statusCode = null; + this.statusCode = 0; this.statusText = ""; this.bytesRead = 0; this.contentLength = ""; @@ -6451,53 +7733,63 @@ var require_client_h1 = __commonJS({ this.headers = []; this.headersSize = 0; if (statusCode < 200) { - return; + return 0; } if (request3.method !== "HEAD" && contentLength && bytesRead !== parseInt(contentLength, 10)) { - util3.destroy(socket, new ResponseContentLengthMismatchError()); + util4.destroy(socket, new ResponseContentLengthMismatchError()); return -1; } request3.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; + socket[kSocketUsed] = client[kPending] === 0; if (socket[kWriting]) { assert(client[kRunning] === 0); - util3.destroy(socket, new InformationalError("reset")); + util4.destroy(socket, new InformationalError("reset")); return constants.ERROR.PAUSED; } else if (!shouldKeepAlive) { - util3.destroy(socket, new InformationalError("reset")); + util4.destroy(socket, new InformationalError("reset")); return constants.ERROR.PAUSED; } else if (socket[kReset] && client[kRunning] === 0) { - util3.destroy(socket, new InformationalError("reset")); + util4.destroy(socket, new InformationalError("reset")); return constants.ERROR.PAUSED; } else if (client[kPipelining] == null || client[kPipelining] === 1) { - setImmediate(() => client[kResume]()); + setImmediate(client[kResume]); } else { client[kResume](); } + return 0; } }; - function onParserTimeout(parser) { - const { socket, timeoutType, client, paused } = parser.deref(); + function onParserTimeout(parserWeakRef) { + const parser = parserWeakRef.deref(); + if (!parser) { + return; + } + const { socket, timeoutType, client, paused } = parser; if (timeoutType === TIMEOUT_HEADERS) { if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { assert(!paused, "cannot be paused while waiting for headers"); - util3.destroy(socket, new HeadersTimeoutError()); + util4.destroy(socket, new HeadersTimeoutError()); } } else if (timeoutType === TIMEOUT_BODY) { if (!paused) { - util3.destroy(socket, new BodyTimeoutError()); + util4.destroy(socket, new BodyTimeoutError()); } } else if (timeoutType === TIMEOUT_KEEP_ALIVE) { assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]); - util3.destroy(socket, new InformationalError("socket idle timeout")); + util4.destroy(socket, new InformationalError("socket idle timeout")); } } - async function connectH1(client, socket) { + function connectH1(client, socket) { client[kSocket] = socket; if (!llhttpInstance) { - llhttpInstance = await llhttpPromise; - llhttpPromise = null; + llhttpInstance = lazyllhttp(); + } + if (socket.errored) { + throw socket.errored; + } + if (socket.destroyed) { + throw new SocketError("destroyed"); } socket[kNoRef] = false; socket[kWriting] = false; @@ -6507,91 +7799,43 @@ var require_client_h1 = __commonJS({ socket[kIdleSocketValidationTimeout] = null; socket[kSocketUsed] = 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]; - 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) { - util3.destroy(this, parserErr); - } - return; - } - util3.destroy(this, new SocketError("other side closed", util3.getSocketInfo(this))); - }); - addListener(socket, "close", function() { - const client2 = this[kClient]; - const parser = this[kParser]; - clearIdleSocketValidation(this); - 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", util3.getSocketInfo(this)); - client2[kSocket] = null; - client2[kHTTPContext] = null; - if (client2.destroyed) { - assert(client2[kPending] === 0); - const requests = client2[kQueue].splice(client2[kRunningIdx]); - for (let i = 0; i < requests.length; i++) { - const request3 = requests[i]; - util3.errorRequest(client2, request3, err); - } - } else if (client2[kRunning] > 0 && err.code !== "UND_ERR_INFO") { - const request3 = client2[kQueue][client2[kRunningIdx]]; - client2[kQueue][client2[kRunningIdx]++] = null; - util3.errorRequest(client2, request3, err); - } - client2[kPendingIdx] = client2[kRunningIdx]; - assert(client2[kRunning] === 0); - client2.emit("disconnect", client2[kUrl], [client2], err); - client2[kResume](); - }); - let closed = false; - socket.on("close", () => { - closed = true; - }); + util4.addListener(socket, "error", onHttpSocketError); + util4.addListener(socket, "readable", onHttpSocketReadable); + util4.addListener(socket, "end", onHttpSocketEnd); + util4.addListener(socket, "close", onHttpSocketClose); + socket[kClosed] = false; + socket.on("close", onSocketClose); return { version: "h1", defaultPipelining: 1, - write(...args) { - return writeH1(client, ...args); + write(request3) { + return writeH1(client, request3); }, resume() { resumeH1(client); }, + /** + * @param {Error|undefined} err + * @param {() => void} callback + */ destroy(err, callback) { - if (closed) { + if (socket[kClosed]) { queueMicrotask(callback); } else { - socket.destroy(err).on("close", callback); + socket.on("close", callback); + socket.destroy(err); } }, + /** + * @returns {boolean} + */ get destroyed() { return socket.destroyed; }, + /** + * @param {import('../core/request.js')} request + * @returns {boolean} + */ busy(request3) { if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { return true; @@ -6603,7 +7847,7 @@ var require_client_h1 = __commonJS({ if (client[kRunning] > 0 && (request3.upgrade || request3.method === "CONNECT")) { return true; } - if (client[kRunning] > 0 && util3.bodyLength(request3.body) !== 0 && (util3.isStream(request3.body) || util3.isAsyncIterable(request3.body) || util3.isFormDataLike(request3.body))) { + if (client[kRunning] > 0 && util4.bodyLength(request3.body) !== 0 && (util4.isStream(request3.body) || util4.isAsyncIterable(request3.body) || util4.isFormDataLike(request3.body))) { return true; } } @@ -6611,23 +7855,83 @@ var require_client_h1 = __commonJS({ } }; } + function onHttpSocketError(err) { + const parser = this[kParser]; + 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); + } + function onHttpSocketReadable() { + this[kParser]?.readMore(); + } + function onHttpSocketEnd() { + const parser = this[kParser]; + if (parser.statusCode && !parser.shouldKeepAlive) { + const parserErr = parser.finish(); + if (parserErr) { + util4.destroy(this, parserErr); + } + return; + } + util4.destroy(this, new SocketError("other side closed", util4.getSocketInfo(this))); + } + function onHttpSocketClose() { + const parser = this[kParser]; + clearIdleSocketValidation(this); + 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", util4.getSocketInfo(this)); + const client = this[kClient]; + client[kSocket] = null; + client[kHTTPContext] = null; + if (client.destroyed) { + assert(client[kPending] === 0); + const requests = client[kQueue].splice(client[kRunningIdx]); + for (let i = 0; i < requests.length; i++) { + const request3 = requests[i]; + util4.errorRequest(client, request3, err); + } + } else if (client[kRunning] > 0 && err.code !== "UND_ERR_INFO") { + const request3 = client[kQueue][client[kRunningIdx]]; + client[kQueue][client[kRunningIdx]++] = null; + util4.errorRequest(client, request3, err); + } + client[kPendingIdx] = client[kRunningIdx]; + assert(client[kRunning] === 0); + client.emit("disconnect", client[kUrl], [client], err); + client[kResume](); + } + function onSocketClose() { + this[kClosed] = true; + } function clearIdleSocketValidation(socket) { if (socket[kIdleSocketValidationTimeout]) { - clearTimeout(socket[kIdleSocketValidationTimeout]); + clearImmediate(socket[kIdleSocketValidationTimeout]); socket[kIdleSocketValidationTimeout] = null; } socket[kIdleSocketValidation] = 0; } function scheduleIdleSocketValidation(client, socket) { socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setTimeout(() => { + socket[kIdleSocketValidationTimeout] = setImmediate(() => { socket[kIdleSocketValidationTimeout] = null; socket[kIdleSocketValidation] = 2; if (client[kSocket] === socket && !socket.destroyed) { client[kResume](); } - }, 0); - socket[kIdleSocketValidationTimeout].unref?.(); + }); } function resumeH1(client) { const socket = client[kSocket]; @@ -6684,7 +7988,7 @@ var require_client_h1 = __commonJS({ const { method, path: path30, host, upgrade, blocking, reset } = request3; let { body, headers, contentLength } = request3; const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH"; - if (util3.isFormDataLike(body)) { + if (util4.isFormDataLike(body)) { if (!extractBody) { extractBody = require_body().extractBody; } @@ -6694,12 +7998,12 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util3.isBlobLike(body) && request3.contentType == null) { + } else if (util4.isBlobLike(body) && request3.contentType == null) { const contentType = body.type; if (contentType) { const contentTypeValue = `${contentType}`; - if (!util3.isValidHeaderValue(contentTypeValue)) { - util3.errorRequest(client, request3, new InvalidArgumentError("invalid content-type header")); + if (!util4.isValidHeaderValue(contentTypeValue)) { + util4.errorRequest(client, request3, new InvalidArgumentError("invalid content-type header")); return false; } headers.push("content-type", contentTypeValue); @@ -6708,7 +8012,7 @@ var require_client_h1 = __commonJS({ if (body && typeof body.read === "function") { body.read(0); } - const bodyLength = util3.bodyLength(body); + const bodyLength = util4.bodyLength(body); contentLength = bodyLength ?? contentLength; if (contentLength === null) { contentLength = request3.contentLength; @@ -6718,7 +8022,7 @@ var require_client_h1 = __commonJS({ } if (shouldSendContentLength(method) && contentLength > 0 && request3.contentLength !== null && request3.contentLength !== contentLength) { if (client[kStrictContentLength]) { - util3.errorRequest(client, request3, new RequestContentLengthMismatchError()); + util4.errorRequest(client, request3, new RequestContentLengthMismatchError()); return false; } process.emitWarning(new RequestContentLengthMismatchError()); @@ -6729,14 +8033,14 @@ var require_client_h1 = __commonJS({ if (request3.aborted || request3.completed) { return; } - util3.errorRequest(client, request3, err || new RequestAbortedError()); - util3.destroy(body); - util3.destroy(socket, new InformationalError("aborted")); + util4.errorRequest(client, request3, err || new RequestAbortedError()); + util4.destroy(body); + util4.destroy(socket, new InformationalError("aborted")); }; try { request3.onConnect(abort); } catch (err) { - util3.errorRequest(client, request3, err); + util4.errorRequest(client, request3, err); } if (request3.aborted) { return false; @@ -6756,6 +8060,9 @@ var require_client_h1 = __commonJS({ if (blocking) { socket[kBlocking] = true; } + if (socket.setTypeOfService) { + socket.setTypeOfService(request3.typeOfService); + } let header = `${method} ${path30} HTTP/1.1\r `; if (typeof host === "string") { @@ -6793,17 +8100,17 @@ upgrade: ${upgrade}\r } if (!body || bodyLength === 0) { writeBuffer(abort, null, client, request3, socket, contentLength, header, expectsPayload); - } else if (util3.isBuffer(body)) { + } else if (util4.isBuffer(body)) { writeBuffer(abort, body, client, request3, socket, contentLength, header, expectsPayload); - } else if (util3.isBlobLike(body)) { + } else if (util4.isBlobLike(body)) { if (typeof body.stream === "function") { writeIterable(abort, body.stream(), client, request3, socket, contentLength, header, expectsPayload); } else { writeBlob(abort, body, client, request3, socket, contentLength, header, expectsPayload); } - } else if (util3.isStream(body)) { + } else if (util4.isStream(body)) { writeStream(abort, body, client, request3, socket, contentLength, header, expectsPayload); - } else if (util3.isIterable(body)) { + } else if (util4.isIterable(body)) { writeIterable(abort, body, client, request3, socket, contentLength, header, expectsPayload); } else { assert(false); @@ -6823,7 +8130,7 @@ upgrade: ${upgrade}\r this.pause(); } } catch (err) { - util3.destroy(this, err); + util4.destroy(this, err); } }; const onDrain = function() { @@ -6860,9 +8167,9 @@ upgrade: ${upgrade}\r } writer.destroy(err); if (err && (err.code !== "UND_ERR_INFO" || err.message !== "reset")) { - util3.destroy(body, err); + util4.destroy(body, err); } else { - util3.destroy(body); + util4.destroy(body); } }; body.on("data", onData).on("end", onFinished).on("error", onFinished).on("close", onClose); @@ -6871,9 +8178,9 @@ upgrade: ${upgrade}\r } socket.on("drain", onDrain).on("error", onFinished); if (body.errorEmitted ?? body.errored) { - setImmediate(() => onFinished(body.errored)); + setImmediate(onFinished, body.errored); } else if (body.endEmitted ?? body.readableEnded) { - setImmediate(() => onFinished(null)); + setImmediate(onFinished, null); } if (body.closeEmitted ?? body.closed) { setImmediate(onClose); @@ -6891,7 +8198,7 @@ upgrade: ${upgrade}\r socket.write(`${header}\r `, "latin1"); } - } else if (util3.isBuffer(body)) { + } else if (util4.isBuffer(body)) { assert(contentLength === body.byteLength, "buffer body must have content length"); socket.cork(); socket.write(`${header}content-length: ${contentLength}\r @@ -6943,12 +8250,12 @@ upgrade: ${upgrade}\r cb(); } } - const waitForDrain = () => new Promise((resolve14, reject) => { + const waitForDrain = () => new Promise((resolve15, reject) => { assert(callback === null); if (socket[kError]) { reject(socket[kError]); } else { - callback = resolve14; + callback = resolve15; } }); socket.on("close", onDrain).on("drain", onDrain); @@ -6970,6 +8277,17 @@ upgrade: ${upgrade}\r } } var AsyncWriter = class { + /** + * + * @param {object} arg + * @param {AbortCallback} arg.abort + * @param {import('net').Socket} arg.socket + * @param {import('../core/request.js')} arg.request + * @param {number} arg.contentLength + * @param {import('./client.js')} arg.client + * @param {boolean} arg.expectsPayload + * @param {string} arg.header + */ constructor({ abort, socket, request: request3, contentLength, client, expectsPayload, header }) { this.socket = socket; this.request = request3; @@ -6981,6 +8299,10 @@ upgrade: ${upgrade}\r this.abort = abort; socket[kWriting] = true; } + /** + * @param {Buffer} chunk + * @returns + */ write(chunk) { const { socket, request: request3, contentLength, client, bytesWritten, expectsPayload, header } = this; if (socket[kError]) { @@ -7031,6 +8353,9 @@ ${len.toString(16)}\r } return ret; } + /** + * @returns {void} + */ end() { const { socket, contentLength, client, bytesWritten, expectsPayload, header, request: request3 } = this; request3.onRequestSent(); @@ -7067,6 +8392,10 @@ ${len.toString(16)}\r } client[kResume](); } + /** + * @param {Error} [err] + * @returns {void} + */ destroy(err) { const { socket, client, abort } = this; socket[kWriting] = false; @@ -7086,12 +8415,15 @@ var require_client_h2 = __commonJS({ "use strict"; var assert = require("node:assert"); var { pipeline: pipeline2 } = require("node:stream"); - var util3 = require_util(); + var util4 = require_util(); var { RequestContentLengthMismatchError, RequestAbortedError, SocketError, - InformationalError + InformationalError, + InvalidArgumentError, + HeadersTimeoutError, + BodyTimeoutError } = require_errors(); var { kUrl, @@ -7107,14 +8439,24 @@ var require_client_h2 = __commonJS({ kStrictContentLength, kOnError, kMaxConcurrentStreams, + kPingInterval, kHTTP2Session, + kHTTP2InitialWindowSize, + kHTTP2ConnectionWindowSize, kResume, kSize, - kHTTPContext + kHTTPContext, + kClosed, + kBodyTimeout, + kHeadersTimeout, + kEnableConnectProtocol, + kRemoteSettings, + kHTTP2Stream, + kHTTP2SessionState } = require_symbols(); + var { channels } = require_diagnostics(); var kOpenStreams = /* @__PURE__ */ Symbol("open streams"); var extractBody; - var h2ExperimentalWarned = false; var http2; try { http2 = require("node:http2"); @@ -7129,7 +8471,10 @@ var require_client_h2 = __commonJS({ HTTP2_HEADER_SCHEME, HTTP2_HEADER_CONTENT_LENGTH, HTTP2_HEADER_EXPECT, - HTTP2_HEADER_STATUS + HTTP2_HEADER_STATUS, + HTTP2_HEADER_PROTOCOL, + NGHTTP2_REFUSED_STREAM, + NGHTTP2_CANCEL } } = http2; function parseH2Headers(headers) { @@ -7145,85 +8490,94 @@ var require_client_h2 = __commonJS({ } return result; } - async function connectH2(client, socket) { + 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 http2InitialWindowSize = client[kHTTP2InitialWindowSize]; + const http2ConnectionWindowSize = client[kHTTP2ConnectionWindowSize]; const session = http2.connect(client[kUrl], { createConnection: () => socket, - peerMaxConcurrentStreams: client[kMaxConcurrentStreams] + peerMaxConcurrentStreams: client[kMaxConcurrentStreams], + settings: { + // TODO(metcoder95): add support for PUSH + enablePush: false, + ...http2InitialWindowSize != null ? { initialWindowSize: http2InitialWindowSize } : null + } }); + client[kSocket] = socket; session[kOpenStreams] = 0; session[kClient] = client; session[kSocket] = socket; - util3.addListener(session, "error", onHttp2SessionError); - util3.addListener(session, "frameError", onHttp2FrameError); - util3.addListener(session, "end", onHttp2SessionEnd); - util3.addListener(session, "goaway", onHTTP2GoAway); - util3.addListener(session, "close", function() { - const { [kClient]: client2 } = this; - const { [kSocket]: socket2 } = client2; - const err = this[kSocket][kError] || this[kError] || new SocketError("closed", util3.getSocketInfo(socket2)); - client2[kHTTP2Session] = null; - if (client2.destroyed) { - assert(client2[kPending] === 0); - const requests = client2[kQueue].splice(client2[kRunningIdx]); - for (let i = 0; i < requests.length; i++) { - const request3 = requests[i]; - util3.errorRequest(client2, request3, err); - } - } - }); + session[kHTTP2SessionState] = { + ping: { + interval: client[kPingInterval] === 0 ? null : setInterval(onHttp2SendPing, client[kPingInterval], session).unref() + } + }; + session[kEnableConnectProtocol] = false; + session[kRemoteSettings] = false; + if (http2ConnectionWindowSize) { + util4.addListener(session, "connect", applyConnectionWindowSize.bind(session, http2ConnectionWindowSize)); + } + util4.addListener(session, "error", onHttp2SessionError); + util4.addListener(session, "frameError", onHttp2FrameError); + util4.addListener(session, "end", onHttp2SessionEnd); + util4.addListener(session, "goaway", onHttp2SessionGoAway); + util4.addListener(session, "close", onHttp2SessionClose); + util4.addListener(session, "remoteSettings", onHttp2RemoteSettings); session.unref(); client[kHTTP2Session] = session; socket[kHTTP2Session] = session; - util3.addListener(socket, "error", function(err) { - assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); - this[kError] = err; - this[kClient][kOnError](err); - }); - util3.addListener(socket, "end", function() { - util3.destroy(this, new SocketError("other side closed", util3.getSocketInfo(this))); - }); - util3.addListener(socket, "close", function() { - const err = this[kError] || new SocketError("closed", util3.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; - }); + util4.addListener(socket, "error", onHttp2SocketError); + util4.addListener(socket, "end", onHttp2SocketEnd); + util4.addListener(socket, "close", onHttp2SocketClose); + socket[kClosed] = false; + socket.on("close", onSocketClose); return { version: "h2", defaultPipelining: Infinity, - write(...args) { - return writeH2(client, ...args); + /** + * @param {import('../core/request.js')} request + * @returns {boolean} + */ + write(request3) { + return writeH2(client, request3); }, + /** + * @returns {void} + */ resume() { resumeH2(client); }, + /** + * @param {Error | null} err + * @param {() => void} callback + */ destroy(err, callback) { - if (closed) { + if (socket[kClosed]) { queueMicrotask(callback); } else { socket.destroy(err).on("close", callback); } }, + /** + * @type {boolean} + */ get destroyed() { return socket.destroyed; }, - busy() { + /** + * @param {import('../core/request.js')} request + * @returns {boolean} + */ + busy(request3) { + if (request3 != null) { + if (client[kRunning] > 0) { + if (request3.idempotent === false) return true; + if ((request3.upgrade === "websocket" || request3.method === "CONNECT") && session[kRemoteSettings] === false) return true; + if (util4.bodyLength(request3.body) !== 0 && (util4.isStream(request3.body) || util4.isAsyncIterable(request3.body) || util4.isFormDataLike(request3.body))) return true; + } else { + return (request3.upgrade === "websocket" || request3.method === "CONNECT") && session[kRemoteSettings] === false; + } + } return false; } }; @@ -7231,7 +8585,7 @@ var require_client_h2 = __commonJS({ function resumeH2(client) { const socket = client[kSocket]; if (socket?.destroyed === false) { - if (client[kSize] === 0 && client[kMaxConcurrentStreams] === 0) { + if (client[kSize] === 0) { socket.unref(); client[kHTTP2Session].unref(); } else { @@ -7240,8 +8594,47 @@ var require_client_h2 = __commonJS({ } } } + function applyConnectionWindowSize(connectionWindowSize) { + try { + if (typeof this.setLocalWindowSize === "function") { + this.setLocalWindowSize(connectionWindowSize); + } + } catch { + } + } + function onHttp2RemoteSettings(settings) { + this[kClient][kMaxConcurrentStreams] = settings.maxConcurrentStreams ?? this[kClient][kMaxConcurrentStreams]; + if (this[kRemoteSettings] === true && this[kEnableConnectProtocol] === true && settings.enableConnectProtocol === false) { + const err = new InformationalError("HTTP/2: Server disabled extended CONNECT protocol against RFC-8441"); + this[kSocket][kError] = err; + this[kClient][kOnError](err); + return; + } + this[kEnableConnectProtocol] = settings.enableConnectProtocol ?? this[kEnableConnectProtocol]; + this[kRemoteSettings] = true; + this[kClient][kResume](); + } + function onHttp2SendPing(session) { + const state = session[kHTTP2SessionState]; + if ((session.closed || session.destroyed) && state.ping.interval != null) { + clearInterval(state.ping.interval); + state.ping.interval = null; + return; + } + session.ping(onPing.bind(session)); + function onPing(err, duration) { + const client = this[kClient]; + const socket = this[kClient]; + if (err != null) { + const error3 = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`); + socket[kError] = error3; + client[kOnError](error3); + } else { + client.emit("ping", duration); + } + } + } function onHttp2SessionError(err) { - assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); this[kSocket][kError] = err; this[kClient][kOnError](err); } @@ -7253,58 +8646,133 @@ var require_client_h2 = __commonJS({ } } function onHttp2SessionEnd() { - const err = new SocketError("other side closed", util3.getSocketInfo(this[kSocket])); + const err = new SocketError("other side closed", util4.getSocketInfo(this[kSocket])); this.destroy(err); - util3.destroy(this[kSocket], err); + util4.destroy(this[kSocket], err); + } + function completeRequest(client, request3, resetPendingIdx = false) { + const queue2 = client[kQueue]; + const runningIdx = client[kRunningIdx]; + if (runningIdx < client[kPendingIdx] && queue2[runningIdx] === request3) { + queue2[runningIdx] = null; + client[kRunningIdx] = runningIdx + 1; + return; + } + const index2 = queue2.indexOf(request3, runningIdx); + if (index2 === -1 || index2 >= client[kPendingIdx]) { + return; + } + queue2.splice(index2, 1); + client[kPendingIdx]--; + if (resetPendingIdx && client[kPendingIdx] < client[kRunningIdx]) { + client[kPendingIdx] = client[kRunningIdx]; + } } - function onHTTP2GoAway(code) { - const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${code}`, util3.getSocketInfo(this)); + function onHttp2SessionGoAway(errorCode) { + const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util4.getSocketInfo(this[kSocket])); const client = this[kClient]; client[kSocket] = null; client[kHTTPContext] = null; - if (this[kHTTP2Session] != null) { - this[kHTTP2Session].destroy(err); - this[kHTTP2Session] = null; - } - util3.destroy(this[kSocket], err); + this.close(); + this[kHTTP2Session] = null; + util4.destroy(this[kSocket], err); if (client[kRunningIdx] < client[kQueue].length) { const request3 = client[kQueue][client[kRunningIdx]]; client[kQueue][client[kRunningIdx]++] = null; - util3.errorRequest(client, request3, err); + if (request3 != null) { + util4.errorRequest(client, request3, err); + } client[kPendingIdx] = client[kRunningIdx]; } assert(client[kRunning] === 0); client.emit("disconnect", client[kUrl], [client], err); + client.emit("connectionError", client[kUrl], [client], err); + client[kResume](); + } + function onHttp2SessionClose() { + const { [kClient]: client, [kHTTP2SessionState]: state } = this; + const { [kSocket]: socket } = client; + const err = this[kSocket][kError] || this[kError] || new SocketError("closed", util4.getSocketInfo(socket)); + client[kSocket] = null; + client[kHTTPContext] = null; + if (state.ping.interval != null) { + clearInterval(state.ping.interval); + state.ping.interval = null; + } + if (client.destroyed) { + assert(client[kPending] === 0); + const requests = client[kQueue].splice(client[kRunningIdx]); + for (let i = 0; i < requests.length; i++) { + const request3 = requests[i]; + if (request3 != null) { + util4.errorRequest(client, request3, err); + } + } + } + } + function onHttp2SocketClose() { + const err = this[kError] || new SocketError("closed", util4.getSocketInfo(this)); + const client = this[kHTTP2Session][kClient]; + client[kSocket] = null; + client[kHTTPContext] = 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](); } + function onHttp2SocketError(err) { + this[kError] = err; + this[kClient][kOnError](err); + } + function onHttp2SocketEnd() { + util4.destroy(this, new SocketError("other side closed", util4.getSocketInfo(this))); + } + function onSocketClose() { + this[kClosed] = true; + } function shouldSendContentLength(method) { return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT"; } function writeH2(client, request3) { + const headersTimeout = request3.headersTimeout ?? client[kHeadersTimeout]; + const bodyTimeout = request3.bodyTimeout ?? client[kBodyTimeout]; const session = client[kHTTP2Session]; - const { method, path: path30, host, upgrade, expectContinue, signal, headers: reqHeaders } = request3; + const { method, path: path30, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request3; let { body } = request3; - if (upgrade) { - util3.errorRequest(client, request3, new Error("Upgrade not supported for H2")); + if (upgrade != null && upgrade !== "websocket") { + util4.errorRequest(client, request3, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`)); return false; } const headers = {}; for (let n = 0; n < reqHeaders.length; n += 2) { const key = reqHeaders[n + 0]; const val = reqHeaders[n + 1]; + if (key === "cookie") { + if (headers[key] != null) { + headers[key] = Array.isArray(headers[key]) ? (headers[key].push(val), headers[key]) : [headers[key], val]; + } else { + headers[key] = val; + } + continue; + } if (Array.isArray(val)) { for (let i = 0; i < val.length; i++) { if (headers[key]) { - headers[key] += `,${val[i]}`; + headers[key] += `, ${val[i]}`; } else { headers[key] = val[i]; } } + } else if (headers[key]) { + headers[key] += `, ${val}`; } else { headers[key] = val; } } - let stream2; + let stream2 = null; const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; @@ -7313,50 +8781,94 @@ var require_client_h2 = __commonJS({ return; } err = err || new RequestAbortedError(); - util3.errorRequest(client, request3, err); + util4.errorRequest(client, request3, err); if (stream2 != null) { - util3.destroy(stream2, err); + stream2.removeAllListeners("data"); + stream2.close(); + client[kOnError](err); + completeRequest(client, request3); + client[kResume](); } - util3.destroy(body, err); - client[kQueue][client[kRunningIdx]++] = null; - client[kResume](); + util4.destroy(body, err); }; try { request3.onConnect(abort); } catch (err) { - util3.errorRequest(client, request3, err); + util4.errorRequest(client, request3, err); } if (request3.aborted) { return false; } - if (method === "CONNECT") { + if (upgrade || method === "CONNECT") { session.ref(); - stream2 = session.request(headers, { endStream: false, signal }); - if (stream2.id && !stream2.pending) { - request3.onUpgrade(null, null, stream2); + if (upgrade === "websocket") { + if (session[kEnableConnectProtocol] === false) { + util4.errorRequest(client, request3, new InformationalError("HTTP/2: Extended CONNECT protocol not supported by server")); + session.unref(); + return false; + } + headers[HTTP2_HEADER_METHOD] = "CONNECT"; + headers[HTTP2_HEADER_PROTOCOL] = "websocket"; + headers[HTTP2_HEADER_PATH] = path30; + if (protocol === "ws:" || protocol === "wss:") { + headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https"; + } else { + headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https"; + } + stream2 = session.request(headers, { endStream: false, signal }); + stream2[kHTTP2Stream] = true; ++session[kOpenStreams]; - client[kQueue][client[kRunningIdx]++] = null; - } else { - stream2.once("ready", () => { - request3.onUpgrade(null, null, stream2); - ++session[kOpenStreams]; - client[kQueue][client[kRunningIdx]++] = null; + stream2.once("response", (headers2, _flags) => { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2; + try { + request3.onUpgrade(statusCode, parseH2Headers(realHeaders), stream2); + } catch (err) { + abort(err); + return; + } + completeRequest(client, request3); + }); + stream2.on("error", () => { + if (stream2.rstCode === NGHTTP2_REFUSED_STREAM || stream2.rstCode === NGHTTP2_CANCEL) { + abort(new InformationalError(`HTTP/2: "stream error" received - code ${stream2.rstCode}`)); + } }); + stream2.once("close", () => { + session[kOpenStreams] -= 1; + if (session[kOpenStreams] === 0) session.unref(); + }); + stream2.setTimeout(headersTimeout); + return true; } + stream2 = session.request(headers, { endStream: false, signal }); + stream2[kHTTP2Stream] = true; + ++session[kOpenStreams]; + stream2.on("response", (headers2) => { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2; + try { + request3.onUpgrade(statusCode, parseH2Headers(realHeaders), stream2); + } catch (err) { + abort(err); + return; + } + completeRequest(client, request3); + }); + stream2.on("error", abort); stream2.once("close", () => { session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); + stream2.setTimeout(headersTimeout); return true; } headers[HTTP2_HEADER_PATH] = path30; - headers[HTTP2_HEADER_SCHEME] = "https"; + headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https"; const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH"; if (body && typeof body.read === "function") { body.read(0); } - let contentLength = util3.bodyLength(body); - if (util3.isFormDataLike(body)) { + let contentLength = util4.bodyLength(body); + if (util4.isFormDataLike(body)) { extractBody ??= require_body().extractBody; const [bodyStream, contentType] = extractBody(body); headers["content-type"] = contentType; @@ -7366,76 +8878,118 @@ var require_client_h2 = __commonJS({ if (contentLength == null) { contentLength = request3.contentLength; } - if (contentLength === 0 || !expectsPayload) { + if (!expectsPayload) { contentLength = null; } if (shouldSendContentLength(method) && contentLength > 0 && request3.contentLength != null && request3.contentLength !== contentLength) { if (client[kStrictContentLength]) { - util3.errorRequest(client, request3, new RequestContentLengthMismatchError()); + util4.errorRequest(client, request3, new RequestContentLengthMismatchError()); return false; } process.emitWarning(new RequestContentLengthMismatchError()); } if (contentLength != null) { - assert(body, "no body must not have content length"); + assert(body || contentLength === 0, "no body must not have content length"); headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`; } session.ref(); + if (channels.sendHeaders.hasSubscribers) { + let header = ""; + for (const key in headers) { + header += `${key}: ${headers[key]}\r +`; + } + channels.sendHeaders.publish({ request: request3, headers: header, socket: session[kSocket] }); + } const shouldEndStream = method === "GET" || method === "HEAD" || body === null; if (expectContinue) { headers[HTTP2_HEADER_EXPECT] = "100-continue"; stream2 = session.request(headers, { endStream: shouldEndStream, signal }); + stream2[kHTTP2Stream] = true; stream2.once("continue", writeBodyH2); } else { stream2 = session.request(headers, { endStream: shouldEndStream, signal }); + stream2[kHTTP2Stream] = true; writeBodyH2(); } ++session[kOpenStreams]; + stream2.setTimeout(headersTimeout); + let responseReceived = false; stream2.once("response", (headers2) => { const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2; request3.onResponseStarted(); + responseReceived = true; + stream2.setTimeout(bodyTimeout); if (request3.aborted) { - const err = new RequestAbortedError(); - util3.errorRequest(client, request3, err); - util3.destroy(stream2, err); + stream2.removeAllListeners("data"); return; } if (request3.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream2.resume.bind(stream2), "") === false) { stream2.pause(); } stream2.on("data", (chunk) => { + if (request3.aborted || request3.completed) { + return; + } if (request3.onData(chunk) === false) { stream2.pause(); } }); }); stream2.once("end", () => { - if (stream2.state?.state == null || stream2.state.state < 6) { - request3.onComplete([]); - } - if (session[kOpenStreams] === 0) { - session.unref(); + stream2.removeAllListeners("data"); + if (responseReceived) { + if (!request3.aborted && !request3.completed) { + request3.onComplete({}); + } + completeRequest(client, request3); + client[kResume](); + } else { + abort(new InformationalError("HTTP/2: stream half-closed (remote)")); + completeRequest(client, request3, true); + client[kResume](); } - abort(new InformationalError("HTTP/2: stream half-closed (remote)")); - client[kQueue][client[kRunningIdx]++] = null; - client[kPendingIdx] = client[kRunningIdx]; - client[kResume](); }); stream2.once("close", () => { + stream2.removeAllListeners("data"); session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) { session.unref(); } + if (!request3.aborted && !request3.completed) { + abort(new InformationalError("HTTP/2: stream closed before the response was complete")); + } }); stream2.once("error", function(err) { + stream2.removeAllListeners("data"); abort(err); }); stream2.once("frameError", (type, code) => { + stream2.removeAllListeners("data"); abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)); }); + stream2.on("aborted", () => { + stream2.removeAllListeners("data"); + }); + stream2.on("timeout", () => { + const err = responseReceived ? new BodyTimeoutError(`HTTP/2: "body timeout after ${bodyTimeout}"`) : new HeadersTimeoutError(`HTTP/2: "headers timeout after ${headersTimeout}"`); + stream2.removeAllListeners("data"); + session[kOpenStreams] -= 1; + if (session[kOpenStreams] === 0) { + session.unref(); + } + abort(err); + }); + stream2.once("trailers", (trailers) => { + if (request3.aborted || request3.completed) { + return; + } + stream2.removeAllListeners("data"); + request3.onComplete(trailers); + }); return true; function writeBodyH2() { if (!body || contentLength === 0) { @@ -7449,7 +9003,7 @@ var require_client_h2 = __commonJS({ contentLength, expectsPayload ); - } else if (util3.isBuffer(body)) { + } else if (util4.isBuffer(body)) { writeBuffer( abort, stream2, @@ -7460,7 +9014,7 @@ var require_client_h2 = __commonJS({ contentLength, expectsPayload ); - } else if (util3.isBlobLike(body)) { + } else if (util4.isBlobLike(body)) { if (typeof body.stream === "function") { writeIterable( abort, @@ -7484,7 +9038,7 @@ var require_client_h2 = __commonJS({ expectsPayload ); } - } else if (util3.isStream(body)) { + } else if (util4.isStream(body)) { writeStream( abort, client[kSocket], @@ -7495,7 +9049,7 @@ var require_client_h2 = __commonJS({ request3, contentLength ); - } else if (util3.isIterable(body)) { + } else if (util4.isIterable(body)) { writeIterable( abort, stream2, @@ -7513,7 +9067,7 @@ var require_client_h2 = __commonJS({ } function writeBuffer(abort, h2stream, body, client, request3, socket, contentLength, expectsPayload) { try { - if (body != null && util3.isBuffer(body)) { + if (body != null && util4.isBuffer(body)) { assert(contentLength === body.byteLength, "buffer body must have content length"); h2stream.cork(); h2stream.write(body); @@ -7537,10 +9091,10 @@ var require_client_h2 = __commonJS({ h2stream, (err) => { if (err) { - util3.destroy(pipe, err); + util4.destroy(pipe, err); abort(err); } else { - util3.removeAllListeners(pipe); + util4.removeAllListeners(pipe); request3.onRequestSent(); if (!expectsPayload) { socket[kReset] = true; @@ -7549,7 +9103,7 @@ var require_client_h2 = __commonJS({ } } ); - util3.addListener(pipe, "data", onPipeData); + util4.addListener(pipe, "data", onPipeData); function onPipeData(chunk) { request3.onBodySent(chunk); } @@ -7585,12 +9139,12 @@ var require_client_h2 = __commonJS({ cb(); } } - const waitForDrain = () => new Promise((resolve14, reject) => { + const waitForDrain = () => new Promise((resolve15, reject) => { assert(callback === null); if (socket[kError]) { reject(socket[kError]); } else { - callback = resolve14; + callback = resolve15; } }); h2stream.on("close", onDrain).on("drain", onDrain); @@ -7621,187 +9175,6 @@ var require_client_h2 = __commonJS({ } }); -// node_modules/undici/lib/handler/redirect-handler.js -var require_redirect_handler = __commonJS({ - "node_modules/undici/lib/handler/redirect-handler.js"(exports2, module2) { - "use strict"; - var util3 = require_util(); - var { kBodyUsed } = require_symbols(); - var assert = require("node:assert"); - var { InvalidArgumentError } = require_errors(); - var EE = require("node:events"); - var redirectableStatusCodes = [300, 301, 302, 303, 307, 308]; - var kBody = /* @__PURE__ */ Symbol("body"); - var BodyAsyncIterable = class { - constructor(body) { - this[kBody] = body; - this[kBodyUsed] = false; - } - async *[Symbol.asyncIterator]() { - assert(!this[kBodyUsed], "disturbed"); - this[kBodyUsed] = true; - yield* this[kBody]; - } - }; - var RedirectHandler = class { - constructor(dispatch, maxRedirections, opts, handler2) { - if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { - throw new InvalidArgumentError("maxRedirections must be a positive number"); - } - util3.validateHandler(handler2, opts.method, opts.upgrade); - this.dispatch = dispatch; - this.location = null; - this.abort = null; - this.opts = { ...opts, maxRedirections: 0 }; - this.maxRedirections = maxRedirections; - this.handler = handler2; - this.history = []; - this.redirectionLimitReached = false; - if (util3.isStream(this.opts.body)) { - if (util3.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") { - this.opts.body = new BodyAsyncIterable(this.opts.body); - } else if (this.opts.body && typeof this.opts.body !== "string" && !ArrayBuffer.isView(this.opts.body) && util3.isIterable(this.opts.body)) { - 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(error3) { - this.handler.onError(error3); - } - onHeaders(statusCode, headers, resume, statusText) { - this.location = this.history.length >= this.maxRedirections || util3.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 } = util3.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))); - const path30 = search ? `${pathname}${search}` : pathname; - this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin); - this.opts.path = path30; - this.opts.origin = origin; - this.opts.maxRedirections = 0; - this.opts.query = null; - if (statusCode === 303 && this.opts.method !== "HEAD") { - this.opts.method = "GET"; - this.opts.body = null; - } - } - onData(chunk) { - if (this.location) { - } else { - return this.handler.onData(chunk); - } - } - onComplete(trailers) { - if (this.location) { - 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 && util3.headerNameToString(headers[i]) === "location") { - return headers[i + 1]; - } - } - } - function shouldRemoveHeader(header, removeContent, unknownOrigin) { - if (header.length === 4) { - return util3.headerNameToString(header) === "host"; - } - if (removeContent && util3.headerNameToString(header).startsWith("content-")) { - return true; - } - if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { - const name = util3.headerNameToString(header); - return name === "authorization" || name === "cookie" || name === "proxy-authorization"; - } - return false; - } - 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; - } - module2.exports = RedirectHandler; - } -}); - -// node_modules/undici/lib/interceptor/redirect-interceptor.js -var require_redirect_interceptor = __commonJS({ - "node_modules/undici/lib/interceptor/redirect-interceptor.js"(exports2, module2) { - "use strict"; - var RedirectHandler = require_redirect_handler(); - function createRedirectInterceptor({ maxRedirections: defaultMaxRedirections }) { - return (dispatch) => { - return function Intercept(opts, handler2) { - const { maxRedirections = defaultMaxRedirections } = opts; - if (!maxRedirections) { - return dispatch(opts, handler2); - } - const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler2); - opts = { ...opts, maxRedirections: 0 }; - return dispatch(opts, redirectHandler); - }; - }; - } - module2.exports = createRedirectInterceptor; - } -}); - // node_modules/undici/lib/dispatcher/client.js var require_client = __commonJS({ "node_modules/undici/lib/dispatcher/client.js"(exports2, module2) { @@ -7809,7 +9182,8 @@ var require_client = __commonJS({ var assert = require("node:assert"); var net = require("node:net"); var http = require("node:http"); - var util3 = require_util(); + var util4 = require_util(); + var { ClientStats } = require_stats(); var { channels } = require_diagnostics(); var Request = require_request(); var DispatcherBase = require_dispatcher_base(); @@ -7847,24 +9221,27 @@ var require_client = __commonJS({ kBodyTimeout, kStrictContentLength, kConnector, - kMaxRedirections, kMaxRequests, kCounter, kClose, kDestroy, kDispatch, - kInterceptors, kLocalAddress, kMaxResponseSize, kOnError, kHTTPContext, kMaxConcurrentStreams, - kResume + kHTTP2InitialWindowSize, + kHTTP2ConnectionWindowSize, + kResume, + kPingInterval } = require_symbols(); var connectH1 = require_client_h1(); var connectH2 = require_client_h2(); - var deprecatedInterceptorWarned = false; var kClosedResolve = /* @__PURE__ */ Symbol("kClosedResolve"); + var getDefaultNodeMaxHeaderSize = http && http.maxHeaderSize && Number.isInteger(http.maxHeaderSize) && http.maxHeaderSize > 0 ? () => http.maxHeaderSize : () => { + throw new InvalidArgumentError("http module not available or http.maxHeaderSize invalid"); + }; var noop3 = () => { }; function getPipelining(client) { @@ -7877,7 +9254,6 @@ var require_client = __commonJS({ * @param {import('../../types/client.js').Client.Options} options */ constructor(url2, { - interceptors, maxHeaderSize, headersTimeout, socketTimeout, @@ -7895,7 +9271,6 @@ var require_client = __commonJS({ tls, strictContentLength, maxCachedSessions, - maxRedirections, connect: connect2, maxRequestsPerClient, localAddress, @@ -7905,9 +9280,13 @@ var require_client = __commonJS({ // h2 maxConcurrentStreams, allowH2, - webSocket + useH2c, + initialWindowSize, + connectionWindowSize, + pingInterval, + webSocket, + eventSource } = {}) { - super({ webSocket }); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -7923,8 +9302,12 @@ var require_client = __commonJS({ if (maxKeepAliveTimeout !== void 0) { throw new InvalidArgumentError("unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead"); } - if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { - throw new InvalidArgumentError("invalid maxHeaderSize"); + if (maxHeaderSize != null) { + if (!Number.isInteger(maxHeaderSize) || maxHeaderSize < 1) { + throw new InvalidArgumentError("invalid maxHeaderSize"); + } + } else { + maxHeaderSize = getDefaultNodeMaxHeaderSize(); } if (socketPath != null && typeof socketPath !== "string") { throw new InvalidArgumentError("invalid socketPath"); @@ -7950,9 +9333,6 @@ var require_client = __commonJS({ if (connect2 != null && typeof connect2 !== "function" && typeof connect2 !== "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"); } @@ -7971,32 +9351,42 @@ var require_client = __commonJS({ if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== "number" || maxConcurrentStreams < 1)) { throw new InvalidArgumentError("maxConcurrentStreams must be a positive integer, greater than 0"); } + if (useH2c != null && typeof useH2c !== "boolean") { + throw new InvalidArgumentError("useH2c must be a valid boolean value"); + } + if (initialWindowSize != null && (!Number.isInteger(initialWindowSize) || initialWindowSize < 1)) { + throw new InvalidArgumentError("initialWindowSize must be a positive integer, greater than 0"); + } + if (connectionWindowSize != null && (!Number.isInteger(connectionWindowSize) || connectionWindowSize < 1)) { + throw new InvalidArgumentError("connectionWindowSize must be a positive integer, greater than 0"); + } + if (pingInterval != null && (typeof pingInterval !== "number" || !Number.isInteger(pingInterval) || pingInterval < 0)) { + throw new InvalidArgumentError("pingInterval must be a positive integer, greater or equal to 0"); + } + super({ webSocket, eventSource }); if (typeof connect2 !== "function") { connect2 = buildConnector({ ...tls, maxCachedSessions, allowH2, + useH2c, socketPath, timeout: connectTimeout, - ...autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0, + ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0, ...connect2 }); - } - 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 })]; + const customConnect = connect2; + connect2 = (opts, callback) => customConnect({ + ...opts, + ...socketPath != null ? { socketPath } : null, + ...allowH2 != null ? { allowH2 } : null + }, callback); } - this[kUrl] = util3.parseOrigin(url2); + this[kUrl] = util4.parseOrigin(url2); this[kConnector] = connect2; this[kPipelining] = pipelining != null ? pipelining : 1; - this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize; + this[kMaxHeadersSize] = maxHeaderSize; this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout; this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 6e5 : keepAliveMaxTimeout; this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold; @@ -8010,12 +9400,14 @@ var require_client = __commonJS({ this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 3e5; this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 3e5; 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; this[kHTTPContext] = null; + this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100; + this[kHTTP2InitialWindowSize] = initialWindowSize != null ? initialWindowSize : 262144; + this[kHTTP2ConnectionWindowSize] = connectionWindowSize != null ? connectionWindowSize : 524288; + this[kPingInterval] = pingInterval != null ? pingInterval : 6e4; this[kQueue] = []; this[kRunningIdx] = 0; this[kPendingIdx] = 0; @@ -8029,6 +9421,9 @@ var require_client = __commonJS({ this[kPipelining] = value; this[kResume](true); } + get stats() { + return new ClientStats(this); + } get [kPending]() { return this[kQueue].length - this[kPendingIdx]; } @@ -8046,17 +9441,15 @@ var require_client = __commonJS({ 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, handler2) { - const origin = opts.origin || this[kUrl].origin; - const request3 = new Request(origin, opts, handler2); + const request3 = new Request(this[kUrl].origin, opts, handler2); this[kQueue].push(request3); if (this[kResuming]) { - } else if (util3.bodyLength(request3.body) == null && util3.isIterable(request3.body)) { + } else if (util4.bodyLength(request3.body) == null && util4.isIterable(request3.body)) { this[kResuming] = 1; queueMicrotask(() => resume(this)); } else { @@ -8067,28 +9460,30 @@ var require_client = __commonJS({ } return this[kNeedDrain] < 2; } - async [kClose]() { - return new Promise((resolve14) => { + [kClose]() { + return new Promise((resolve15) => { if (this[kSize]) { - this[kClosedResolve] = resolve14; + this[kClosedResolve] = resolve15; } else { - resolve14(null); + resolve15(null); } }); } - async [kDestroy](err) { - return new Promise((resolve14) => { + [kDestroy](err) { + return new Promise((resolve15) => { const requests = this[kQueue].splice(this[kPendingIdx]); for (let i = 0; i < requests.length; i++) { const request3 = requests[i]; - util3.errorRequest(this, request3, err); + if (request3 != null) { + util4.errorRequest(this, request3, err); + } } const callback = () => { if (this[kClosedResolve]) { this[kClosedResolve](); this[kClosedResolve] = null; } - resolve14(null); + resolve15(null); }; if (this[kHTTPContext]) { this[kHTTPContext].destroy(err, callback); @@ -8100,19 +9495,20 @@ var require_client = __commonJS({ }); } }; - var createRedirectInterceptor = require_redirect_interceptor(); function onError(client, err) { if (client[kRunning] === 0 && err.code !== "UND_ERR_INFO" && err.code !== "UND_ERR_SOCKET") { assert(client[kPendingIdx] === client[kRunningIdx]); const requests = client[kQueue].splice(client[kRunningIdx]); for (let i = 0; i < requests.length; i++) { const request3 = requests[i]; - util3.errorRequest(client, request3, err); + if (request3 != null) { + util4.errorRequest(client, request3, err); + } } assert(client[kSize] === 0); } } - async function connect(client) { + function connect(client) { assert(!client[kConnecting]); assert(!client[kHTTPContext]); let { host, hostname, protocol, port } = client[kUrl]; @@ -8120,7 +9516,7 @@ var require_client = __commonJS({ const idx = hostname.indexOf("]"); assert(idx !== -1); const ip = hostname.substring(1, idx); - assert(net.isIP(ip)); + assert(net.isIPv6(ip)); hostname = ip; } client[kConnecting] = true; @@ -8139,86 +9535,91 @@ var require_client = __commonJS({ }); } try { - const socket = await new Promise((resolve14, reject) => { - client[kConnector]({ + client[kConnector]({ + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, (err, socket) => { + if (err) { + handleConnectError(client, err, { host, hostname, protocol, port }); + client[kResume](); + return; + } + if (client.destroyed) { + util4.destroy(socket.on("error", noop3), new ClientDestroyedError()); + client[kResume](); + return; + } + assert(socket); + try { + client[kHTTPContext] = socket.alpnProtocol === "h2" ? connectH2(client, socket) : connectH1(client, socket); + } catch (err2) { + socket.destroy().on("error", noop3); + handleConnectError(client, err2, { host, hostname, protocol, port }); + client[kResume](); + return; + } + 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]); + client[kResume](); + }); + } catch (err) { + handleConnectError(client, err, { host, hostname, protocol, port }); + client[kResume](); + } + } + function handleConnectError(client, err, { host, hostname, protocol, port }) { + 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] - }, (err, socket2) => { - if (err) { - reject(err); - } else { - resolve14(socket2); - } - }); + }, + connector: client[kConnector], + error: err }); - if (client.destroyed) { - util3.destroy(socket.on("error", noop3), 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", noop3); - 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 request3 = client[kQueue][client[kPendingIdx]++]; - util3.errorRequest(client, request3, err); - } - } else { - onError(client, 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 request3 = client[kQueue][client[kPendingIdx]++]; + util4.errorRequest(client, request3, err); } - client.emit("connectionError", client[kUrl], [client], err); + } else { + onError(client, err); } - client[kResume](); + client.emit("connectionError", client[kUrl], [client], err); } function emitDrain(client) { client[kNeedDrain] = 0; @@ -8269,6 +9670,9 @@ var require_client = __commonJS({ return; } const request3 = client[kQueue][client[kPendingIdx]]; + if (request3 === null) { + return; + } if (client[kUrl].protocol === "https:" && client[kServerName] !== request3.servername) { if (client[kRunning] > 0) { return; @@ -8310,26 +9714,36 @@ var require_fixed_queue = __commonJS({ var kSize = 2048; var kMask = kSize - 1; var FixedCircularBuffer = class { - constructor() { - this.bottom = 0; - this.top = 0; - this.list = new Array(kSize); - this.next = null; - } + /** @type {number} */ + bottom = 0; + /** @type {number} */ + top = 0; + /** @type {Array} */ + list = new Array(kSize).fill(void 0); + /** @type {T|null} */ + next = null; + /** @returns {boolean} */ isEmpty() { return this.top === this.bottom; } + /** @returns {boolean} */ isFull() { return (this.top + 1 & kMask) === this.bottom; } + /** + * @param {T} data + * @returns {void} + */ push(data) { this.list[this.top] = data; this.top = this.top + 1 & kMask; } + /** @returns {T|null} */ shift() { const nextItem = this.list[this.bottom]; - if (nextItem === void 0) + if (nextItem === void 0) { return null; + } this.list[this.bottom] = void 0; this.bottom = this.bottom + 1 & kMask; return nextItem; @@ -8339,20 +9753,24 @@ var require_fixed_queue = __commonJS({ constructor() { this.head = this.tail = new FixedCircularBuffer(); } + /** @returns {boolean} */ isEmpty() { return this.head.isEmpty(); } + /** @param {T} data */ push(data) { if (this.head.isFull()) { this.head = this.head.next = new FixedCircularBuffer(); } this.head.push(data); } + /** @returns {T|null} */ shift() { const tail = this.tail; const next = tail.shift(); if (tail.isEmpty() && tail.next !== null) { this.tail = tail.next; + tail.next = null; } return next; } @@ -8360,46 +9778,14 @@ var require_fixed_queue = __commonJS({ } }); -// node_modules/undici/lib/dispatcher/pool-stats.js -var require_pool_stats = __commonJS({ - "node_modules/undici/lib/dispatcher/pool-stats.js"(exports2, module2) { - var { kFree, kConnected, kPending, kQueued, kRunning, kSize } = require_symbols(); - var kPool = /* @__PURE__ */ Symbol("pool"); - var PoolStats = class { - 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]; - } - }; - module2.exports = PoolStats; - } -}); - // node_modules/undici/lib/dispatcher/pool-base.js var require_pool_base = __commonJS({ "node_modules/undici/lib/dispatcher/pool-base.js"(exports2, module2) { "use strict"; + var { PoolStats } = require_stats(); var DispatcherBase = require_dispatcher_base(); var FixedQueue = require_fixed_queue(); var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require_symbols(); - var PoolStats = require_pool_stats(); var kClients = /* @__PURE__ */ Symbol("clients"); var kNeedDrain = /* @__PURE__ */ Symbol("needDrain"); var kQueue = /* @__PURE__ */ Symbol("queue"); @@ -8411,53 +9797,63 @@ var require_pool_base = __commonJS({ var kGetDispatcher = /* @__PURE__ */ Symbol("get dispatcher"); var kAddClient = /* @__PURE__ */ Symbol("add client"); var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); - var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class 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 queue2 = pool[kQueue]; - let needDrain = false; - while (!needDrain) { - const item = queue2.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]); + [kQueue] = new FixedQueue(); + [kQueued] = 0; + [kClients] = []; + [kNeedDrain] = false; + [kOnDrain](client, origin, targets) { + const queue2 = this[kQueue]; + let needDrain = false; + while (!needDrain) { + const item = queue2.shift(); + if (!item) { + break; } - if (pool[kClosedResolve] && queue2.isEmpty()) { - Promise.all(pool[kClients].map((c) => c.close())).then(pool[kClosedResolve]); + this[kQueued]--; + needDrain = !client.dispatch(item.opts, item.handler); + } + client[kNeedDrain] = needDrain; + if (!needDrain && this[kNeedDrain]) { + this[kNeedDrain] = false; + this.emit("drain", origin, [this, ...targets]); + } + if (this[kClosedResolve] && queue2.isEmpty()) { + const closeAll = []; + for (let i = 0; i < this[kClients].length; i++) { + const client2 = this[kClients][i]; + if (!client2.destroyed) { + closeAll.push(client2.close()); + } } - }; - 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); + return Promise.all(closeAll).then(this[kClosedResolve]); + } } + [kOnConnect] = (origin, targets) => { + this.emit("connect", origin, [this, ...targets]); + }; + [kOnDisconnect] = (origin, targets, err) => { + this.emit("disconnect", origin, [this, ...targets], err); + }; + [kOnConnectionError] = (origin, targets, err) => { + this.emit("connectionError", origin, [this, ...targets], err); + }; get [kBusy]() { return this[kNeedDrain]; } get [kConnected]() { - return this[kClients].filter((client) => client[kConnected]).length; + let ret = 0; + for (const { [kConnected]: connected } of this[kClients]) { + ret += connected; + } + return ret; } get [kFree]() { - return this[kClients].filter((client) => client[kConnected] && !client[kNeedDrain]).length; + let ret = 0; + for (const { [kConnected]: connected, [kNeedDrain]: needDrain } of this[kClients]) { + ret += connected && !needDrain; + } + return ret; } get [kPending]() { let ret = this[kQueued]; @@ -8481,18 +9877,25 @@ var require_pool_base = __commonJS({ return ret; } get stats() { - return this[kStats]; + return new PoolStats(this); } - async [kClose]() { + [kClose]() { if (this[kQueue].isEmpty()) { - await Promise.all(this[kClients].map((c) => c.close())); + const closeAll = []; + for (let i = 0; i < this[kClients].length; i++) { + const client = this[kClients][i]; + if (!client.destroyed) { + closeAll.push(client.close()); + } + } + return Promise.all(closeAll); } else { - await new Promise((resolve14) => { - this[kClosedResolve] = resolve14; + return new Promise((resolve15) => { + this[kClosedResolve] = resolve15; }); } } - async [kDestroy](err) { + [kDestroy](err) { while (true) { const item = this[kQueue].shift(); if (!item) { @@ -8500,7 +9903,11 @@ var require_pool_base = __commonJS({ } item.handler.onError(err); } - await Promise.all(this[kClients].map((c) => c.destroy(err))); + const destroyAll = new Array(this[kClients].length); + for (let i = 0; i < this[kClients].length; i++) { + destroyAll[i] = this[kClients][i].destroy(err); + } + return Promise.all(destroyAll); } [kDispatch](opts, handler2) { const dispatcher = this[kGetDispatcher](); @@ -8515,12 +9922,12 @@ var require_pool_base = __commonJS({ return !this[kNeedDrain]; } [kAddClient](client) { - client.on("drain", this[kOnDrain]).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]); + client.on("drain", this[kOnDrain].bind(this, client)).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]); + this[kOnDrain](client, client[kUrl], [client, this]); } }); } @@ -8556,14 +9963,15 @@ var require_pool = __commonJS({ kClients, kNeedDrain, kAddClient, - kGetDispatcher + kGetDispatcher, + kRemoveClient } = require_pool_base(); var Client = require_client(); var { InvalidArgumentError } = require_errors(); - var util3 = require_util(); - var { kUrl, kInterceptors } = require_symbols(); + var util4 = require_util(); + var { kUrl } = require_symbols(); var buildConnector = require_connect(); var kOptions = /* @__PURE__ */ Symbol("options"); var kConnections = /* @__PURE__ */ Symbol("connections"); @@ -8583,6 +9991,7 @@ var require_pool = __commonJS({ autoSelectFamily, autoSelectFamilyAttemptTimeout, allowH2, + clientTtl, ...options } = {}) { if (connections != null && (!Number.isFinite(connections) || connections < 0)) { @@ -8601,17 +10010,23 @@ var require_pool = __commonJS({ allowH2, socketPath, timeout: connectTimeout, - ...autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0, + ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0, ...connect }); } super(options); - this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; - this[kUrl] = util3.parseOrigin(origin); - this[kOptions] = { ...util3.deepClone(options), connect, allowH2 }; + this[kUrl] = util4.parseOrigin(origin); + this[kOptions] = { ...util4.deepClone(options), connect, allowH2, clientTtl, socketPath }; this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : void 0; this[kFactory] = factory; + this.on("connect", (origin2, targets) => { + if (clientTtl != null && clientTtl > 0) { + for (const target of targets) { + Object.assign(target, { ttl: Date.now() }); + } + } + }); this.on("connectionError", (origin2, targets, error3) => { for (const target of targets) { const idx = this[kClients].indexOf(target); @@ -8622,8 +10037,11 @@ var require_pool = __commonJS({ }); } [kGetDispatcher]() { + const clientTtlOption = this[kOptions].clientTtl; for (const client of this[kClients]) { - if (!client[kNeedDrain]) { + if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && Date.now() - client.ttl > clientTtlOption) { + this[kRemoveClient](client); + } else if (!client[kNeedDrain]) { return client; } } @@ -8655,8 +10073,8 @@ var require_balanced_pool = __commonJS({ kGetDispatcher } = require_pool_base(); var Pool = require_pool(); - var { kUrl, kInterceptors } = require_symbols(); - var { parseOrigin } = require_util(); + var { kUrl } = require_symbols(); + var util4 = require_util(); var kFactory = /* @__PURE__ */ Symbol("factory"); var kOptions = /* @__PURE__ */ Symbol("options"); var kGreatestCommonDivisor = /* @__PURE__ */ Symbol("kGreatestCommonDivisor"); @@ -8678,9 +10096,15 @@ var require_balanced_pool = __commonJS({ return new Pool(origin, opts); } var BalancedPool = class extends PoolBase { - constructor(upstreams = [], { factory = defaultFactory, ...opts } = {}) { - super(); - this[kOptions] = opts; + constructor(upstreams = [], { factory = defaultFactory, connect, tls, ...opts } = {}) { + if (typeof factory !== "function") { + throw new InvalidArgumentError("factory must be a function."); + } + super(opts); + if (connect && typeof connect !== "function") connect = { ...connect }; + if (tls && typeof tls !== "function") tls = { ...tls }; + this[kOptions] = { ...util4.deepClone(opts), connect, tls }; + this[kOptions].interceptors = opts.interceptors ? { ...opts.interceptors } : void 0; this[kIndex] = -1; this[kCurrentWeight] = 0; this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100; @@ -8688,10 +10112,6 @@ var require_balanced_pool = __commonJS({ 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); @@ -8699,11 +10119,11 @@ var require_balanced_pool = __commonJS({ this._updateBalancedPoolStats(); } addUpstream(upstream) { - const upstreamOrigin = parseOrigin(upstream).origin; + const upstreamOrigin = util4.parseOrigin(upstream).origin; if (this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true)) { return this; } - const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])); + const pool = this[kFactory](upstreamOrigin, this[kOptions]); this[kAddClient](pool); pool.on("connect", () => { pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]); @@ -8733,13 +10153,17 @@ var require_balanced_pool = __commonJS({ this[kGreatestCommonDivisor] = result; } removeUpstream(upstream) { - const upstreamOrigin = parseOrigin(upstream).origin; + const upstreamOrigin = util4.parseOrigin(upstream).origin; const pool = this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true); if (pool) { this[kRemoveClient](pool); } return this; } + getUpstream(upstream) { + const upstreamOrigin = util4.parseOrigin(upstream).origin; + return this[kClients].find((pool) => pool[kUrl].origin === upstreamOrigin && pool.closed !== true && pool.destroyed !== true); + } get upstreams() { return this[kClients].filter((dispatcher) => dispatcher.closed !== true && dispatcher.destroyed !== true).map((p) => p[kUrl].origin); } @@ -8782,48 +10206,165 @@ var require_balanced_pool = __commonJS({ } }); +// node_modules/undici/lib/dispatcher/round-robin-pool.js +var require_round_robin_pool = __commonJS({ + "node_modules/undici/lib/dispatcher/round-robin-pool.js"(exports2, module2) { + "use strict"; + var { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kGetDispatcher, + kRemoveClient + } = require_pool_base(); + var Client = require_client(); + var { + InvalidArgumentError + } = require_errors(); + var util4 = require_util(); + var { kUrl } = require_symbols(); + var buildConnector = require_connect(); + var kOptions = /* @__PURE__ */ Symbol("options"); + var kConnections = /* @__PURE__ */ Symbol("connections"); + var kFactory = /* @__PURE__ */ Symbol("factory"); + var kIndex = /* @__PURE__ */ Symbol("index"); + function defaultFactory(origin, opts) { + return new Client(origin, opts); + } + var RoundRobinPool = class extends PoolBase { + constructor(origin, { + connections, + factory = defaultFactory, + connect, + connectTimeout, + tls, + maxCachedSessions, + socketPath, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + allowH2, + clientTtl, + ...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, + ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0, + ...connect + }); + } + super(); + this[kConnections] = connections || null; + this[kUrl] = util4.parseOrigin(origin); + this[kOptions] = { ...util4.deepClone(options), connect, allowH2, clientTtl, socketPath }; + this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : void 0; + this[kFactory] = factory; + this[kIndex] = -1; + this.on("connect", (origin2, targets) => { + if (clientTtl != null && clientTtl > 0) { + for (const target of targets) { + Object.assign(target, { ttl: Date.now() }); + } + } + }); + this.on("connectionError", (origin2, targets, error3) => { + for (const target of targets) { + const idx = this[kClients].indexOf(target); + if (idx !== -1) { + this[kClients].splice(idx, 1); + } + } + }); + } + [kGetDispatcher]() { + const clientTtlOption = this[kOptions].clientTtl; + const clientsLength = this[kClients].length; + if (clientsLength === 0) { + const dispatcher = this[kFactory](this[kUrl], this[kOptions]); + this[kAddClient](dispatcher); + return dispatcher; + } + let checked = 0; + while (checked < clientsLength) { + this[kIndex] = (this[kIndex] + 1) % clientsLength; + const client = this[kClients][this[kIndex]]; + if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && Date.now() - client.ttl > clientTtlOption) { + this[kRemoveClient](client); + checked++; + continue; + } + if (!client[kNeedDrain]) { + return client; + } + checked++; + } + if (!this[kConnections] || clientsLength < this[kConnections]) { + const dispatcher = this[kFactory](this[kUrl], this[kOptions]); + this[kAddClient](dispatcher); + return dispatcher; + } + } + }; + module2.exports = RoundRobinPool; + } +}); + // node_modules/undici/lib/dispatcher/agent.js var require_agent = __commonJS({ "node_modules/undici/lib/dispatcher/agent.js"(exports2, module2) { "use strict"; - var { InvalidArgumentError } = require_errors(); - var { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require_symbols(); + var { InvalidArgumentError, MaxOriginsReachedError } = require_errors(); + var { kClients, kRunning, kClose, kDestroy, kDispatch, kUrl } = require_symbols(); var DispatcherBase = require_dispatcher_base(); var Pool = require_pool(); var Client = require_client(); - var util3 = require_util(); - var createRedirectInterceptor = require_redirect_interceptor(); + var util4 = require_util(); var kOnConnect = /* @__PURE__ */ Symbol("onConnect"); var kOnDisconnect = /* @__PURE__ */ Symbol("onDisconnect"); var kOnConnectionError = /* @__PURE__ */ Symbol("onConnectionError"); - var kMaxRedirections = /* @__PURE__ */ Symbol("maxRedirections"); var kOnDrain = /* @__PURE__ */ Symbol("onDrain"); var kFactory = /* @__PURE__ */ Symbol("factory"); var kOptions = /* @__PURE__ */ Symbol("options"); + var kOrigins = /* @__PURE__ */ Symbol("origins"); function defaultFactory(origin, opts) { return opts && opts.connections === 1 ? new Client(origin, opts) : new Pool(origin, opts); } var Agent = class extends DispatcherBase { - constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + constructor({ factory = defaultFactory, maxOrigins = Infinity, connect, tls, ...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"); + if (typeof maxOrigins !== "number" || Number.isNaN(maxOrigins) || maxOrigins <= 0) { + throw new InvalidArgumentError("maxOrigins must be a number greater than 0"); } 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] = { ...util3.deepClone(options), connect }; - this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : void 0; - this[kMaxRedirections] = maxRedirections; + if (tls && typeof tls !== "function") { + tls = { ...tls }; + } + this[kOptions] = { ...util4.deepClone(options), maxOrigins, connect, tls }; this[kFactory] = factory; this[kClients] = /* @__PURE__ */ new Map(); + this[kOrigins] = /* @__PURE__ */ new Set(); this[kOnDrain] = (origin, targets) => { this.emit("drain", origin, [this, ...targets]); }; @@ -8839,8 +10380,8 @@ var require_agent = __commonJS({ } get [kRunning]() { let ret = 0; - for (const client of this[kClients].values()) { - ret += client[kRunning]; + for (const { dispatcher } of this[kClients].values()) { + ret += dispatcher[kRunning]; } return ret; } @@ -8851,31 +10392,767 @@ var require_agent = __commonJS({ } else { throw new InvalidArgumentError("opts.origin must be a non-empty string or URL."); } - let dispatcher = this[kClients].get(key); + if (this[kOrigins].size >= this[kOptions].maxOrigins && !this[kOrigins].has(key)) { + throw new MaxOriginsReachedError(); + } + const result = this[kClients].get(key); + let dispatcher = result && result.dispatcher; 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[kClients].set(key, dispatcher); + const closeClientIfUnused = (connected) => { + const result2 = this[kClients].get(key); + if (result2) { + if (connected) result2.count -= 1; + if (result2.count <= 0) { + this[kClients].delete(key); + if (!result2.dispatcher.destroyed) { + result2.dispatcher.close(); + } + } + this[kOrigins].delete(key); + } + }; + dispatcher = this[kFactory](opts.origin, this[kOptions]).on("drain", this[kOnDrain]).on("connect", (origin, targets) => { + const result2 = this[kClients].get(key); + if (result2) { + result2.count += 1; + } + this[kOnConnect](origin, targets); + }).on("disconnect", (origin, targets, err) => { + closeClientIfUnused(true); + this[kOnDisconnect](origin, targets, err); + }).on("connectionError", (origin, targets, err) => { + closeClientIfUnused(false); + this[kOnConnectionError](origin, targets, err); + }); + this[kClients].set(key, { count: 0, dispatcher }); + this[kOrigins].add(key); } return dispatcher.dispatch(opts, handler2); } - async [kClose]() { + [kClose]() { const closePromises = []; - for (const client of this[kClients].values()) { - closePromises.push(client.close()); + for (const { dispatcher } of this[kClients].values()) { + closePromises.push(dispatcher.close()); } this[kClients].clear(); + return Promise.all(closePromises); + } + [kDestroy](err) { + const destroyPromises = []; + for (const { dispatcher } of this[kClients].values()) { + destroyPromises.push(dispatcher.destroy(err)); + } + this[kClients].clear(); + return Promise.all(destroyPromises); + } + get stats() { + const allClientStats = {}; + for (const { dispatcher } of this[kClients].values()) { + if (dispatcher.stats) { + allClientStats[dispatcher[kUrl].origin] = dispatcher.stats; + } + } + return allClientStats; + } + }; + module2.exports = Agent; + } +}); + +// node_modules/undici/lib/core/socks5-utils.js +var require_socks5_utils = __commonJS({ + "node_modules/undici/lib/core/socks5-utils.js"(exports2, module2) { + "use strict"; + var { Buffer: Buffer3 } = require("node:buffer"); + var net = require("node:net"); + var { InvalidArgumentError } = require_errors(); + function parseAddress(address) { + if (net.isIPv4(address)) { + const parts = address.split(".").map(Number); + return { + type: 1, + // IPv4 + buffer: Buffer3.from(parts) + }; + } + if (net.isIPv6(address)) { + return { + type: 4, + // IPv6 + buffer: parseIPv6(address) + }; + } + const domainBuffer = Buffer3.from(address, "utf8"); + if (domainBuffer.length > 255) { + throw new InvalidArgumentError("Domain name too long (max 255 bytes)"); + } + return { + type: 3, + // Domain + buffer: Buffer3.concat([Buffer3.from([domainBuffer.length]), domainBuffer]) + }; + } + function parseIPv6(address) { + const buffer = Buffer3.alloc(16); + let normalizedAddress = address; + if (address.includes(".")) { + const lastColonIndex = address.lastIndexOf(":"); + const ipv4Part = address.slice(lastColonIndex + 1); + if (net.isIPv4(ipv4Part)) { + const octets = ipv4Part.split(".").map(Number); + const high = (octets[0] << 8 | octets[1]).toString(16); + const low = (octets[2] << 8 | octets[3]).toString(16); + normalizedAddress = `${address.slice(0, lastColonIndex)}:${high}:${low}`; + } + } + const doubleColonIndex = normalizedAddress.indexOf("::"); + if (doubleColonIndex !== -1) { + const before = normalizedAddress.slice(0, doubleColonIndex); + const after = normalizedAddress.slice(doubleColonIndex + 2); + const beforeParts = before === "" ? [] : before.split(":"); + const afterParts = after === "" ? [] : after.split(":"); + let bufferIndex = 0; + for (const part of beforeParts) { + buffer.writeUInt16BE(parseInt(part, 16), bufferIndex); + bufferIndex += 2; + } + bufferIndex = 16 - afterParts.length * 2; + for (const part of afterParts) { + buffer.writeUInt16BE(parseInt(part, 16), bufferIndex); + bufferIndex += 2; + } + } else { + const parts = normalizedAddress.split(":"); + for (let i = 0; i < parts.length; i++) { + buffer.writeUInt16BE(parseInt(parts[i], 16), i * 2); + } + } + return buffer; + } + function buildAddressBuffer(type, addressBuffer, port) { + const portBuffer = Buffer3.allocUnsafe(2); + portBuffer.writeUInt16BE(port, 0); + return Buffer3.concat([ + Buffer3.from([type]), + addressBuffer, + portBuffer + ]); + } + function parseResponseAddress(buffer, offset = 0) { + if (buffer.length < offset + 1) { + throw new InvalidArgumentError("Buffer too small to contain address type"); + } + const addressType = buffer[offset]; + let address; + let currentOffset = offset + 1; + switch (addressType) { + case 1: { + if (buffer.length < currentOffset + 6) { + throw new InvalidArgumentError("Buffer too small for IPv4 address"); + } + address = Array.from(buffer.subarray(currentOffset, currentOffset + 4)).join("."); + currentOffset += 4; + break; + } + case 3: { + if (buffer.length < currentOffset + 1) { + throw new InvalidArgumentError("Buffer too small for domain length"); + } + const domainLength = buffer[currentOffset]; + currentOffset += 1; + if (buffer.length < currentOffset + domainLength + 2) { + throw new InvalidArgumentError("Buffer too small for domain address"); + } + address = buffer.subarray(currentOffset, currentOffset + domainLength).toString("utf8"); + currentOffset += domainLength; + break; + } + case 4: { + if (buffer.length < currentOffset + 18) { + throw new InvalidArgumentError("Buffer too small for IPv6 address"); + } + const parts = []; + for (let i = 0; i < 8; i++) { + const value = buffer.readUInt16BE(currentOffset + i * 2); + parts.push(value.toString(16)); + } + address = parts.join(":"); + currentOffset += 16; + break; + } + default: + throw new InvalidArgumentError(`Invalid address type: ${addressType}`); + } + if (buffer.length < currentOffset + 2) { + throw new InvalidArgumentError("Buffer too small for port"); + } + const port = buffer.readUInt16BE(currentOffset); + currentOffset += 2; + return { + address, + port, + bytesRead: currentOffset - offset + }; + } + function createReplyError(replyCode) { + const messages = { + 1: "General SOCKS server failure", + 2: "Connection not allowed by ruleset", + 3: "Network unreachable", + 4: "Host unreachable", + 5: "Connection refused", + 6: "TTL expired", + 7: "Command not supported", + 8: "Address type not supported" + }; + const message = messages[replyCode] || `Unknown SOCKS5 error code: ${replyCode}`; + const error3 = new Error(message); + error3.code = `SOCKS5_${replyCode}`; + return error3; + } + module2.exports = { + parseAddress, + parseIPv6, + buildAddressBuffer, + parseResponseAddress, + createReplyError + }; + } +}); + +// node_modules/undici/lib/core/socks5-client.js +var require_socks5_client = __commonJS({ + "node_modules/undici/lib/core/socks5-client.js"(exports2, module2) { + "use strict"; + var { EventEmitter: EventEmitter2 } = require("node:events"); + var { Buffer: Buffer3 } = require("node:buffer"); + var { InvalidArgumentError, Socks5ProxyError } = require_errors(); + var { debuglog } = require("node:util"); + var { parseAddress } = require_socks5_utils(); + var debug6 = debuglog("undici:socks5"); + var EMPTY_BUFFER = Buffer3.alloc(0); + var SOCKS_VERSION = 5; + var AUTH_METHODS = { + NO_AUTH: 0, + GSSAPI: 1, + USERNAME_PASSWORD: 2, + NO_ACCEPTABLE: 255 + }; + var COMMANDS = { + CONNECT: 1, + BIND: 2, + UDP_ASSOCIATE: 3 + }; + var ADDRESS_TYPES = { + IPV4: 1, + DOMAIN: 3, + IPV6: 4 + }; + var REPLY_CODES = { + SUCCEEDED: 0, + GENERAL_FAILURE: 1, + CONNECTION_NOT_ALLOWED: 2, + NETWORK_UNREACHABLE: 3, + HOST_UNREACHABLE: 4, + CONNECTION_REFUSED: 5, + TTL_EXPIRED: 6, + COMMAND_NOT_SUPPORTED: 7, + ADDRESS_TYPE_NOT_SUPPORTED: 8 + }; + var STATES = { + INITIAL: "initial", + HANDSHAKING: "handshaking", + AUTHENTICATING: "authenticating", + AUTHENTICATED: "authenticated", + CONNECTING: "connecting", + CONNECTED: "connected", + ERROR: "error", + CLOSED: "closed" + }; + var Socks5Client = class extends EventEmitter2 { + constructor(socket, options = {}) { + super(); + if (!socket) { + throw new InvalidArgumentError("socket is required"); + } + this.socket = socket; + this.options = options; + this.state = STATES.INITIAL; + this.buffer = EMPTY_BUFFER; + this.onSocketData = this.onData.bind(this); + this.onSocketError = this.onError.bind(this); + this.onSocketClose = this.onClose.bind(this); + this.authMethods = []; + if (options.username && options.password) { + this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD); + } + this.authMethods.push(AUTH_METHODS.NO_AUTH); + this.socket.on("data", this.onSocketData); + this.socket.on("error", this.onSocketError); + this.socket.on("close", this.onSocketClose); + } + /** + * Handle incoming data from the socket + */ + onData(data) { + debug6("received data", data.length, "bytes in state", this.state); + this.buffer = Buffer3.concat([this.buffer, data]); + try { + switch (this.state) { + case STATES.HANDSHAKING: + this.handleHandshakeResponse(); + break; + case STATES.AUTHENTICATING: + this.handleAuthResponse(); + break; + case STATES.CONNECTING: + this.handleConnectResponse(); + break; + } + } catch (err) { + this.onError(err); + } + } + /** + * Handle socket errors + */ + onError(err) { + debug6("socket error", err); + this.state = STATES.ERROR; + this.emit("error", err); + this.destroy(); + } + /** + * Handle socket close + */ + onClose() { + debug6("socket closed"); + this.state = STATES.CLOSED; + this.emit("close"); + } + /** + * Destroy the client and underlying socket + */ + destroy() { + if (this.socket && !this.socket.destroyed) { + this.socket.destroy(); + } + } + markAuthenticated() { + this.state = STATES.AUTHENTICATED; + this.emit("authenticated"); + } + /** + * Start the SOCKS5 handshake + */ + handshake() { + if (this.state !== STATES.INITIAL) { + throw new InvalidArgumentError("Handshake already started"); + } + debug6("starting handshake with", this.authMethods.length, "auth methods"); + this.state = STATES.HANDSHAKING; + const request3 = Buffer3.alloc(2 + this.authMethods.length); + request3[0] = SOCKS_VERSION; + request3[1] = this.authMethods.length; + this.authMethods.forEach((method, i) => { + request3[2 + i] = method; + }); + this.socket.write(request3); + } + /** + * Handle handshake response from server + */ + handleHandshakeResponse() { + if (this.buffer.length < 2) { + return; + } + const version = this.buffer[0]; + const method = this.buffer[1]; + if (version !== SOCKS_VERSION) { + throw new Socks5ProxyError(`Invalid SOCKS version: ${version}`, "UND_ERR_SOCKS5_VERSION"); + } + if (method === AUTH_METHODS.NO_ACCEPTABLE) { + throw new Socks5ProxyError("No acceptable authentication method", "UND_ERR_SOCKS5_AUTH_REJECTED"); + } + this.buffer = this.buffer.subarray(2); + debug6("server selected auth method", method); + if (method === AUTH_METHODS.NO_AUTH) { + this.markAuthenticated(); + } else if (method === AUTH_METHODS.USERNAME_PASSWORD) { + this.state = STATES.AUTHENTICATING; + this.sendAuthRequest(); + } else { + throw new Socks5ProxyError(`Unsupported authentication method: ${method}`, "UND_ERR_SOCKS5_AUTH_METHOD"); + } + } + /** + * Send username/password authentication request + */ + sendAuthRequest() { + const { username, password } = this.options; + if (!username || !password) { + throw new InvalidArgumentError("Username and password required for authentication"); + } + debug6("sending username/password auth"); + const usernameBuffer = Buffer3.from(username); + const passwordBuffer = Buffer3.from(password); + if (usernameBuffer.length > 255 || passwordBuffer.length > 255) { + throw new InvalidArgumentError("Username or password too long"); + } + const request3 = Buffer3.alloc(3 + usernameBuffer.length + passwordBuffer.length); + request3[0] = 1; + request3[1] = usernameBuffer.length; + usernameBuffer.copy(request3, 2); + request3[2 + usernameBuffer.length] = passwordBuffer.length; + passwordBuffer.copy(request3, 3 + usernameBuffer.length); + this.socket.write(request3); + } + /** + * Handle authentication response + */ + handleAuthResponse() { + if (this.buffer.length < 2) { + return; + } + const version = this.buffer[0]; + const status = this.buffer[1]; + if (version !== 1) { + throw new Socks5ProxyError(`Invalid auth sub-negotiation version: ${version}`, "UND_ERR_SOCKS5_AUTH_VERSION"); + } + if (status !== 0) { + throw new Socks5ProxyError("Authentication failed", "UND_ERR_SOCKS5_AUTH_FAILED"); + } + this.buffer = this.buffer.subarray(2); + debug6("authentication successful"); + this.markAuthenticated(); + } + /** + * Send CONNECT command + * @param {string} address - Target address (IP or domain) + * @param {number} port - Target port + */ + connect(address, port) { + if (this.state === STATES.CONNECTING || this.state === STATES.CONNECTED) { + throw new InvalidArgumentError("Connection already in progress"); + } + if (this.state !== STATES.AUTHENTICATED) { + throw new InvalidArgumentError("Client must be authenticated before CONNECT"); + } + debug6("connecting to", address, port); + this.state = STATES.CONNECTING; + const request3 = this.buildConnectRequest(COMMANDS.CONNECT, address, port); + this.socket.write(request3); + } + /** + * Build a SOCKS5 request + */ + buildConnectRequest(command, address, port) { + const { type: addressType, buffer: addressBuffer } = parseAddress(address); + const request3 = Buffer3.alloc(4 + addressBuffer.length + 2); + request3[0] = SOCKS_VERSION; + request3[1] = command; + request3[2] = 0; + request3[3] = addressType; + addressBuffer.copy(request3, 4); + request3.writeUInt16BE(port, 4 + addressBuffer.length); + return request3; + } + /** + * Handle CONNECT response + */ + handleConnectResponse() { + if (this.buffer.length < 4) { + return; + } + const version = this.buffer[0]; + const reply = this.buffer[1]; + const addressType = this.buffer[3]; + if (version !== SOCKS_VERSION) { + throw new Socks5ProxyError(`Invalid SOCKS version in reply: ${version}`, "UND_ERR_SOCKS5_REPLY_VERSION"); + } + let responseLength = 4; + if (addressType === ADDRESS_TYPES.IPV4) { + responseLength += 4 + 2; + } else if (addressType === ADDRESS_TYPES.DOMAIN) { + if (this.buffer.length < 5) { + return; + } + responseLength += 1 + this.buffer[4] + 2; + } else if (addressType === ADDRESS_TYPES.IPV6) { + responseLength += 16 + 2; + } else { + throw new Socks5ProxyError(`Invalid address type in reply: ${addressType}`, "UND_ERR_SOCKS5_ADDR_TYPE"); + } + if (this.buffer.length < responseLength) { + return; + } + if (reply !== REPLY_CODES.SUCCEEDED) { + const errorMessage = this.getReplyErrorMessage(reply); + throw new Socks5ProxyError(`SOCKS5 connection failed: ${errorMessage}`, `UND_ERR_SOCKS5_REPLY_${reply}`); + } + let boundAddress; + let offset = 4; + if (addressType === ADDRESS_TYPES.IPV4) { + boundAddress = Array.from(this.buffer.subarray(offset, offset + 4)).join("."); + offset += 4; + } else if (addressType === ADDRESS_TYPES.DOMAIN) { + const domainLength = this.buffer[offset]; + offset += 1; + boundAddress = this.buffer.subarray(offset, offset + domainLength).toString(); + offset += domainLength; + } else if (addressType === ADDRESS_TYPES.IPV6) { + const parts = []; + for (let i = 0; i < 8; i++) { + const value = this.buffer.readUInt16BE(offset + i * 2); + parts.push(value.toString(16)); + } + boundAddress = parts.join(":"); + offset += 16; + } + const boundPort = this.buffer.readUInt16BE(offset); + this.buffer = EMPTY_BUFFER; + this.state = STATES.CONNECTED; + this.socket.removeListener("data", this.onSocketData); + debug6("connected, bound address:", boundAddress, "port:", boundPort); + this.emit("connected", { address: boundAddress, port: boundPort }); + } + /** + * Get human-readable error message for reply code + */ + getReplyErrorMessage(reply) { + switch (reply) { + case REPLY_CODES.GENERAL_FAILURE: + return "General SOCKS server failure"; + case REPLY_CODES.CONNECTION_NOT_ALLOWED: + return "Connection not allowed by ruleset"; + case REPLY_CODES.NETWORK_UNREACHABLE: + return "Network unreachable"; + case REPLY_CODES.HOST_UNREACHABLE: + return "Host unreachable"; + case REPLY_CODES.CONNECTION_REFUSED: + return "Connection refused"; + case REPLY_CODES.TTL_EXPIRED: + return "TTL expired"; + case REPLY_CODES.COMMAND_NOT_SUPPORTED: + return "Command not supported"; + case REPLY_CODES.ADDRESS_TYPE_NOT_SUPPORTED: + return "Address type not supported"; + default: + return `Unknown error code: ${reply}`; + } + } + }; + module2.exports = { + Socks5Client, + AUTH_METHODS, + COMMANDS, + ADDRESS_TYPES, + REPLY_CODES, + STATES + }; + } +}); + +// node_modules/undici/lib/dispatcher/socks5-proxy-agent.js +var require_socks5_proxy_agent = __commonJS({ + "node_modules/undici/lib/dispatcher/socks5-proxy-agent.js"(exports2, module2) { + "use strict"; + var { URL: URL2 } = require("node:url"); + var tls; + var DispatcherBase = require_dispatcher_base(); + var { InvalidArgumentError } = require_errors(); + var { Socks5Client, STATES } = require_socks5_client(); + var { kDispatch, kClose, kDestroy } = require_symbols(); + var Pool = require_pool(); + var buildConnector = require_connect(); + var { debuglog } = require("node:util"); + var debug6 = debuglog("undici:socks5-proxy"); + var kProxyUrl = /* @__PURE__ */ Symbol("proxy url"); + var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers"); + var kProxyAuth = /* @__PURE__ */ Symbol("proxy auth"); + var kProxyProtocol = /* @__PURE__ */ Symbol("proxy protocol"); + var kPools = /* @__PURE__ */ Symbol("pools"); + var kConnector = /* @__PURE__ */ Symbol("connector"); + var kRequestTls = /* @__PURE__ */ Symbol("request tls settings"); + var experimentalWarningEmitted = false; + var Socks5ProxyAgent = class extends DispatcherBase { + constructor(proxyUrl, options = {}) { + super(); + if (!experimentalWarningEmitted) { + process.emitWarning( + "SOCKS5 proxy support is experimental and subject to change", + "ExperimentalWarning" + ); + experimentalWarningEmitted = true; + } + if (!proxyUrl) { + throw new InvalidArgumentError("Proxy URL is mandatory"); + } + const url2 = typeof proxyUrl === "string" ? new URL2(proxyUrl) : proxyUrl; + if (url2.protocol !== "socks5:" && url2.protocol !== "socks:") { + throw new InvalidArgumentError("Proxy URL must use socks5:// or socks:// protocol"); + } + this[kProxyUrl] = url2; + this[kProxyHeaders] = options.headers || {}; + this[kProxyProtocol] = options.proxyTls ? "https:" : "http:"; + this[kRequestTls] = options.requestTls; + this[kProxyAuth] = { + username: options.username || (url2.username ? decodeURIComponent(url2.username) : null), + password: options.password || (url2.password ? decodeURIComponent(url2.password) : null) + }; + this[kConnector] = options.connect || buildConnector({ + ...options.proxyTls, + servername: options.proxyTls?.servername || url2.hostname + }); + this[kPools] = /* @__PURE__ */ new Map(); + } + /** + * Create a SOCKS5 connection to the proxy + */ + async createSocks5Connection(targetHost, targetPort) { + const proxyHost = this[kProxyUrl].hostname; + const proxyPort = parseInt(this[kProxyUrl].port) || 1080; + debug6("creating SOCKS5 connection to", proxyHost, proxyPort); + const socket = await new Promise((resolve15, reject) => { + this[kConnector]({ + hostname: proxyHost, + host: proxyHost, + port: proxyPort, + protocol: this[kProxyProtocol] + }, (err, socket2) => { + if (err) { + reject(err); + } else { + resolve15(socket2); + } + }); + }); + const socks5Client = new Socks5Client(socket, this[kProxyAuth]); + socks5Client.on("error", (err) => { + debug6("SOCKS5 error:", err); + socket.destroy(); + }); + await socks5Client.handshake(); + await new Promise((resolve15, reject) => { + const timeout = setTimeout(() => { + reject(new Error("SOCKS5 authentication timeout")); + }, 5e3); + const onAuthenticated = () => { + clearTimeout(timeout); + socks5Client.removeListener("error", onError); + resolve15(); + }; + const onError = (err) => { + clearTimeout(timeout); + socks5Client.removeListener("authenticated", onAuthenticated); + reject(err); + }; + if (socks5Client.state === STATES.AUTHENTICATED) { + clearTimeout(timeout); + resolve15(); + } else { + socks5Client.once("authenticated", onAuthenticated); + socks5Client.once("error", onError); + } + }); + await socks5Client.connect(targetHost, targetPort); + await new Promise((resolve15, reject) => { + const timeout = setTimeout(() => { + reject(new Error("SOCKS5 connection timeout")); + }, 5e3); + const onConnected = (info8) => { + debug6("SOCKS5 tunnel established to", targetHost, targetPort, "via", info8); + clearTimeout(timeout); + socks5Client.removeListener("error", onError); + resolve15(); + }; + const onError = (err) => { + clearTimeout(timeout); + socks5Client.removeListener("connected", onConnected); + reject(err); + }; + socks5Client.once("connected", onConnected); + socks5Client.once("error", onError); + }); + return socket; + } + /** + * Dispatch a request through the SOCKS5 proxy + */ + [kDispatch](opts, handler2) { + const { origin } = opts; + debug6("dispatching request to", origin, "via SOCKS5"); + try { + const originKey = String(origin); + let pool = this[kPools].get(originKey); + if (!pool || pool.destroyed || pool.closed) { + pool = new Pool(origin, { + pipelining: opts.pipelining, + connections: opts.connections, + connect: async (connectOpts, callback) => { + try { + const url2 = new URL2(origin); + const targetHost = url2.hostname; + const targetPort = parseInt(url2.port) || (url2.protocol === "https:" ? 443 : 80); + debug6("establishing SOCKS5 connection to", targetHost, targetPort); + const socket = await this.createSocks5Connection(targetHost, targetPort); + let finalSocket = socket; + if (url2.protocol === "https:") { + if (!tls) { + tls = require("node:tls"); + } + debug6("upgrading to TLS"); + finalSocket = tls.connect({ + ...this[kRequestTls], + socket, + servername: this[kRequestTls]?.servername || targetHost + }); + await new Promise((resolve15, reject) => { + finalSocket.once("secureConnect", resolve15); + finalSocket.once("error", reject); + }); + } + callback(null, finalSocket); + } catch (err) { + debug6("SOCKS5 connection error:", err); + callback(err); + } + } + }); + this[kPools].set(originKey, pool); + } + return pool[kDispatch](opts, handler2); + } catch (err) { + debug6("dispatch error:", err); + if (typeof handler2.onResponseError === "function") { + handler2.onResponseError(null, err); + return false; + } else if (typeof handler2.onError === "function") { + handler2.onError(err); + return false; + } else { + throw err; + } + } + } + async [kClose]() { + const closePromises = []; + for (const pool of this[kPools].values()) { + closePromises.push(pool.close()); + } + this[kPools].clear(); await Promise.all(closePromises); } async [kDestroy](err) { const destroyPromises = []; - for (const client of this[kClients].values()) { - destroyPromises.push(client.destroy(err)); + for (const pool of this[kPools].values()) { + destroyPromises.push(pool.destroy(err)); } - this[kClients].clear(); + this[kPools].clear(); await Promise.all(destroyPromises); } }; - module2.exports = Agent; + module2.exports = Socks5ProxyAgent; } }); @@ -8883,14 +11160,15 @@ var require_agent = __commonJS({ var require_proxy_agent = __commonJS({ "node_modules/undici/lib/dispatcher/proxy-agent.js"(exports2, module2) { "use strict"; - var { kProxy, kClose, kDestroy, kDispatch, kInterceptors } = require_symbols(); - var { URL: URL2 } = require("node:url"); + var { kProxy, kClose, kDestroy, kDispatch } = require_symbols(); var Agent = require_agent(); var Pool = require_pool(); var DispatcherBase = require_dispatcher_base(); var { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require_errors(); var buildConnector = require_connect(); var Client = require_client(); + var { channels } = require_diagnostics(); + var Socks5ProxyAgent = require_socks5_proxy_agent(); var kAgent = /* @__PURE__ */ Symbol("proxy agent"); var kClient = /* @__PURE__ */ Symbol("proxy client"); var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers"); @@ -8915,10 +11193,10 @@ var require_proxy_agent = __commonJS({ var Http1ProxyWrapper = class extends DispatcherBase { #client; constructor(proxyUrl, { headers = {}, connect, factory }) { - super(); if (!proxyUrl) { throw new InvalidArgumentError("Proxy URL is mandatory"); } + super(); this[kProxyHeaders] = headers; if (factory) { this.#client = factory(proxyUrl, { connect }); @@ -8944,23 +11222,22 @@ var require_proxy_agent = __commonJS({ } = opts; opts.path = origin + path30; if (!("host" in headers) && !("Host" in headers)) { - const { host } = new URL2(origin); + const { host } = new URL(origin); headers.host = host; } opts.headers = { ...this[kProxyHeaders], ...headers }; return this.#client[kDispatch](opts, handler2); } - async [kClose]() { + [kClose]() { return this.#client.close(); } - async [kDestroy](err) { + [kDestroy](err) { return this.#client.destroy(err); } }; var ProxyAgent2 = class extends DispatcherBase { constructor(opts) { - super(); - if (!opts || typeof opts === "object" && !(opts instanceof URL2) && !opts.uri) { + if (!opts || typeof opts === "object" && !(opts instanceof URL) && !opts.uri) { throw new InvalidArgumentError("Proxy uri is mandatory"); } const { clientFactory = defaultFactory } = opts; @@ -8968,10 +11245,10 @@ var require_proxy_agent = __commonJS({ throw new InvalidArgumentError("Proxy opts.clientFactory must be a function."); } const { proxyTunnel = true } = opts; + super(); const url2 = this.#getUrl(opts); const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url2; 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 || {}; @@ -8989,7 +11266,18 @@ var require_proxy_agent = __commonJS({ this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }); const agentFactory = opts.factory || defaultAgentFactory; const factory = (origin2, options) => { - const { protocol: protocol2 } = new URL2(origin2); + const { protocol: protocol2 } = new URL(origin2); + if (this[kProxy].protocol === "socks5:" || this[kProxy].protocol === "socks:") { + return new Socks5ProxyAgent(this[kProxy].uri, { + headers: this[kProxyHeaders], + connect, + factory: agentFactory, + username: opts.username || username, + password: opts.password || password, + proxyTls: opts.proxyTls, + requestTls: opts.requestTls + }); + } if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") { return new Http1ProxyWrapper(this[kProxy].uri, { headers: this[kProxyHeaders], @@ -8999,30 +11287,47 @@ var require_proxy_agent = __commonJS({ } return agentFactory(origin2, options); }; - this[kClient] = clientFactory(url2, { connect }); + if (protocol === "socks5:" || protocol === "socks:") { + this[kClient] = null; + } else { + this[kClient] = clientFactory(url2, { connect }); + } this[kAgent] = new Agent({ ...opts, factory, connect: async (opts2, callback) => { + if (!this[kClient]) { + callback(new InvalidArgumentError("Cannot establish tunnel connection without a proxy client")); + return; + } let requestedPath = opts2.host; if (!opts2.port) { requestedPath += `:${defaultProtocolPort(opts2.protocol)}`; } try { - const { socket, statusCode } = await this[kClient].connect({ + const connectParams = { origin, port, path: requestedPath, signal: opts2.signal, headers: { ...this[kProxyHeaders], - host: opts2.host + host: opts2.host, + ...opts2.connections == null || opts2.connections > 0 ? { "proxy-connection": "keep-alive" } : {} }, servername: this[kProxyTls]?.servername || proxyHostname - }); + }; + const { socket, statusCode } = await this[kClient].connect(connectParams); if (statusCode !== 200) { socket.on("error", noop3).destroy(); callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)); + return; + } + if (channels.proxyConnected.hasSubscribers) { + channels.proxyConnected.publish({ + socket, + connectParams + }); } if (opts2.protocol !== "https:") { callback(null, socket); @@ -9049,7 +11354,7 @@ var require_proxy_agent = __commonJS({ const headers = buildHeaders(opts.headers); throwIfProxyAuthIsSent(headers); if (headers && !("host" in headers) && !("Host" in headers)) { - const { host } = new URL2(opts.origin); + const { host } = new URL(opts.origin); headers.host = host; } return this[kAgent].dispatch( @@ -9061,25 +11366,31 @@ var require_proxy_agent = __commonJS({ ); } /** - * @param {import('../types/proxy-agent').ProxyAgent.Options | string | URL} opts + * @param {import('../../types/proxy-agent').ProxyAgent.Options | string | URL} opts * @returns {URL} */ #getUrl(opts) { if (typeof opts === "string") { - return new URL2(opts); - } else if (opts instanceof URL2) { + return new URL(opts); + } else if (opts instanceof URL) { return opts; } else { - return new URL2(opts.uri); + return new URL(opts.uri); } } - async [kClose]() { - await this[kAgent].close(); - await this[kClient].close(); + [kClose]() { + const promises7 = [this[kAgent].close()]; + if (this[kClient]) { + promises7.push(this[kClient].close()); + } + return Promise.all(promises7); } - async [kDestroy]() { - await this[kAgent].destroy(); - await this[kClient].destroy(); + [kDestroy]() { + const promises7 = [this[kAgent].destroy()]; + if (this[kClient]) { + promises7.push(this[kClient].destroy()); + } + return Promise.all(promises7); } }; function buildHeaders(headers) { @@ -9114,7 +11425,6 @@ var require_env_http_proxy_agent = __commonJS({ "http:": 80, "https:": 443 }; - var experimentalWarned = false; var EnvHttpProxyAgent = class extends DispatcherBase { #noProxyValue = null; #noProxyEntries = null; @@ -9122,12 +11432,6 @@ var require_env_http_proxy_agent = __commonJS({ 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; @@ -9149,23 +11453,19 @@ var require_env_http_proxy_agent = __commonJS({ const agent = this.#getProxyAgentForUrl(url2); return agent.dispatch(opts, handler2); } - async [kClose]() { - await this[kNoProxyAgent].close(); - if (!this[kHttpProxyAgent][kClosed]) { - await this[kHttpProxyAgent].close(); - } - if (!this[kHttpsProxyAgent][kClosed]) { - await this[kHttpsProxyAgent].close(); - } + [kClose]() { + return Promise.all([ + this[kNoProxyAgent].close(), + !this[kHttpProxyAgent][kClosed] && this[kHttpProxyAgent].close(), + !this[kHttpsProxyAgent][kClosed] && 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); - } + [kDestroy](err) { + return Promise.all([ + this[kNoProxyAgent].destroy(err), + !this[kHttpProxyAgent][kDestroyed] && this[kHttpProxyAgent].destroy(err), + !this[kHttpsProxyAgent][kDestroyed] && this[kHttpsProxyAgent].destroy(err) + ]); } #getProxyAgentForUrl(url2) { let { protocol, host: hostname, port } = url2; @@ -9194,14 +11494,11 @@ var require_env_http_proxy_agent = __commonJS({ if (entry.port && entry.port !== port) { continue; } - if (!/^[.*]/.test(entry.hostname)) { - if (hostname === entry.hostname) { - return false; - } - } else { - if (hostname.endsWith(entry.hostname.replace(/^\*/, ""))) { - return false; - } + if (hostname === entry.hostname) { + return false; + } + if (hostname.slice(-(entry.hostname.length + 1)) === `.${entry.hostname}`) { + return false; } } return true; @@ -9217,7 +11514,8 @@ var require_env_http_proxy_agent = __commonJS({ } const parsed = entry.match(/^(.+):(\d+)$/); noProxyEntries.push({ - hostname: (parsed ? parsed[1] : entry).toLowerCase(), + // strip leading dot or asterisk with dot + hostname: (parsed ? parsed[1] : entry).replace(/^\*?\./, "").toLowerCase(), port: parsed ? Number.parseInt(parsed[2], 10) : 0 }); } @@ -9245,36 +11543,84 @@ var require_retry_handler = __commonJS({ var assert = require("node:assert"); var { kRetryHandlerDefaultRetry } = require_symbols(); var { RequestRetryError } = require_errors(); + var WrapHandler = require_wrap_handler(); var { isDisturbed, - parseHeaders, parseRangeHeader, wrapRequestBody } = require_util(); function calculateRetryAfterHeader(retryAfter) { - const current = Date.now(); - return new Date(retryAfter).getTime() - current; + const retryTime = new Date(retryAfter).getTime(); + return isNaN(retryTime) ? 0 : retryTime - Date.now(); } function validatePartialResponseContentLength(headers, range2, statusCode, retryCount) { const contentLength = headers["content-length"]; if (contentLength == null) { - return null; + return; } if (!Number.isFinite(range2.start) || !Number.isFinite(range2.end)) { - return null; + return; } const length = Number(contentLength); const expectedLength = range2.end - range2.start + 1; if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { + throw new RequestRetryError("Content-Length mismatch", statusCode, { headers, data: { count: retryCount } }); } - return null; } + var RetryController = class { + #paused = false; + #target = null; + set target(target) { + this.#target = target; + if (this.#paused) { + target?.pause(); + } + } + get target() { + return this.#target; + } + pause() { + this.#paused = true; + this.#target?.pause(); + } + resume() { + this.#paused = false; + this.#target?.resume(); + } + abort(reason) { + this.#target?.abort(reason); + } + get paused() { + return this.#paused || (this.#target?.paused ?? false); + } + get aborted() { + return this.#target?.aborted ?? false; + } + get reason() { + return this.#target?.reason ?? null; + } + get rawHeaders() { + return this.#target?.rawHeaders ?? null; + } + set rawHeaders(value) { + if (this.#target) { + this.#target.rawHeaders = value; + } + } + get rawTrailers() { + return this.#target?.rawTrailers ?? null; + } + set rawTrailers(value) { + if (this.#target) { + this.#target.rawTrailers = value; + } + } + }; var RetryHandler = class _RetryHandler { - constructor(opts, handlers) { + constructor(opts, { dispatch, handler: handler2 }) { const { retryOptions, ...dispatchOpts } = opts; const { // Retry scoped @@ -9287,14 +11633,15 @@ var require_retry_handler = __commonJS({ methods, errorCodes, retryAfter, - statusCodes + statusCodes, + throwOnError } = retryOptions ?? {}; - this.dispatch = handlers.dispatch; - this.handler = handlers.handler; + this.error = null; + this.dispatch = dispatch; + this.handler = WrapHandler.wrap(handler2); this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) }; - this.abort = null; - this.aborted = false; this.retryOpts = { + throwOnError: throwOnError ?? true, retry: retryFn ?? _RetryHandler[kRetryHandlerDefaultRetry], retryAfter: retryAfter ?? true, maxTimeout: maxTimeout ?? 30 * 1e3, @@ -9322,38 +11669,77 @@ var require_retry_handler = __commonJS({ }; this.retryCount = 0; this.retryCountCheckpoint = 0; + this.headersSent = false; this.start = 0; this.end = null; this.etag = null; - this.resume = null; - this.handler.onConnect((reason) => { - this.aborted = true; - if (this.abort) { - this.abort(reason); + this.controllerProxy = new RetryController(); + } + onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err) { + if (this.retryOpts.throwOnError) { + if (this.retryOpts.statusCodes.includes(statusCode) === false) { + if (this.headersSent) { + this.handler.onResponseError?.(this.controllerProxy, err); + } else { + this.headersSent = true; + this.checkpointResponseEnd(headers); + this.handler.onResponseStart?.(this.controllerProxy, statusCode, headers, statusMessage); + } } else { - this.reason = reason; + this.error = err; } - }); - } - onRequestSent() { - if (this.handler.onRequestSent) { - this.handler.onRequestSent(); + return; } + if (isDisturbed(this.opts.body)) { + this.headersSent = true; + this.checkpointResponseEnd(headers); + this.handler.onResponseStart?.(this.controllerProxy, statusCode, headers, statusMessage); + return; + } + function shouldRetry(passedErr) { + if (passedErr) { + if (this.headersSent) { + this.handler.onResponseError?.(this.controllerProxy, passedErr); + } else { + this.headersSent = true; + this.checkpointResponseEnd(headers); + this.handler.onResponseStart?.(this.controllerProxy, statusCode, headers, statusMessage); + } + controller.resume(); + return; + } + this.error = err; + controller.resume(); + } + controller.pause(); + this.retryOpts.retry( + err, + { + state: { counter: this.retryCount }, + opts: { retryOptions: this.retryOpts, ...this.opts } + }, + shouldRetry.bind(this) + ); } - onUpgrade(statusCode, headers, socket) { - if (this.handler.onUpgrade) { - this.handler.onUpgrade(statusCode, headers, socket); + checkpointResponseEnd(headers) { + if (this.end == null && this.opts.method !== "HEAD") { + const contentLength = headers["content-length"]; + this.end = contentLength != null ? Number(contentLength) - 1 : null; + assert( + this.end == null || Number.isFinite(this.end), + "invalid content-length" + ); + this.resume = this.end != null; } } - onConnect(abort) { - if (this.aborted) { - abort(this.reason); - } else { - this.abort = abort; + onRequestStart(controller, context5) { + this.controllerProxy.target = controller; + if (!this.headersSent) { + this.handler.onRequestStart?.(this.controllerProxy, context5); } } - onBodySent(chunk) { - if (this.handler.onBodySent) return this.handler.onBodySent(chunk); + onRequestUpgrade(_controller, statusCode, headers, socket) { + this.handler.onRequestUpgrade?.(this.controllerProxy, statusCode, headers, socket); } static [kRetryHandlerDefaultRetry](err, { state, opts }, cb) { const { statusCode, code, headers } = err; @@ -9387,92 +11773,69 @@ var require_retry_handler = __commonJS({ let retryAfterHeader = headers?.["retry-after"]; if (retryAfterHeader) { retryAfterHeader = Number(retryAfterHeader); - retryAfterHeader = Number.isNaN(retryAfterHeader) ? calculateRetryAfterHeader(retryAfterHeader) : retryAfterHeader * 1e3; + retryAfterHeader = Number.isNaN(retryAfterHeader) ? calculateRetryAfterHeader(headers["retry-after"]) : retryAfterHeader * 1e3; } 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); + onResponseStart(controller, statusCode, headers, statusMessage) { + this.error = null; 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; - } + const err = new RequestRetryError("Request failed", statusCode, { + headers, + data: { + count: this.retryCount + } + }); + this.onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err); + return; } - if (this.resume != null) { - this.resume = null; + if (this.headersSent) { 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; + throw new RequestRetryError("server does not support the range header and the payload was partially consumed", statusCode, { + headers, + data: { count: this.retryCount } + }); } const contentRange = parseRangeHeader(headers["content-range"]); if (!contentRange) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; + throw new RequestRetryError("Content-Range mismatch", statusCode, { + headers, + data: { count: this.retryCount } + }); } if (this.etag != null && this.etag !== headers.etag) { - this.abort( - new RequestRetryError("ETag mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; + throw new RequestRetryError("ETag mismatch", statusCode, { + headers, + data: { count: this.retryCount } + }); } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; + validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); + const { start, size, end = size ? size - 1 : null } = contentRange; + if (this.start !== start || this.end != null && this.end !== end) { + throw new RequestRetryError("Content-Range mismatch", statusCode, { + headers, + data: { count: this.retryCount } + }); } - 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; + return; } if (this.end == null) { if (statusCode === 206) { const range2 = parseRangeHeader(headers["content-range"]); if (range2 == null) { - return this.handler.onHeaders( + this.headersSent = true; + this.handler.onResponseStart?.( + this.controllerProxy, statusCode, - rawHeaders, - resume, + headers, statusMessage ); + return; } - const contentLengthError = validatePartialResponseContentLength(headers, range2, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } - const { start, size, end = size - 1 } = range2; + validatePartialResponseContentLength(headers, range2, statusCode, this.retryCount); + const { start, size, end = size ? size - 1 : null } = range2; assert( start != null && Number.isFinite(start), "content-range mismatch" @@ -9490,36 +11853,74 @@ var require_retry_handler = __commonJS({ this.end == null || Number.isFinite(this.end), "invalid content-length" ); - this.resume = resume; + this.resume = true; this.etag = headers.etag != null ? headers.etag : null; - if (this.etag != null && this.etag.startsWith("W/")) { + if (this.etag != null && this.etag[0] === "W" && this.etag[1] === "/") { this.etag = null; } - return this.handler.onHeaders( + this.headersSent = true; + this.handler.onResponseStart?.( + this.controllerProxy, statusCode, - rawHeaders, - resume, + headers, statusMessage ); + } else { + throw new RequestRetryError("Request failed", statusCode, { + headers, + data: { count: this.retryCount } + }); } - const err = new RequestRetryError("Request failed", statusCode, { - headers, - data: { count: this.retryCount } - }); - this.abort(err); - return false; } - onData(chunk) { + onResponseData(_controller, chunk) { + if (this.error) { + return; + } this.start += chunk.length; - return this.handler.onData(chunk); + this.handler.onResponseData?.(this.controllerProxy, chunk); } - onComplete(rawTrailers) { - this.retryCount = 0; - return this.handler.onComplete(rawTrailers); + onResponseEnd(_controller, trailers) { + if (this.error && this.retryOpts.throwOnError) { + throw this.error; + } + if (!this.error) { + this.retryCount = 0; + return this.handler.onResponseEnd?.(this.controllerProxy, trailers); + } + this.retry(); } - onError(err) { - if (this.aborted || isDisturbed(this.opts.body)) { - return this.handler.onError(err); + retry() { + if (this.start !== 0) { + const headers = { range: `bytes=${this.start}-${this.end ?? ""}` }; + 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.onResponseError?.(this.controllerProxy, err); + } + } + onResponseError(controller, err) { + if (controller?.aborted || isDisturbed(this.opts.body) || this.headersSent && !this.resume) { + this.handler.onResponseError?.(this.controllerProxy, err); + return; + } + function shouldRetry(returnedErr) { + if (!returnedErr) { + this.retry(); + return; + } + this.handler?.onResponseError?.(this.controllerProxy, returnedErr); } if (this.retryCount - this.retryCountCheckpoint > 0) { this.retryCount = this.retryCountCheckpoint + (this.retryCount - this.retryCountCheckpoint); @@ -9532,32 +11933,8 @@ var require_retry_handler = __commonJS({ state: { counter: this.retryCount }, opts: { retryOptions: this.retryOpts, ...this.opts } }, - onRetry.bind(this) + shouldRetry.bind(this) ); - function onRetry(err2) { - if (err2 != null || this.aborted || isDisturbed(this.opts.body)) { - return this.handler.onError(err2); - } - if (this.start !== 0) { - const headers = { range: `bytes=${this.start}-${this.end ?? ""}` }; - 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 (err3) { - this.handler.onError(err3); - } - } } }; module2.exports = RetryHandler; @@ -9599,14 +11976,57 @@ var require_retry_agent = __commonJS({ } }); +// node_modules/undici/lib/dispatcher/h2c-client.js +var require_h2c_client = __commonJS({ + "node_modules/undici/lib/dispatcher/h2c-client.js"(exports2, module2) { + "use strict"; + var { InvalidArgumentError } = require_errors(); + var Client = require_client(); + var H2CClient = class extends Client { + constructor(origin, clientOpts) { + if (typeof origin === "string") { + origin = new URL(origin); + } + if (origin.protocol !== "http:") { + throw new InvalidArgumentError( + "h2c-client: Only h2c protocol is supported" + ); + } + const { maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {}; + let defaultMaxConcurrentStreams = 100; + let defaultPipelining = 100; + if (maxConcurrentStreams != null && Number.isInteger(maxConcurrentStreams) && maxConcurrentStreams > 0) { + defaultMaxConcurrentStreams = maxConcurrentStreams; + } + if (pipelining != null && Number.isInteger(pipelining) && pipelining > 0) { + defaultPipelining = pipelining; + } + if (defaultPipelining > defaultMaxConcurrentStreams) { + throw new InvalidArgumentError( + "h2c-client: pipelining cannot be greater than maxConcurrentStreams" + ); + } + super(origin, { + ...opts, + maxConcurrentStreams: defaultMaxConcurrentStreams, + pipelining: defaultPipelining, + allowH2: true, + useH2c: true + }); + } + }; + module2.exports = H2CClient; + } +}); + // node_modules/undici/lib/api/readable.js var require_readable = __commonJS({ "node_modules/undici/lib/api/readable.js"(exports2, module2) { "use strict"; var assert = require("node:assert"); - var { Readable: Readable3 } = require("node:stream"); - var { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require_errors(); - var util3 = require_util(); + var { Readable: Readable4 } = require("node:stream"); + var { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError: AbortError2 } = require_errors(); + var util4 = require_util(); var { ReadableStreamFrom } = require_util(); var kConsume = /* @__PURE__ */ Symbol("kConsume"); var kReading = /* @__PURE__ */ Symbol("kReading"); @@ -9614,9 +12034,19 @@ var require_readable = __commonJS({ var kAbort = /* @__PURE__ */ Symbol("kAbort"); var kContentType = /* @__PURE__ */ Symbol("kContentType"); var kContentLength = /* @__PURE__ */ Symbol("kContentLength"); + var kUsed = /* @__PURE__ */ Symbol("kUsed"); + var kBytesRead = /* @__PURE__ */ Symbol("kBytesRead"); var noop3 = () => { }; - var BodyReadable = class extends Readable3 { + var BodyReadable = class extends Readable4 { + /** + * @param {object} opts + * @param {(this: Readable, size: number) => void} opts.resume + * @param {() => (void | null)} opts.abort + * @param {string} [opts.contentType = ''] + * @param {number} [opts.contentLength] + * @param {number} [opts.highWaterMark = 64 * 1024] + */ constructor({ resume, abort, @@ -9633,84 +12063,155 @@ var require_readable = __commonJS({ this._readableState.dataEmitted = false; this[kAbort] = abort; this[kConsume] = null; + this[kBytesRead] = 0; this[kBody] = null; + this[kUsed] = false; this[kContentType] = contentType; - this[kContentLength] = contentLength; + this[kContentLength] = Number.isFinite(contentLength) ? contentLength : null; this[kReading] = false; } - destroy(err) { + /** + * @param {Error|null} err + * @param {(error:(Error|null)) => void} callback + * @returns {void} + */ + _destroy(err, callback) { if (!err && !this._readableState.endEmitted) { err = new RequestAbortedError(); } if (err) { this[kAbort](); } - return super.destroy(err); - } - _destroy(err, callback) { - if (!this[kReading]) { - setImmediate(() => { - callback(err); - }); + if (!this[kUsed]) { + setImmediate(callback, err); } else { callback(err); } } - on(ev, ...args) { - if (ev === "data" || ev === "readable") { + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + on(event, listener) { + if (event === "data" || event === "readable") { this[kReading] = true; + this[kUsed] = true; } - return super.on(ev, ...args); + return super.on(event, listener); } - addListener(ev, ...args) { - return this.on(ev, ...args); + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + addListener(event, listener) { + return this.on(event, listener); } - off(ev, ...args) { - const ret = super.off(ev, ...args); - if (ev === "data" || ev === "readable") { + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + off(event, listener) { + const ret = super.off(event, listener); + if (event === "data" || event === "readable") { this[kReading] = this.listenerCount("data") > 0 || this.listenerCount("readable") > 0; } return ret; } - removeListener(ev, ...args) { - return this.off(ev, ...args); + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + removeListener(event, listener) { + return this.off(event, listener); } + /** + * @param {Buffer|null} chunk + * @returns {boolean} + */ push(chunk) { - if (this[kConsume] && chunk !== null) { - consumePush(this[kConsume], chunk); - return this[kReading] ? super.push(chunk) : true; + if (chunk) { + this[kBytesRead] += chunk.length; + if (this[kConsume]) { + 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() { + /** + * Consumes and returns the body as a string. + * + * @see https://fetch.spec.whatwg.org/#dom-body-text + * @returns {Promise} + */ + text() { return consume(this, "text"); } - // https://fetch.spec.whatwg.org/#dom-body-json - async json() { + /** + * Consumes and returns the body as a JavaScript Object. + * + * @see https://fetch.spec.whatwg.org/#dom-body-json + * @returns {Promise} + */ + json() { return consume(this, "json"); } - // https://fetch.spec.whatwg.org/#dom-body-blob - async blob() { + /** + * Consumes and returns the body as a Blob + * + * @see https://fetch.spec.whatwg.org/#dom-body-blob + * @returns {Promise} + */ + blob() { return consume(this, "blob"); } - // https://fetch.spec.whatwg.org/#dom-body-bytes - async bytes() { + /** + * Consumes and returns the body as an Uint8Array. + * + * @see https://fetch.spec.whatwg.org/#dom-body-bytes + * @returns {Promise} + */ + bytes() { return consume(this, "bytes"); } - // https://fetch.spec.whatwg.org/#dom-body-arraybuffer - async arrayBuffer() { + /** + * Consumes and returns the body as an ArrayBuffer. + * + * @see https://fetch.spec.whatwg.org/#dom-body-arraybuffer + * @returns {Promise} + */ + arrayBuffer() { return consume(this, "arrayBuffer"); } - // https://fetch.spec.whatwg.org/#dom-body-formdata + /** + * Not implemented + * + * @see https://fetch.spec.whatwg.org/#dom-body-formdata + * @throws {NotSupportedError} + */ async formData() { throw new NotSupportedError(); } - // https://fetch.spec.whatwg.org/#dom-body-bodyused + /** + * Returns true if the body is not null and the body has been consumed. + * Otherwise, returns false. + * + * @see https://fetch.spec.whatwg.org/#dom-body-bodyused + * @readonly + * @returns {boolean} + */ get bodyUsed() { - return util3.isDisturbed(this); + return util4.isDisturbed(this); } - // https://fetch.spec.whatwg.org/#dom-body-body + /** + * @see https://fetch.spec.whatwg.org/#dom-body-body + * @readonly + * @returns {ReadableStream} + */ get body() { if (!this[kBody]) { this[kBody] = ReadableStreamFrom(this); @@ -9721,55 +12222,76 @@ var require_readable = __commonJS({ } return this[kBody]; } - async dump(opts) { - let limit = Number.isFinite(opts?.limit) ? opts.limit : 128 * 1024; + /** + * Dumps the response body by reading `limit` number of bytes. + * @param {object} opts + * @param {number} [opts.limit = 131072] Number of bytes to read. + * @param {AbortSignal} [opts.signal] An AbortSignal to cancel the dump. + * @returns {Promise} + */ + dump(opts) { const signal = opts?.signal; if (signal != null && (typeof signal !== "object" || !("aborted" in signal))) { - throw new InvalidArgumentError("signal must be an AbortSignal"); + return Promise.reject(new InvalidArgumentError("signal must be an AbortSignal")); + } + const limit = opts?.limit && Number.isFinite(opts.limit) ? opts.limit : 128 * 1024; + if (signal?.aborted) { + return Promise.reject(signal.reason ?? new AbortError2()); } - signal?.throwIfAborted(); if (this._readableState.closeEmitted) { - return null; + return Promise.resolve(null); } - return await new Promise((resolve14, reject) => { - if (this[kContentLength] > limit) { - this.destroy(new AbortError()); + return new Promise((resolve15, reject) => { + if (this[kContentLength] && this[kContentLength] > limit || this[kBytesRead] > limit) { + this.destroy(new AbortError2()); } - 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 { - resolve14(null); - } - }).on("error", noop3).on("data", function(chunk) { - limit -= chunk.length; - if (limit <= 0) { + if (signal) { + const onAbort = () => { + this.destroy(signal.reason ?? new AbortError2()); + }; + signal.addEventListener("abort", onAbort); + this.on("close", function() { + signal.removeEventListener("abort", onAbort); + if (signal.aborted) { + reject(signal.reason ?? new AbortError2()); + } else { + resolve15(null); + } + }); + } else { + this.on("close", resolve15); + } + this.on("error", noop3).on("data", () => { + if (this[kBytesRead] > limit) { this.destroy(); } }).resume(); }); } + /** + * @param {BufferEncoding} encoding + * @returns {this} + */ + setEncoding(encoding) { + if (Buffer.isEncoding(encoding)) { + this._readableState.encoding = encoding; + } + return this; + } }; - function isLocked(self2) { - return self2[kBody] && self2[kBody].locked === true || self2[kConsume]; + function isLocked(bodyReadable) { + return bodyReadable[kBody]?.locked === true || bodyReadable[kConsume] !== null; } - function isUnusable(self2) { - return util3.isDisturbed(self2) || isLocked(self2); + function isUnusable(bodyReadable) { + return util4.isDisturbed(bodyReadable) || isLocked(bodyReadable); } - async function consume(stream2, type) { + function consume(stream2, type) { assert(!stream2[kConsume]); - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { if (isUnusable(stream2)) { const rState = stream2._readableState; if (rState.destroyed && rState.closeEmitted === false) { - stream2.on("error", (err) => { - reject(err); - }).on("close", () => { + stream2.on("error", reject).on("close", () => { reject(new TypeError("unusable")); }); } else { @@ -9780,7 +12302,7 @@ var require_readable = __commonJS({ stream2[kConsume] = { type, stream: stream2, - resolve: resolve14, + resolve: resolve15, reject, length: 0, body: [] @@ -9814,24 +12336,28 @@ var require_readable = __commonJS({ } } if (state.endEmitted) { - consumeEnd(this[kConsume]); + consumeEnd(this[kConsume], this._readableState.encoding); } else { consume2.stream.on("end", function() { - consumeEnd(this[kConsume]); + consumeEnd(this[kConsume], this._readableState.encoding); }); } consume2.stream.resume(); while (consume2.stream.read() != null) { } } - function chunksDecode(chunks, length) { + function chunksDecode(chunks, length, encoding) { if (chunks.length === 0 || length === 0) { return ""; } const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length); const bufferLength = buffer.length; const start = bufferLength > 2 && buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191 ? 3 : 0; - return buffer.utf8Slice(start, bufferLength); + if (!encoding || encoding === "utf8" || encoding === "utf-8") { + return buffer.utf8Slice(start, bufferLength); + } else { + return buffer.subarray(start, bufferLength).toString(encoding); + } } function chunksConcat(chunks, length) { if (chunks.length === 0 || length === 0) { @@ -9849,19 +12375,19 @@ var require_readable = __commonJS({ } return buffer; } - function consumeEnd(consume2) { - const { type, body, resolve: resolve14, stream: stream2, length } = consume2; + function consumeEnd(consume2, encoding) { + const { type, body, resolve: resolve15, stream: stream2, length } = consume2; try { if (type === "text") { - resolve14(chunksDecode(body, length)); + resolve15(chunksDecode(body, length, encoding)); } else if (type === "json") { - resolve14(JSON.parse(chunksDecode(body, length))); + resolve15(JSON.parse(chunksDecode(body, length, encoding))); } else if (type === "arrayBuffer") { - resolve14(chunksConcat(body, length).buffer); + resolve15(chunksConcat(body, length).buffer); } else if (type === "blob") { - resolve14(new Blob(body, { type: stream2[kContentType] })); + resolve15(new Blob(body, { type: stream2[kContentType] })); } else if (type === "bytes") { - resolve14(chunksConcat(body, length)); + resolve15(chunksConcat(body, length)); } consumeFinish(consume2); } catch (err) { @@ -9888,67 +12414,9 @@ var require_readable = __commonJS({ consume2.length = 0; consume2.body = null; } - module2.exports = { Readable: BodyReadable, chunksDecode }; - } -}); - -// node_modules/undici/lib/api/util.js -var require_util3 = __commonJS({ - "node_modules/undici/lib/api/util.js"(exports2, module2) { - var assert = require("node:assert"); - var { - ResponseStatusCodeError - } = require_errors(); - var { chunksDecode } = require_readable(); - var 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; - } - 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 { - } finally { - Error.stackTraceLimit = stackTraceLimit; - } - queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers, payload))); - } - var 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"; - }; - var isContentTypeText = (contentType) => { - return contentType.length > 4 && contentType[4] === "/" && contentType[0] === "t" && contentType[1] === "e" && contentType[2] === "x" && contentType[3] === "t"; - }; module2.exports = { - getResolveErrorBodyCallback, - isContentTypeApplicationJson, - isContentTypeText + Readable: BodyReadable, + chunksDecode }; } }); @@ -9958,22 +12426,23 @@ var require_api_request = __commonJS({ "node_modules/undici/lib/api/api-request.js"(exports2, module2) { "use strict"; var assert = require("node:assert"); - var { Readable: Readable3 } = require_readable(); - var { InvalidArgumentError, RequestAbortedError } = require_errors(); - var util3 = require_util(); - var { getResolveErrorBodyCallback } = require_util3(); var { AsyncResource } = require("node:async_hooks"); + var { Readable: Readable4 } = require_readable(); + var { InvalidArgumentError, RequestAbortedError } = require_errors(); + var util4 = require_util(); + function noop3() { + } var RequestHandler = class 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; + const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts; try { if (typeof callback !== "function") { throw new InvalidArgumentError("invalid callback"); } - if (highWaterMark && (typeof highWaterMark !== "number" || highWaterMark < 0)) { + if (highWaterMark != null && (!Number.isFinite(highWaterMark) || highWaterMark < 0)) { throw new InvalidArgumentError("invalid highWaterMark"); } if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") { @@ -9987,8 +12456,8 @@ var require_api_request = __commonJS({ } super("UNDICI_REQUEST"); } catch (err) { - if (util3.isStream(body)) { - util3.destroy(body.on("error", util3.nop), err); + if (util4.isStream(body)) { + util4.destroy(body.on("error", noop3), err); } throw err; } @@ -10002,35 +12471,21 @@ var require_api_request = __commonJS({ 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 (util3.isStream(body)) { - body.on("error", (err) => { - this.onError(err); + if (signal?.aborted) { + this.reason = signal.reason ?? new RequestAbortedError(); + } else if (signal) { + this.removeAbortListener = util4.addAbortListener(signal, () => { + this.reason = signal.reason ?? new RequestAbortedError(); + if (this.res) { + util4.destroy(this.res.on("error", noop3), this.reason); + } else if (this.abort) { + this.abort(this.reason); + } }); } - if (this.signal) { - if (this.signal.aborted) { - this.reason = this.signal.reason ?? new RequestAbortedError(); - } else { - this.removeAbortListener = util3.addAbortListener(this.signal, () => { - this.reason = this.signal.reason ?? new RequestAbortedError(); - if (this.res) { - util3.destroy(this.res.on("error", util3.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, context5) { if (this.reason) { @@ -10043,17 +12498,17 @@ var require_api_request = __commonJS({ } onHeaders(statusCode, rawHeaders, resume, statusMessage) { const { callback, opaque, abort, context: context5, responseHeaders, highWaterMark } = this; - const headers = responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders); + const headers = responseHeaders === "raw" ? util4.parseRawHeaders(rawHeaders) : util4.parseHeaders(rawHeaders); if (statusCode < 200) { if (this.onInfo) { this.onInfo({ statusCode, headers }); } return; } - const parsedHeaders = responseHeaders === "raw" ? util3.parseHeaders(rawHeaders) : headers; + const parsedHeaders = responseHeaders === "raw" ? util4.parseHeaders(rawHeaders) : headers; const contentType = parsedHeaders["content-type"]; const contentLength = parsedHeaders["content-length"]; - const res = new Readable3({ + const res = new Readable4({ resume, abort, contentType, @@ -10062,25 +12517,27 @@ var require_api_request = __commonJS({ }); if (this.removeAbortListener) { res.on("close", this.removeAbortListener); + this.removeAbortListener = null; } 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 { + try { this.runInAsyncScope(callback, null, null, { statusCode, + statusText: statusMessage, headers, trailers: this.trailers, opaque, body: res, context: context5 }); + } catch (err) { + this.res = null; + util4.destroy(res.on("error", noop3), err); + queueMicrotask(() => { + throw err; + }); } } } @@ -10088,7 +12545,7 @@ var require_api_request = __commonJS({ return this.res.push(chunk); } onComplete(trailers) { - util3.parseHeaders(trailers, this.trailers); + util4.parseHeaders(trailers, this.trailers); this.res.push(null); } onError(err) { @@ -10102,15 +12559,17 @@ var require_api_request = __commonJS({ if (res) { this.res = null; queueMicrotask(() => { - util3.destroy(res, err); + util4.destroy(res.on("error", noop3), err); }); } if (body) { this.body = null; - util3.destroy(body, err); + if (util4.isStream(body)) { + body.on("error", noop3); + util4.destroy(body, err); + } } if (this.removeAbortListener) { - res?.off("close", this.removeAbortListener); this.removeAbortListener(); this.removeAbortListener = null; } @@ -10118,14 +12577,15 @@ var require_api_request = __commonJS({ }; function request3(opts, callback) { if (callback === void 0) { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { request3.call(this, opts, (err, data) => { - return err ? reject(err) : resolve14(data); + return err ? reject(err) : resolve15(data); }); }); } try { - this.dispatch(opts, new RequestHandler(opts, callback)); + const handler2 = new RequestHandler(opts, callback); + this.dispatch(opts, handler2); } catch (err) { if (typeof callback !== "function") { throw err; @@ -10142,6 +12602,7 @@ var require_api_request = __commonJS({ // node_modules/undici/lib/api/abort-signal.js var require_abort_signal = __commonJS({ "node_modules/undici/lib/api/abort-signal.js"(exports2, module2) { + "use strict"; var { addAbortListener } = require_util(); var { RequestAbortedError } = require_errors(); var kListener = /* @__PURE__ */ Symbol("kListener"); @@ -10195,18 +12656,19 @@ var require_api_stream = __commonJS({ "node_modules/undici/lib/api/api-stream.js"(exports2, module2) { "use strict"; var assert = require("node:assert"); - var { finished, PassThrough: PassThrough3 } = require("node:stream"); - var { InvalidArgumentError, InvalidReturnValueError } = require_errors(); - var util3 = require_util(); - var { getResolveErrorBodyCallback } = require_util3(); + var { finished } = require("node:stream"); var { AsyncResource } = require("node:async_hooks"); + var { InvalidArgumentError, InvalidReturnValueError } = require_errors(); + var util4 = require_util(); var { addSignal, removeSignal } = require_abort_signal(); + function noop3() { + } var StreamHandler = class 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; + const { signal, method, opaque, body, onInfo, responseHeaders } = opts; try { if (typeof callback !== "function") { throw new InvalidArgumentError("invalid callback"); @@ -10225,8 +12687,8 @@ var require_api_stream = __commonJS({ } super("UNDICI_STREAM"); } catch (err) { - if (util3.isStream(body)) { - util3.destroy(body.on("error", util3.nop), err); + if (util4.isStream(body)) { + util4.destroy(body.on("error", noop3), err); } throw err; } @@ -10240,8 +12702,7 @@ var require_api_stream = __commonJS({ this.trailers = null; this.body = body; this.onInfo = onInfo || null; - this.throwOnError = throwOnError || false; - if (util3.isStream(body)) { + if (util4.isStream(body)) { body.on("error", (err) => { this.onError(err); }); @@ -10258,8 +12719,8 @@ var require_api_stream = __commonJS({ this.context = context5; } onHeaders(statusCode, rawHeaders, resume, statusMessage) { - const { factory, opaque, context: context5, callback, responseHeaders } = this; - const headers = responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders); + const { factory, opaque, context: context5, responseHeaders } = this; + const headers = responseHeaders === "raw" ? util4.parseRawHeaders(rawHeaders) : util4.parseHeaders(rawHeaders); if (statusCode < 200) { if (this.onInfo) { this.onInfo({ statusCode, headers }); @@ -10267,43 +12728,30 @@ var require_api_stream = __commonJS({ return; } this.factory = null; - let res; - if (this.throwOnError && statusCode >= 400) { - const parsedHeaders = responseHeaders === "raw" ? util3.parseHeaders(rawHeaders) : headers; - const contentType = parsedHeaders["content-type"]; - res = new PassThrough3(); - this.callback = null; - this.runInAsyncScope( - getResolveErrorBodyCallback, - null, - { callback, body: res, contentType, statusCode, statusMessage, headers } - ); - } else { - if (factory === null) { - return; + if (factory === null) { + return; + } + const res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context: context5 + }); + if (!res || typeof res.write !== "function" || typeof res.end !== "function" || typeof res.on !== "function") { + throw new InvalidReturnValueError("expected Writable"); + } + finished(res, { readable: false }, (err) => { + const { callback, res: res2, opaque: opaque2, trailers, abort } = this; + this.res = null; + if (err || !res2?.readable) { + util4.destroy(res2, err); } - res = this.runInAsyncScope(factory, null, { - statusCode, - headers, - opaque, - context: context5 - }); - if (!res || typeof res.write !== "function" || typeof res.end !== "function" || typeof res.on !== "function") { - throw new InvalidReturnValueError("expected Writable"); + this.callback = null; + this.runInAsyncScope(callback, null, err || null, { opaque: opaque2, trailers }); + if (err) { + abort(); } - finished(res, { readable: false }, (err) => { - const { callback: callback2, res: res2, opaque: opaque2, trailers, abort } = this; - this.res = null; - if (err || !res2.readable) { - util3.destroy(res2, err); - } - this.callback = null; - this.runInAsyncScope(callback2, null, err || null, { opaque: opaque2, trailers }); - if (err) { - abort(); - } - }); - } + }); res.on("drain", resume); this.res = res; const needDrain = res.writableNeedDrain !== void 0 ? res.writableNeedDrain : res._writableState?.needDrain; @@ -10319,7 +12767,7 @@ var require_api_stream = __commonJS({ if (!res) { return; } - this.trailers = util3.parseHeaders(trailers); + this.trailers = util4.parseHeaders(trailers); res.end(); } onError(err) { @@ -10328,7 +12776,7 @@ var require_api_stream = __commonJS({ this.factory = null; if (res) { this.res = null; - util3.destroy(res, err); + util4.destroy(res, err); } else if (callback) { this.callback = null; queueMicrotask(() => { @@ -10337,20 +12785,21 @@ var require_api_stream = __commonJS({ } if (body) { this.body = null; - util3.destroy(body, err); + util4.destroy(body, err); } } }; function stream2(opts, factory, callback) { if (callback === void 0) { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { stream2.call(this, opts, factory, (err, data) => { - return err ? reject(err) : resolve14(data); + return err ? reject(err) : resolve15(data); }); }); } try { - this.dispatch(opts, new StreamHandler(opts, factory, callback)); + const handler2 = new StreamHandler(opts, factory, callback); + this.dispatch(opts, handler2); } catch (err) { if (typeof callback !== "function") { throw err; @@ -10368,21 +12817,23 @@ var require_api_pipeline = __commonJS({ "node_modules/undici/lib/api/api-pipeline.js"(exports2, module2) { "use strict"; var { - Readable: Readable3, - Duplex, + Readable: Readable4, + Duplex: Duplex4, PassThrough: PassThrough3 } = require("node:stream"); + var assert = require("node:assert"); + var { AsyncResource } = require("node:async_hooks"); var { InvalidArgumentError, InvalidReturnValueError, RequestAbortedError } = require_errors(); - var util3 = require_util(); - var { AsyncResource } = require("node:async_hooks"); + var util4 = require_util(); var { addSignal, removeSignal } = require_abort_signal(); - var assert = require("node:assert"); + function noop3() { + } var kResume = /* @__PURE__ */ Symbol("resume"); - var PipelineRequest = class extends Readable3 { + var PipelineRequest = class extends Readable4 { constructor() { super({ autoDestroy: true }); this[kResume] = null; @@ -10399,7 +12850,7 @@ var require_api_pipeline = __commonJS({ callback(err); } }; - var PipelineResponse = class extends Readable3 { + var PipelineResponse = class extends Readable4 { constructor(resume) { super({ autoDestroy: true }); this[kResume] = resume; @@ -10439,8 +12890,8 @@ var require_api_pipeline = __commonJS({ this.abort = null; this.context = null; this.onInfo = onInfo || null; - this.req = new PipelineRequest().on("error", util3.nop); - this.ret = new Duplex({ + this.req = new PipelineRequest().on("error", noop3); + this.ret = new Duplex4({ readableObjectMode: opts.objectMode, autoDestroy: true, read: () => { @@ -10465,9 +12916,9 @@ var require_api_pipeline = __commonJS({ if (abort && err) { abort(); } - util3.destroy(body, err); - util3.destroy(req, err); - util3.destroy(res, err); + util4.destroy(body, err); + util4.destroy(req, err); + util4.destroy(res, err); removeSignal(this); callback(err); } @@ -10479,13 +12930,12 @@ var require_api_pipeline = __commonJS({ addSignal(this, signal); } onConnect(abort, context5) { - const { ret, res } = this; + const { res } = this; if (this.reason) { abort(this.reason); return; } assert(!res, "pipeline cannot be retried"); - assert(!ret.destroyed); this.abort = abort; this.context = context5; } @@ -10493,7 +12943,7 @@ var require_api_pipeline = __commonJS({ const { opaque, handler: handler2, context: context5 } = this; if (statusCode < 200) { if (this.onInfo) { - const headers = this.responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders); + const headers = this.responseHeaders === "raw" ? util4.parseRawHeaders(rawHeaders) : util4.parseHeaders(rawHeaders); this.onInfo({ statusCode, headers }); } return; @@ -10502,7 +12952,7 @@ var require_api_pipeline = __commonJS({ let body; try { this.handler = null; - const headers = this.responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders); + const headers = this.responseHeaders === "raw" ? util4.parseRawHeaders(rawHeaders) : util4.parseHeaders(rawHeaders); body = this.runInAsyncScope(handler2, null, { statusCode, headers, @@ -10511,7 +12961,7 @@ var require_api_pipeline = __commonJS({ context: context5 }); } catch (err) { - this.res.on("error", util3.nop); + this.res.on("error", noop3); throw err; } if (!body || typeof body.on !== "function") { @@ -10524,14 +12974,14 @@ var require_api_pipeline = __commonJS({ } }).on("error", (err) => { const { ret } = this; - util3.destroy(ret, err); + util4.destroy(ret, err); }).on("end", () => { const { ret } = this; ret.push(null); }).on("close", () => { const { ret } = this; if (!ret._readableState.ended) { - util3.destroy(ret, new RequestAbortedError()); + util4.destroy(ret, new RequestAbortedError()); } }); this.body = body; @@ -10547,7 +12997,7 @@ var require_api_pipeline = __commonJS({ onError(err) { const { ret } = this; this.handler = null; - util3.destroy(ret, err); + util4.destroy(ret, err); } }; function pipeline2(opts, handler2) { @@ -10569,9 +13019,10 @@ var require_api_upgrade = __commonJS({ "use strict"; var { InvalidArgumentError, SocketError } = require_errors(); var { AsyncResource } = require("node:async_hooks"); - var util3 = require_util(); - var { addSignal, removeSignal } = require_abort_signal(); var assert = require("node:assert"); + var util4 = require_util(); + var { kHTTP2Stream } = require_symbols(); + var { addSignal, removeSignal } = require_abort_signal(); var UpgradeHandler = class extends AsyncResource { constructor(opts, callback) { if (!opts || typeof opts !== "object") { @@ -10605,11 +13056,11 @@ var require_api_upgrade = __commonJS({ throw new SocketError("bad upgrade", null); } onUpgrade(statusCode, rawHeaders, socket) { - assert(statusCode === 101); + assert(socket[kHTTP2Stream] === true ? statusCode === 200 : statusCode === 101); const { callback, opaque, context: context5 } = this; removeSignal(this); this.callback = null; - const headers = this.responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders); + const headers = this.responseHeaders === "raw" ? util4.parseRawHeaders(rawHeaders) : util4.parseHeaders(rawHeaders); this.runInAsyncScope(callback, null, null, { headers, socket, @@ -10630,19 +13081,20 @@ var require_api_upgrade = __commonJS({ }; function upgrade(opts, callback) { if (callback === void 0) { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { upgrade.call(this, opts, (err, data) => { - return err ? reject(err) : resolve14(data); + return err ? reject(err) : resolve15(data); }); }); } try { const upgradeHandler = new UpgradeHandler(opts, callback); - this.dispatch({ + const upgradeOpts = { ...opts, method: opts.method || "GET", upgrade: opts.protocol || "Websocket" - }, upgradeHandler); + }; + this.dispatch(upgradeOpts, upgradeHandler); } catch (err) { if (typeof callback !== "function") { throw err; @@ -10662,7 +13114,7 @@ var require_api_connect = __commonJS({ var assert = require("node:assert"); var { AsyncResource } = require("node:async_hooks"); var { InvalidArgumentError, SocketError } = require_errors(); - var util3 = require_util(); + var util4 = require_util(); var { addSignal, removeSignal } = require_abort_signal(); var ConnectHandler = class extends AsyncResource { constructor(opts, callback) { @@ -10701,7 +13153,7 @@ var require_api_connect = __commonJS({ this.callback = null; let headers = rawHeaders; if (headers != null) { - headers = this.responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders); + headers = this.responseHeaders === "raw" ? util4.parseRawHeaders(rawHeaders) : util4.parseHeaders(rawHeaders); } this.runInAsyncScope(callback, null, null, { statusCode, @@ -10724,15 +13176,16 @@ var require_api_connect = __commonJS({ }; function connect(opts, callback) { if (callback === void 0) { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { connect.call(this, opts, (err, data) => { - return err ? reject(err) : resolve14(data); + return err ? reject(err) : resolve15(data); }); }); } try { const connectHandler = new ConnectHandler(opts, callback); - this.dispatch({ ...opts, method: "CONNECT" }, connectHandler); + const connectOptions = { ...opts, method: "CONNECT" }; + this.dispatch(connectOptions, connectHandler); } catch (err) { if (typeof callback !== "function") { throw err; @@ -10763,18 +13216,19 @@ var require_mock_errors = __commonJS({ "use strict"; var { UndiciError } = require_errors(); var kMockNotMatchedError = /* @__PURE__ */ Symbol.for("undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED"); - var MockNotMatchedError = class _MockNotMatchedError extends UndiciError { + var MockNotMatchedError = class 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; + static [Symbol.hasInstance](instance8) { + return instance8 && instance8[kMockNotMatchedError] === true; + } + get [kMockNotMatchedError]() { + return true; } - [kMockNotMatchedError] = true; }; module2.exports = { MockNotMatchedError @@ -10801,11 +13255,20 @@ var require_mock_symbols = __commonJS({ kMockDispatch: /* @__PURE__ */ Symbol("mock dispatch"), kClose: /* @__PURE__ */ Symbol("close"), kOriginalClose: /* @__PURE__ */ Symbol("original agent close"), + kOriginalDispatch: /* @__PURE__ */ Symbol("original dispatch"), kOrigin: /* @__PURE__ */ Symbol("origin"), kIsMockActive: /* @__PURE__ */ Symbol("is mock active"), kNetConnect: /* @__PURE__ */ Symbol("net connect"), kGetNetConnect: /* @__PURE__ */ Symbol("get net connect"), - kConnected: /* @__PURE__ */ Symbol("connected") + kConnected: /* @__PURE__ */ Symbol("connected"), + kIgnoreTrailingSlash: /* @__PURE__ */ Symbol("ignore trailing slash"), + kMockAgentMockCallHistoryInstance: /* @__PURE__ */ Symbol("mock agent mock call history name"), + kMockAgentRegisterCallHistory: /* @__PURE__ */ Symbol("mock agent register mock call history"), + kMockAgentAddCallHistoryLog: /* @__PURE__ */ Symbol("mock agent add call history log"), + kMockAgentIsCallHistoryEnabled: /* @__PURE__ */ Symbol("mock agent is call history enabled"), + kMockAgentAcceptsNonStandardSearchParameters: /* @__PURE__ */ Symbol("mock agent accepts non standard search parameters"), + kMockCallHistoryAddLog: /* @__PURE__ */ Symbol("mock call history add log"), + kTotalDispatchCount: /* @__PURE__ */ Symbol("total dispatch count") }; } }); @@ -10820,15 +13283,17 @@ var require_mock_utils = __commonJS({ kMockAgent, kOriginalDispatch, kOrigin, - kGetNetConnect + kGetNetConnect, + kTotalDispatchCount } = require_mock_symbols(); - var { buildURL } = require_util(); + var { serializePathWithQuery } = require_util(); var { STATUS_CODES } = require("node:http"); var { types: { - isPromise + isPromise: isPromise2 } } = require("node:util"); + var { InvalidArgumentError } = require_errors(); function matchValue(match2, value) { if (typeof match2 === "string") { return match2 === value; @@ -10891,11 +13356,35 @@ var require_mock_utils = __commonJS({ } return true; } + function normalizeSearchParams(query) { + if (typeof query !== "string") { + return query; + } + const originalQp = new URLSearchParams(query); + const normalizedQp = new URLSearchParams(); + for (let [key, value] of originalQp.entries()) { + key = key.replace("[]", ""); + const valueRepresentsString = /^(['"]).*\1$/.test(value); + if (valueRepresentsString) { + normalizedQp.append(key, value); + continue; + } + if (value.includes(",")) { + const values = value.split(","); + for (const v of values) { + normalizedQp.append(key, v); + } + continue; + } + normalizedQp.append(key, value); + } + return normalizedQp; + } function safeUrl(path30) { if (typeof path30 !== "string") { return path30; } - const pathSegments = path30.split("?"); + const pathSegments = path30.split("?", 3); if (pathSegments.length !== 2) { return path30; } @@ -10919,14 +13408,19 @@ var require_mock_utils = __commonJS({ return data; } else if (typeof data === "object") { return JSON.stringify(data); - } else { + } else if (data) { return data.toString(); + } else { + return ""; } } function getMockDispatch(mockDispatches, key) { - const basePath = key.query ? buildURL(key.path, key.query) : key.path; + const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path; const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath; - let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path30 }) => matchValue(safeUrl(path30), resolvedPath)); + const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath); + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path30, ignoreTrailingSlash }) => { + return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path30)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path30), resolvedPath); + }); if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`); } @@ -10945,11 +13439,12 @@ var require_mock_utils = __commonJS({ } return matchedMockDispatches[0]; } - function addMockDispatch(mockDispatches, key, data) { - const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }; + function addMockDispatch(mockDispatches, key, data, opts) { + const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false, ...opts }; const replyData = typeof data === "function" ? { callback: data } : { ...data }; const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }; mockDispatches.push(newMockDispatch); + mockDispatches[kTotalDispatchCount] = (mockDispatches[kTotalDispatchCount] || 0) + 1; return newMockDispatch; } function deleteMockDispatch(mockDispatches, key) { @@ -10963,6 +13458,15 @@ var require_mock_utils = __commonJS({ mockDispatches.splice(index2, 1); } } + function removeTrailingSlash(path30) { + while (path30.endsWith("/")) { + path30 = path30.slice(0, -1); + } + if (path30.length === 0) { + path30 = "/"; + } + return path30; + } function buildKey(opts) { const { path: path30, method, body, headers, query } = opts; return { @@ -11016,24 +13520,43 @@ var require_mock_utils = __commonJS({ handler2.onError(error3); return true; } + let aborted = false; + let timer = null; + function abort(err) { + if (aborted) { + return; + } + aborted = true; + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + handler2.onError(err); + } + handler2.onConnect?.(abort, null); if (typeof delay2 === "number" && delay2 > 0) { - setTimeout(() => { + timer = setTimeout(() => { + timer = null; handleReply(this[kDispatches]); }, delay2); } else { handleReply(this[kDispatches]); } function handleReply(mockDispatches, _data = data) { + if (aborted) { + return; + } const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers; const body = typeof _data === "function" ? _data({ ...opts, headers: optsHeaders }) : _data; - if (isPromise(body)) { - body.then((newData) => handleReply(mockDispatches, newData)); + if (isPromise2(body)) { + return body.then((newData) => handleReply(mockDispatches, newData)); + } + if (aborted) { return; } const responseData = getResponseData2(body); const responseHeaders = generateKeyValues(headers); const responseTrailers = generateKeyValues(trailers); - handler2.onConnect?.((err) => handler2.onError(err), null); handler2.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode)); handler2.onData?.(Buffer.from(responseData)); handler2.onComplete?.(responseTrailers); @@ -11052,15 +13575,18 @@ var require_mock_utils = __commonJS({ try { mockDispatch.call(this, opts, handler2); } catch (error3) { - if (error3 instanceof MockNotMatchedError) { + if (error3.code === "UND_MOCK_ERR_MOCK_NOT_MATCHED") { const netConnect = agent[kGetNetConnect](); + const totalInterceptsCount = this[kDispatches][kTotalDispatchCount] || this[kDispatches].length; + const pendingInterceptsCount = this[kDispatches].filter(({ consumed }) => !consumed).length; + const interceptsMessage = `, ${pendingInterceptsCount} interceptor(s) remaining out of ${totalInterceptsCount} defined`; if (netConnect === false) { - throw new MockNotMatchedError(`${error3.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`); + throw new MockNotMatchedError(`${error3.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)${interceptsMessage}`); } if (checkNetConnect(netConnect, origin)) { originalDispatch.call(this, opts, handler2); } else { - throw new MockNotMatchedError(`${error3.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`); + throw new MockNotMatchedError(`${error3.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)${interceptsMessage}`); } } else { throw error3; @@ -11080,11 +13606,27 @@ var require_mock_utils = __commonJS({ } return false; } - function buildMockOptions(opts) { - if (opts) { - const { agent, ...mockOptions } = opts; - return mockOptions; + function normalizeOrigin(origin) { + if (typeof origin !== "string" && !(origin instanceof URL)) { + return origin; + } + if (origin instanceof URL) { + return origin.origin; } + return origin.toLowerCase(); + } + function buildAndValidateMockOptions(opts) { + const { agent, ...mockOptions } = opts; + if ("enableCallHistory" in mockOptions && typeof mockOptions.enableCallHistory !== "boolean") { + throw new InvalidArgumentError("options.enableCallHistory must to be a boolean"); + } + if ("acceptNonStandardSearchParameters" in mockOptions && typeof mockOptions.acceptNonStandardSearchParameters !== "boolean") { + throw new InvalidArgumentError("options.acceptNonStandardSearchParameters must to be a boolean"); + } + if ("ignoreTrailingSlash" in mockOptions && typeof mockOptions.ignoreTrailingSlash !== "boolean") { + throw new InvalidArgumentError("options.ignoreTrailingSlash must to be a boolean"); + } + return mockOptions; } module2.exports = { getResponseData: getResponseData2, @@ -11099,9 +13641,11 @@ var require_mock_utils = __commonJS({ mockDispatch, buildMockDispatch, checkNetConnect, - buildMockOptions, + buildAndValidateMockOptions, getHeaderByName, - buildHeadersFromArray + buildHeadersFromArray, + normalizeSearchParams, + normalizeOrigin }; } }); @@ -11117,10 +13661,11 @@ var require_mock_interceptor = __commonJS({ kDefaultHeaders, kDefaultTrailers, kContentLength, - kMockDispatch + kMockDispatch, + kIgnoreTrailingSlash } = require_mock_symbols(); var { InvalidArgumentError } = require_errors(); - var { buildURL } = require_util(); + var { serializePathWithQuery } = require_util(); var MockScope = class { constructor(mockDispatch) { this[kMockDispatch] = mockDispatch; @@ -11166,7 +13711,7 @@ var require_mock_interceptor = __commonJS({ } if (typeof opts.path === "string") { if (opts.query) { - opts.path = buildURL(opts.path, opts.query); + opts.path = serializePathWithQuery(opts.path, opts.query); } else { const parsedURL = new URL(opts.path, "data://"); opts.path = parsedURL.pathname + parsedURL.search; @@ -11177,6 +13722,7 @@ var require_mock_interceptor = __commonJS({ } this[kDispatchKey] = buildKey(opts); this[kDispatches] = mockDispatches; + this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false; this[kDefaultHeaders] = {}; this[kDefaultTrailers] = {}; this[kContentLength] = false; @@ -11212,7 +13758,7 @@ var require_mock_interceptor = __commonJS({ ...this.createMockScopeDispatchData(replyParameters2) }; }; - const newMockDispatch2 = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback); + const newMockDispatch2 = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] }); return new MockScope(newMockDispatch2); } const replyParameters = { @@ -11222,7 +13768,7 @@ var require_mock_interceptor = __commonJS({ }; this.validateReplyParameters(replyParameters); const dispatchData = this.createMockScopeDispatchData(replyParameters); - const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData); + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] }); return new MockScope(newMockDispatch); } /** @@ -11232,7 +13778,7 @@ var require_mock_interceptor = __commonJS({ if (typeof error3 === "undefined") { throw new InvalidArgumentError("error must be defined"); } - const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error: error3 }); + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error: error3 }, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] }); return new MockScope(newMockDispatch); } /** @@ -11282,19 +13828,21 @@ var require_mock_client = __commonJS({ kOriginalClose, kOrigin, kOriginalDispatch, - kConnected + kConnected, + kIgnoreTrailingSlash } = require_mock_symbols(); var { MockInterceptor } = require_mock_interceptor(); var Symbols = require_symbols(); var { InvalidArgumentError } = require_errors(); var MockClient = class 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"); } + super(origin, opts); this[kMockAgent] = opts.agent; this[kOrigin] = origin; + this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false; this[kDispatches] = []; this[kConnected] = 1; this[kOriginalDispatch] = this.dispatch; @@ -11309,7 +13857,13 @@ var require_mock_client = __commonJS({ * Sets up the base interceptor for mocking replies from undici. */ intercept(opts) { - return new MockInterceptor(opts, this[kDispatches]); + return new MockInterceptor( + opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts }, + this[kDispatches] + ); + } + cleanMocks() { + this[kDispatches] = []; } async [kClose]() { await promisify(this[kOriginalClose])(); @@ -11321,6 +13875,206 @@ var require_mock_client = __commonJS({ } }); +// node_modules/undici/lib/mock/mock-call-history.js +var require_mock_call_history = __commonJS({ + "node_modules/undici/lib/mock/mock-call-history.js"(exports2, module2) { + "use strict"; + var { kMockCallHistoryAddLog } = require_mock_symbols(); + var { InvalidArgumentError } = require_errors(); + function handleFilterCallsWithOptions(criteria, options, handler2, store, allLogs) { + switch (options.operator) { + case "OR": + store.push(...handler2(criteria, allLogs)); + return store; + case "AND": + return handler2(criteria, store); + default: + throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'"); + } + } + function buildAndValidateFilterCallsOptions(options = {}) { + const finalOptions = {}; + if ("operator" in options) { + if (typeof options.operator !== "string" || options.operator.toUpperCase() !== "OR" && options.operator.toUpperCase() !== "AND") { + throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'"); + } + return { + ...finalOptions, + operator: options.operator.toUpperCase() + }; + } + return finalOptions; + } + function makeFilterCalls(parameterName) { + return (parameterValue, logs) => { + if (typeof parameterValue === "string" || parameterValue == null) { + return logs.filter((log) => { + return log[parameterName] === parameterValue; + }); + } + if (parameterValue instanceof RegExp) { + return logs.filter((log) => { + return parameterValue.test(log[parameterName]); + }); + } + throw new InvalidArgumentError(`${parameterName} parameter should be one of string, regexp, undefined or null`); + }; + } + function computeUrlWithMaybeSearchParameters(requestInit) { + try { + const url2 = new URL(requestInit.path, requestInit.origin); + if (url2.search.length !== 0) { + return url2; + } + url2.search = new URLSearchParams(requestInit.query).toString(); + return url2; + } catch (error3) { + throw new InvalidArgumentError("An error occurred when computing MockCallHistoryLog.url", { cause: error3 }); + } + } + var MockCallHistoryLog = class { + constructor(requestInit = {}) { + this.body = requestInit.body; + this.headers = requestInit.headers; + this.method = requestInit.method; + const url2 = computeUrlWithMaybeSearchParameters(requestInit); + this.fullUrl = url2.toString(); + this.origin = url2.origin; + this.path = url2.pathname; + this.searchParams = Object.fromEntries(url2.searchParams); + this.protocol = url2.protocol; + this.host = url2.host; + this.port = url2.port; + this.hash = url2.hash; + } + toMap() { + return /* @__PURE__ */ new Map( + [ + ["protocol", this.protocol], + ["host", this.host], + ["port", this.port], + ["origin", this.origin], + ["path", this.path], + ["hash", this.hash], + ["searchParams", this.searchParams], + ["fullUrl", this.fullUrl], + ["method", this.method], + ["body", this.body], + ["headers", this.headers] + ] + ); + } + toString() { + const options = { betweenKeyValueSeparator: "->", betweenPairSeparator: "|" }; + let result = ""; + this.toMap().forEach((value, key) => { + if (typeof value === "string" || value === void 0 || value === null) { + result = `${result}${key}${options.betweenKeyValueSeparator}${value}${options.betweenPairSeparator}`; + } + if (typeof value === "object" && value !== null || Array.isArray(value)) { + result = `${result}${key}${options.betweenKeyValueSeparator}${JSON.stringify(value)}${options.betweenPairSeparator}`; + } + }); + return result.slice(0, -1); + } + }; + var MockCallHistory = class { + logs = []; + calls() { + return this.logs; + } + firstCall() { + return this.logs.at(0); + } + lastCall() { + return this.logs.at(-1); + } + nthCall(number2) { + if (typeof number2 !== "number") { + throw new InvalidArgumentError("nthCall must be called with a number"); + } + if (!Number.isInteger(number2)) { + throw new InvalidArgumentError("nthCall must be called with an integer"); + } + if (Math.sign(number2) !== 1) { + throw new InvalidArgumentError("nthCall must be called with a positive value. use firstCall or lastCall instead"); + } + return this.logs.at(number2 - 1); + } + filterCalls(criteria, options) { + if (this.logs.length === 0) { + return this.logs; + } + if (typeof criteria === "function") { + return this.logs.filter(criteria); + } + if (criteria instanceof RegExp) { + return this.logs.filter((log) => { + return criteria.test(log.toString()); + }); + } + if (typeof criteria === "object" && criteria !== null) { + if (Object.keys(criteria).length === 0) { + return this.logs; + } + const finalOptions = { operator: "OR", ...buildAndValidateFilterCallsOptions(options) }; + let maybeDuplicatedLogsFiltered = finalOptions.operator === "AND" ? this.logs : []; + if ("protocol" in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered, this.logs); + } + if ("host" in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered, this.logs); + } + if ("port" in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered, this.logs); + } + if ("origin" in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered, this.logs); + } + if ("path" in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered, this.logs); + } + if ("hash" in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered, this.logs); + } + if ("fullUrl" in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered, this.logs); + } + if ("method" in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered, this.logs); + } + const uniqLogsFiltered = [...new Set(maybeDuplicatedLogsFiltered)]; + return uniqLogsFiltered; + } + throw new InvalidArgumentError("criteria parameter should be one of function, regexp, or object"); + } + filterCallsByProtocol = makeFilterCalls.call(this, "protocol"); + filterCallsByHost = makeFilterCalls.call(this, "host"); + filterCallsByPort = makeFilterCalls.call(this, "port"); + filterCallsByOrigin = makeFilterCalls.call(this, "origin"); + filterCallsByPath = makeFilterCalls.call(this, "path"); + filterCallsByHash = makeFilterCalls.call(this, "hash"); + filterCallsByFullUrl = makeFilterCalls.call(this, "fullUrl"); + filterCallsByMethod = makeFilterCalls.call(this, "method"); + clear() { + this.logs = []; + } + [kMockCallHistoryAddLog](requestInit) { + const log = new MockCallHistoryLog(requestInit); + this.logs.push(log); + return log; + } + *[Symbol.iterator]() { + for (const log of this.calls()) { + yield log; + } + } + }; + module2.exports.MockCallHistory = MockCallHistory; + module2.exports.MockCallHistoryLog = MockCallHistoryLog; + } +}); + // node_modules/undici/lib/mock/mock-pool.js var require_mock_pool = __commonJS({ "node_modules/undici/lib/mock/mock-pool.js"(exports2, module2) { @@ -11335,19 +14089,21 @@ var require_mock_pool = __commonJS({ kOriginalClose, kOrigin, kOriginalDispatch, - kConnected + kConnected, + kIgnoreTrailingSlash } = require_mock_symbols(); var { MockInterceptor } = require_mock_interceptor(); var Symbols = require_symbols(); var { InvalidArgumentError } = require_errors(); var MockPool = class 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"); } + super(origin, opts); this[kMockAgent] = opts.agent; this[kOrigin] = origin; + this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false; this[kDispatches] = []; this[kConnected] = 1; this[kOriginalDispatch] = this.dispatch; @@ -11362,7 +14118,13 @@ var require_mock_pool = __commonJS({ * Sets up the base interceptor for mocking replies from undici. */ intercept(opts) { - return new MockInterceptor(opts, this[kDispatches]); + return new MockInterceptor( + opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts }, + this[kDispatches] + ); + } + cleanMocks() { + this[kDispatches] = []; } async [kClose]() { await promisify(this[kOriginalClose])(); @@ -11374,37 +14136,6 @@ var require_mock_pool = __commonJS({ } }); -// node_modules/undici/lib/mock/pluralizer.js -var require_pluralizer = __commonJS({ - "node_modules/undici/lib/mock/pluralizer.js"(exports2, module2) { - "use strict"; - var singulars = { - pronoun: "it", - is: "is", - was: "was", - this: "this" - }; - var plurals = { - pronoun: "they", - is: "are", - was: "were", - this: "these" - }; - module2.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 }; - } - }; - } -}); - // node_modules/undici/lib/mock/pending-interceptors-formatter.js var require_pending_interceptors_formatter = __commonJS({ "node_modules/undici/lib/mock/pending-interceptors-formatter.js"(exports2, module2) { @@ -11461,41 +14192,67 @@ var require_mock_agent = __commonJS({ kNetConnect, kGetNetConnect, kOptions, - kFactory + kFactory, + kMockAgentRegisterCallHistory, + kMockAgentIsCallHistoryEnabled, + kMockAgentAddCallHistoryLog, + kMockAgentMockCallHistoryInstance, + kMockAgentAcceptsNonStandardSearchParameters, + kMockCallHistoryAddLog, + kIgnoreTrailingSlash } = require_mock_symbols(); var MockClient = require_mock_client(); var MockPool = require_mock_pool(); - var { matchValue, buildMockOptions } = require_mock_utils(); + var { matchValue, normalizeSearchParams, buildAndValidateMockOptions, normalizeOrigin } = require_mock_utils(); var { InvalidArgumentError, UndiciError } = require_errors(); var Dispatcher = require_dispatcher(); - var Pluralizer = require_pluralizer(); var PendingInterceptorsFormatter = require_pending_interceptors_formatter(); + var { MockCallHistory } = require_mock_call_history(); var MockAgent = class extends Dispatcher { - constructor(opts) { + constructor(opts = {}) { super(opts); + const mockOptions = buildAndValidateMockOptions(opts); this[kNetConnect] = true; this[kIsMockActive] = true; + this[kMockAgentIsCallHistoryEnabled] = mockOptions.enableCallHistory ?? false; + this[kMockAgentAcceptsNonStandardSearchParameters] = mockOptions.acceptNonStandardSearchParameters ?? false; + this[kIgnoreTrailingSlash] = mockOptions.ignoreTrailingSlash ?? false; 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); + this[kOptions] = mockOptions; + if (this[kMockAgentIsCallHistoryEnabled]) { + this[kMockAgentRegisterCallHistory](); + } } get(origin) { - let dispatcher = this[kMockAgentGet](origin); + const normalizedOrigin = normalizeOrigin(origin); + const originKey = this[kIgnoreTrailingSlash] ? normalizedOrigin.replace(/\/$/, "") : normalizedOrigin; + let dispatcher = this[kMockAgentGet](originKey); if (!dispatcher) { - dispatcher = this[kFactory](origin); - this[kMockAgentSet](origin, dispatcher); + dispatcher = this[kFactory](originKey); + this[kMockAgentSet](originKey, dispatcher); } return dispatcher; } dispatch(opts, handler2) { + opts.origin = normalizeOrigin(opts.origin); this.get(opts.origin); - return this[kAgent].dispatch(opts, handler2); + this[kMockAgentAddCallHistoryLog](opts); + const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters]; + const dispatchOpts = { ...opts }; + if (acceptNonStandardSearchParameters && dispatchOpts.path) { + const [path30, searchParams] = dispatchOpts.path.split("?"); + const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters); + dispatchOpts.path = `${path30}?${normalizedSearchParams}`; + } + return this[kAgent].dispatch(dispatchOpts, handler2); } async close() { + this.clearCallHistory(); await this[kAgent].close(); this[kClients].clear(); } @@ -11521,33 +14278,60 @@ var require_mock_agent = __commonJS({ disableNetConnect() { this[kNetConnect] = false; } + enableCallHistory() { + this[kMockAgentIsCallHistoryEnabled] = true; + return this; + } + disableCallHistory() { + this[kMockAgentIsCallHistoryEnabled] = false; + return this; + } + getCallHistory() { + return this[kMockAgentMockCallHistoryInstance]; + } + clearCallHistory() { + if (this[kMockAgentMockCallHistoryInstance] !== void 0) { + this[kMockAgentMockCallHistoryInstance].clear(); + } + } // This is required to bypass issues caused by using global symbols - see: // https://github.com/nodejs/undici/issues/1447 get isMockActive() { return this[kIsMockActive]; } + [kMockAgentRegisterCallHistory]() { + if (this[kMockAgentMockCallHistoryInstance] === void 0) { + this[kMockAgentMockCallHistoryInstance] = new MockCallHistory(); + } + } + [kMockAgentAddCallHistoryLog](opts) { + if (this[kMockAgentIsCallHistoryEnabled]) { + this[kMockAgentRegisterCallHistory](); + this[kMockAgentMockCallHistoryInstance][kMockCallHistoryAddLog](opts); + } + } [kMockAgentSet](origin, dispatcher) { - this[kClients].set(origin, dispatcher); + this[kClients].set(origin, { count: 0, 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) { - const client = this[kClients].get(origin); - if (client) { - return client; + const result = this[kClients].get(origin); + if (result?.dispatcher) { + return result.dispatcher; } if (typeof origin !== "string") { const dispatcher = this[kFactory]("http://localhost:9999"); this[kMockAgentSet](origin, dispatcher); return dispatcher; } - for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) { - if (nonExplicitDispatcher && typeof keyMatcher !== "string" && matchValue(keyMatcher, origin)) { + for (const [keyMatcher, result2] of Array.from(this[kClients])) { + if (result2 && typeof keyMatcher !== "string" && matchValue(keyMatcher, origin)) { const dispatcher = this[kFactory](origin); this[kMockAgentSet](origin, dispatcher); - dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]; + dispatcher[kDispatches] = result2.dispatcher[kDispatches]; return dispatcher; } } @@ -11557,30 +14341,781 @@ var require_mock_agent = __commonJS({ } pendingInterceptors() { const mockAgentClients = this[kClients]; - return Array.from(mockAgentClients.entries()).flatMap(([origin, scope]) => scope[kDispatches].map((dispatch) => ({ ...dispatch, origin }))).filter(({ pending }) => pending); + return Array.from(mockAgentClients.entries()).flatMap(([origin, result]) => result.dispatcher[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: + throw new UndiciError( + pending.length === 1 ? `1 interceptor is pending: + +${pendingInterceptorsFormatter.format(pending)}`.trim() : `${pending.length} interceptors are pending: -${pendingInterceptorsFormatter.format(pending)} -`.trim()); +${pendingInterceptorsFormatter.format(pending)}`.trim() + ); } }; module2.exports = MockAgent; } }); +// node_modules/undici/lib/mock/snapshot-utils.js +var require_snapshot_utils = __commonJS({ + "node_modules/undici/lib/mock/snapshot-utils.js"(exports2, module2) { + "use strict"; + var { InvalidArgumentError } = require_errors(); + var { runtimeFeatures } = require_runtime_features(); + function createHeaderFilters(matchOptions = {}) { + const { ignoreHeaders = [], excludeHeaders = [], matchHeaders = [], caseSensitive = false } = matchOptions; + return { + ignore: new Set(ignoreHeaders.map((header) => caseSensitive ? header : header.toLowerCase())), + exclude: new Set(excludeHeaders.map((header) => caseSensitive ? header : header.toLowerCase())), + match: new Set(matchHeaders.map((header) => caseSensitive ? header : header.toLowerCase())) + }; + } + var crypto3 = runtimeFeatures.has("crypto") ? require("node:crypto") : null; + var hashId = crypto3?.hash ? (value) => crypto3.hash("sha256", value, "base64url") : (value) => Buffer.from(value).toString("base64url"); + function isUndiciHeaders(headers) { + return Array.isArray(headers) && (headers.length & 1) === 0; + } + function isUrlExcludedFactory(excludePatterns = []) { + if (excludePatterns.length === 0) { + return () => false; + } + return function isUrlExcluded(url2) { + let urlLowerCased; + for (const pattern of excludePatterns) { + if (typeof pattern === "string") { + if (!urlLowerCased) { + urlLowerCased = url2.toLowerCase(); + } + if (urlLowerCased.includes(pattern.toLowerCase())) { + return true; + } + } else if (pattern instanceof RegExp) { + if (pattern.test(url2)) { + return true; + } + } + } + return false; + }; + } + function normalizeHeaders(headers) { + const normalizedHeaders = {}; + if (!headers) return normalizedHeaders; + if (isUndiciHeaders(headers)) { + for (let i = 0; i < headers.length; i += 2) { + const key = headers[i]; + const value = headers[i + 1]; + if (key && value !== void 0) { + const keyStr = Buffer.isBuffer(key) ? key.toString() : key; + const valueStr = Buffer.isBuffer(value) ? value.toString() : value; + normalizedHeaders[keyStr.toLowerCase()] = valueStr; + } + } + return normalizedHeaders; + } + if (headers && typeof headers === "object") { + for (const [key, value] of Object.entries(headers)) { + if (key && typeof key === "string") { + normalizedHeaders[key.toLowerCase()] = Array.isArray(value) ? value.join(", ") : String(value); + } + } + } + return normalizedHeaders; + } + var validSnapshotModes = ( + /** @type {const} */ + ["record", "playback", "update"] + ); + function validateSnapshotMode(mode) { + if (!validSnapshotModes.includes(mode)) { + throw new InvalidArgumentError(`Invalid snapshot mode: ${mode}. Must be one of: ${validSnapshotModes.join(", ")}`); + } + } + module2.exports = { + createHeaderFilters, + hashId, + isUndiciHeaders, + normalizeHeaders, + isUrlExcludedFactory, + validateSnapshotMode + }; + } +}); + +// node_modules/undici/lib/mock/snapshot-recorder.js +var require_snapshot_recorder = __commonJS({ + "node_modules/undici/lib/mock/snapshot-recorder.js"(exports2, module2) { + "use strict"; + var { writeFile, readFile, mkdir } = require("node:fs/promises"); + var { dirname: dirname6, resolve: resolve15 } = require("node:path"); + var { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = require("node:timers"); + var { InvalidArgumentError, UndiciError } = require_errors(); + var { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = require_snapshot_utils(); + function formatRequestKey(opts, headerFilters, matchOptions = {}) { + const url2 = new URL(opts.path, opts.origin); + const normalized = opts._normalizedHeaders || normalizeHeaders(opts.headers); + if (!opts._normalizedHeaders) { + opts._normalizedHeaders = normalized; + } + return { + method: opts.method || "GET", + url: matchOptions.matchQuery !== false ? url2.toString() : `${url2.origin}${url2.pathname}`, + headers: filterHeadersForMatching(normalized, headerFilters, matchOptions), + body: matchOptions.matchBody !== false && opts.body ? String(opts.body) : "" + }; + } + function filterHeadersForMatching(headers, headerFilters, matchOptions = {}) { + if (!headers || typeof headers !== "object") return {}; + const { + caseSensitive = false + } = matchOptions; + const filtered = {}; + const { ignore, exclude, match: match2 } = headerFilters; + for (const [key, value] of Object.entries(headers)) { + const headerKey = caseSensitive ? key : key.toLowerCase(); + if (exclude.has(headerKey)) continue; + if (ignore.has(headerKey)) continue; + if (match2.size !== 0) { + if (!match2.has(headerKey)) continue; + } + filtered[headerKey] = value; + } + return filtered; + } + function filterHeadersForStorage(headers, headerFilters, matchOptions = {}) { + if (!headers || typeof headers !== "object") return {}; + const { + caseSensitive = false + } = matchOptions; + const filtered = {}; + const { exclude: excludeSet } = headerFilters; + for (const [key, value] of Object.entries(headers)) { + const headerKey = caseSensitive ? key : key.toLowerCase(); + if (excludeSet.has(headerKey)) continue; + filtered[headerKey] = value; + } + return filtered; + } + function createRequestHash(formattedRequest) { + const parts = [ + formattedRequest.method, + formattedRequest.url + ]; + if (formattedRequest.headers && typeof formattedRequest.headers === "object") { + const headerKeys = Object.keys(formattedRequest.headers).sort(); + for (const key of headerKeys) { + const values = Array.isArray(formattedRequest.headers[key]) ? formattedRequest.headers[key] : [formattedRequest.headers[key]]; + parts.push(key); + for (const value of values.sort()) { + parts.push(String(value)); + } + } + } + parts.push(formattedRequest.body); + const content = parts.join("|"); + return hashId(content); + } + var SnapshotRecorder = class { + /** @type {NodeJS.Timeout | null} */ + #flushTimeout; + /** @type {import('./snapshot-utils').IsUrlExcluded} */ + #isUrlExcluded; + /** @type {Map} */ + #snapshots = /* @__PURE__ */ new Map(); + /** @type {string|undefined} */ + #snapshotPath; + /** @type {number} */ + #maxSnapshots = Infinity; + /** @type {boolean} */ + #autoFlush = false; + /** @type {import('./snapshot-utils').HeaderFilters} */ + #headerFilters; + /** + * Creates a new SnapshotRecorder instance + * @param {SnapshotRecorderOptions&SnapshotRecorderMatchOptions} [options={}] - Configuration options for the recorder + */ + constructor(options = {}) { + this.#snapshotPath = options.snapshotPath; + this.#maxSnapshots = options.maxSnapshots || Infinity; + this.#autoFlush = options.autoFlush || false; + this.flushInterval = options.flushInterval || 3e4; + this._flushTimer = null; + this.matchOptions = { + matchHeaders: options.matchHeaders || [], + // empty means match all headers + ignoreHeaders: options.ignoreHeaders || [], + excludeHeaders: options.excludeHeaders || [], + matchBody: options.matchBody !== false, + // default: true + matchQuery: options.matchQuery !== false, + // default: true + caseSensitive: options.caseSensitive || false + }; + this.#headerFilters = createHeaderFilters(this.matchOptions); + this.shouldRecord = options.shouldRecord || (() => true); + this.shouldPlayback = options.shouldPlayback || (() => true); + this.#isUrlExcluded = isUrlExcludedFactory(options.excludeUrls); + if (this.#autoFlush && this.#snapshotPath) { + this.#startAutoFlush(); + } + } + /** + * Records a request-response interaction + * @param {SnapshotRequestOptions} requestOpts - Request options + * @param {SnapshotEntryResponse} response - Response data to record + * @return {Promise} - Resolves when the recording is complete + */ + async record(requestOpts, response) { + if (!this.shouldRecord(requestOpts)) { + return; + } + if (this.isUrlExcluded(requestOpts)) { + return; + } + const request3 = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions); + const hash2 = createRequestHash(request3); + const normalizedHeaders = normalizeHeaders(response.headers); + const responseData = { + statusCode: response.statusCode, + headers: filterHeadersForStorage(normalizedHeaders, this.#headerFilters, this.matchOptions), + body: Buffer.isBuffer(response.body) ? response.body.toString("base64") : Buffer.from(String(response.body || "")).toString("base64"), + trailers: response.trailers + }; + if (this.#snapshots.size >= this.#maxSnapshots && !this.#snapshots.has(hash2)) { + const oldestKey = this.#snapshots.keys().next().value; + this.#snapshots.delete(oldestKey); + } + const existingSnapshot = this.#snapshots.get(hash2); + if (existingSnapshot && existingSnapshot.responses) { + existingSnapshot.responses.push(responseData); + existingSnapshot.timestamp = (/* @__PURE__ */ new Date()).toISOString(); + } else { + this.#snapshots.set(hash2, { + request: request3, + responses: [responseData], + // Always store as array for consistency + callCount: 0, + timestamp: (/* @__PURE__ */ new Date()).toISOString() + }); + } + if (this.#autoFlush && this.#snapshotPath) { + this.#scheduleFlush(); + } + } + /** + * Checks if a URL should be excluded from recording/playback + * @param {SnapshotRequestOptions} requestOpts - Request options to check + * @returns {boolean} - True if URL is excluded + */ + isUrlExcluded(requestOpts) { + const url2 = new URL(requestOpts.path, requestOpts.origin).toString(); + return this.#isUrlExcluded(url2); + } + /** + * Finds a matching snapshot for the given request + * Returns the appropriate response based on call count for sequential responses + * + * @param {SnapshotRequestOptions} requestOpts - Request options to match + * @returns {SnapshotEntry&Record<'response', SnapshotEntryResponse>|undefined} - Matching snapshot response or undefined if not found + */ + findSnapshot(requestOpts) { + if (!this.shouldPlayback(requestOpts)) { + return void 0; + } + if (this.isUrlExcluded(requestOpts)) { + return void 0; + } + const request3 = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions); + const hash2 = createRequestHash(request3); + const snapshot = this.#snapshots.get(hash2); + if (!snapshot) return void 0; + const currentCallCount = snapshot.callCount || 0; + const responseIndex = Math.min(currentCallCount, snapshot.responses.length - 1); + snapshot.callCount = currentCallCount + 1; + return { + ...snapshot, + response: snapshot.responses[responseIndex] + }; + } + /** + * Loads snapshots from file + * @param {string} [filePath] - Optional file path to load snapshots from + * @return {Promise} - Resolves when snapshots are loaded + */ + async loadSnapshots(filePath) { + const path30 = filePath || this.#snapshotPath; + if (!path30) { + throw new InvalidArgumentError("Snapshot path is required"); + } + try { + const data = await readFile(resolve15(path30), "utf8"); + const parsed = JSON.parse(data); + if (Array.isArray(parsed)) { + this.#snapshots.clear(); + for (const { hash: hash2, snapshot } of parsed) { + this.#snapshots.set(hash2, snapshot); + } + } else { + this.#snapshots = new Map(Object.entries(parsed)); + } + } catch (error3) { + if (error3.code === "ENOENT") { + this.#snapshots.clear(); + } else { + throw new UndiciError(`Failed to load snapshots from ${path30}`, { cause: error3 }); + } + } + } + /** + * Saves snapshots to file + * + * @param {string} [filePath] - Optional file path to save snapshots + * @returns {Promise} - Resolves when snapshots are saved + */ + async saveSnapshots(filePath) { + const path30 = filePath || this.#snapshotPath; + if (!path30) { + throw new InvalidArgumentError("Snapshot path is required"); + } + const resolvedPath = resolve15(path30); + await mkdir(dirname6(resolvedPath), { recursive: true }); + const data = Array.from(this.#snapshots.entries()).map(([hash2, snapshot]) => ({ + hash: hash2, + snapshot + })); + await writeFile(resolvedPath, JSON.stringify(data, null, 2), { flush: true }); + } + /** + * Clears all recorded snapshots + * @returns {void} + */ + clear() { + this.#snapshots.clear(); + } + /** + * Gets all recorded snapshots + * @return {Array} - Array of all recorded snapshots + */ + getSnapshots() { + return Array.from(this.#snapshots.values()); + } + /** + * Gets snapshot count + * @return {number} - Number of recorded snapshots + */ + size() { + return this.#snapshots.size; + } + /** + * Resets call counts for all snapshots (useful for test cleanup) + * @returns {void} + */ + resetCallCounts() { + for (const snapshot of this.#snapshots.values()) { + snapshot.callCount = 0; + } + } + /** + * Deletes a specific snapshot by request options + * @param {SnapshotRequestOptions} requestOpts - Request options to match + * @returns {boolean} - True if snapshot was deleted, false if not found + */ + deleteSnapshot(requestOpts) { + const request3 = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions); + const hash2 = createRequestHash(request3); + return this.#snapshots.delete(hash2); + } + /** + * Gets information about a specific snapshot + * @param {SnapshotRequestOptions} requestOpts - Request options to match + * @returns {SnapshotInfo|null} - Snapshot information or null if not found + */ + getSnapshotInfo(requestOpts) { + const request3 = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions); + const hash2 = createRequestHash(request3); + const snapshot = this.#snapshots.get(hash2); + if (!snapshot) return null; + return { + hash: hash2, + request: snapshot.request, + responseCount: snapshot.responses ? snapshot.responses.length : snapshot.response ? 1 : 0, + // .response for legacy snapshots + callCount: snapshot.callCount || 0, + timestamp: snapshot.timestamp + }; + } + /** + * Replaces all snapshots with new data (full replacement) + * @param {Array<{hash: string; snapshot: SnapshotEntry}>|Record} snapshotData - New snapshot data to replace existing ones + * @returns {void} + */ + replaceSnapshots(snapshotData) { + this.#snapshots.clear(); + if (Array.isArray(snapshotData)) { + for (const { hash: hash2, snapshot } of snapshotData) { + this.#snapshots.set(hash2, snapshot); + } + } else if (snapshotData && typeof snapshotData === "object") { + this.#snapshots = new Map(Object.entries(snapshotData)); + } + } + /** + * Starts the auto-flush timer + * @returns {void} + */ + #startAutoFlush() { + return this.#scheduleFlush(); + } + /** + * Stops the auto-flush timer + * @returns {void} + */ + #stopAutoFlush() { + if (this.#flushTimeout) { + clearTimeout2(this.#flushTimeout); + this.saveSnapshots().catch(() => { + }); + this.#flushTimeout = null; + } + } + /** + * Schedules a flush (debounced to avoid excessive writes) + */ + #scheduleFlush() { + this.#flushTimeout = setTimeout2(() => { + this.saveSnapshots().catch(() => { + }); + if (this.#autoFlush) { + this.#flushTimeout?.refresh(); + } else { + this.#flushTimeout = null; + } + }, 1e3); + } + /** + * Cleanup method to stop timers + * @returns {void} + */ + destroy() { + this.#stopAutoFlush(); + if (this.#flushTimeout) { + clearTimeout2(this.#flushTimeout); + this.#flushTimeout = null; + } + } + /** + * Async close method that saves all recordings and performs cleanup + * @returns {Promise} + */ + async close() { + if (this.#snapshotPath && this.#snapshots.size !== 0) { + await this.saveSnapshots(); + } + this.destroy(); + } + }; + module2.exports = { SnapshotRecorder, formatRequestKey, createRequestHash, filterHeadersForMatching, filterHeadersForStorage, createHeaderFilters }; + } +}); + +// node_modules/undici/lib/mock/snapshot-agent.js +var require_snapshot_agent = __commonJS({ + "node_modules/undici/lib/mock/snapshot-agent.js"(exports2, module2) { + "use strict"; + var Agent = require_agent(); + var MockAgent = require_mock_agent(); + var { SnapshotRecorder } = require_snapshot_recorder(); + var WrapHandler = require_wrap_handler(); + var { InvalidArgumentError, UndiciError } = require_errors(); + var { validateSnapshotMode } = require_snapshot_utils(); + var kSnapshotRecorder = /* @__PURE__ */ Symbol("kSnapshotRecorder"); + var kSnapshotMode = /* @__PURE__ */ Symbol("kSnapshotMode"); + var kSnapshotPath = /* @__PURE__ */ Symbol("kSnapshotPath"); + var kSnapshotLoaded = /* @__PURE__ */ Symbol("kSnapshotLoaded"); + var kRealAgent = /* @__PURE__ */ Symbol("kRealAgent"); + var warningEmitted = false; + var SnapshotAgent = class extends MockAgent { + constructor(opts = {}) { + if (!warningEmitted) { + process.emitWarning( + "SnapshotAgent is experimental and subject to change", + "ExperimentalWarning" + ); + warningEmitted = true; + } + const { + mode = "record", + snapshotPath = null, + ...mockAgentOpts + } = opts; + super(mockAgentOpts); + validateSnapshotMode(mode); + if ((mode === "playback" || mode === "update") && !snapshotPath) { + throw new InvalidArgumentError(`snapshotPath is required when mode is '${mode}'`); + } + this[kSnapshotMode] = mode; + this[kSnapshotPath] = snapshotPath; + this[kSnapshotRecorder] = new SnapshotRecorder({ + snapshotPath: this[kSnapshotPath], + mode: this[kSnapshotMode], + maxSnapshots: opts.maxSnapshots, + autoFlush: opts.autoFlush, + flushInterval: opts.flushInterval, + matchHeaders: opts.matchHeaders, + ignoreHeaders: opts.ignoreHeaders, + excludeHeaders: opts.excludeHeaders, + matchBody: opts.matchBody, + matchQuery: opts.matchQuery, + caseSensitive: opts.caseSensitive, + shouldRecord: opts.shouldRecord, + shouldPlayback: opts.shouldPlayback, + excludeUrls: opts.excludeUrls + }); + this[kSnapshotLoaded] = false; + if (this[kSnapshotMode] === "record" || this[kSnapshotMode] === "update" || this[kSnapshotMode] === "playback" && opts.excludeUrls && opts.excludeUrls.length > 0) { + this[kRealAgent] = new Agent(opts); + } + if ((this[kSnapshotMode] === "playback" || this[kSnapshotMode] === "update") && this[kSnapshotPath]) { + this.loadSnapshots().catch(() => { + }); + } + } + dispatch(opts, handler2) { + handler2 = WrapHandler.wrap(handler2); + const mode = this[kSnapshotMode]; + if (this[kSnapshotRecorder].isUrlExcluded(opts)) { + return this[kRealAgent].dispatch(opts, handler2); + } + if (mode === "playback" || mode === "update") { + if (!this[kSnapshotLoaded]) { + return this.#asyncDispatch(opts, handler2); + } + const snapshot = this[kSnapshotRecorder].findSnapshot(opts); + if (snapshot) { + return this.#replaySnapshot(snapshot, handler2); + } else if (mode === "update") { + return this.#recordAndReplay(opts, handler2); + } else { + const error3 = new UndiciError(`No snapshot found for ${opts.method || "GET"} ${opts.path}`); + if (handler2.onError) { + handler2.onError(error3); + return; + } + throw error3; + } + } else if (mode === "record") { + return this.#recordAndReplay(opts, handler2); + } + } + /** + * Async version of dispatch for when we need to load snapshots first + */ + async #asyncDispatch(opts, handler2) { + await this.loadSnapshots(); + return this.dispatch(opts, handler2); + } + /** + * Records a real request and replays the response + */ + #recordAndReplay(opts, handler2) { + const responseData = { + statusCode: null, + headers: {}, + trailers: {}, + body: [] + }; + const self2 = this; + const recordingHandler = { + onRequestStart(controller, context5) { + return handler2.onRequestStart(controller, { ...context5, history: this.history }); + }, + onRequestUpgrade(controller, statusCode, headers, socket) { + return handler2.onRequestUpgrade(controller, statusCode, headers, socket); + }, + onResponseStart(controller, statusCode, headers, statusMessage) { + responseData.statusCode = statusCode; + responseData.headers = headers; + return handler2.onResponseStart(controller, statusCode, headers, statusMessage); + }, + onResponseData(controller, chunk) { + responseData.body.push(chunk); + return handler2.onResponseData(controller, chunk); + }, + onResponseEnd(controller, trailers) { + responseData.trailers = trailers; + const responseBody = Buffer.concat(responseData.body); + self2[kSnapshotRecorder].record(opts, { + statusCode: responseData.statusCode, + headers: responseData.headers, + body: responseBody, + trailers: responseData.trailers + }).then(() => handler2.onResponseEnd(controller, trailers)).catch((error3) => handler2.onResponseError(controller, error3)); + } + }; + const agent = this[kRealAgent]; + return agent.dispatch(opts, recordingHandler); + } + /** + * Replays a recorded response + * + * @param {Object} snapshot - The recorded snapshot to replay. + * @param {Object} handler - The handler to call with the response data. + * @returns {void} + */ + #replaySnapshot(snapshot, handler2) { + try { + const { response } = snapshot; + const controller = { + pause() { + }, + resume() { + }, + abort(reason) { + this.aborted = true; + this.reason = reason; + }, + aborted: false, + paused: false + }; + handler2.onRequestStart(controller); + handler2.onResponseStart(controller, response.statusCode, response.headers); + const body = Buffer.from(response.body, "base64"); + handler2.onResponseData(controller, body); + handler2.onResponseEnd(controller, response.trailers); + } catch (error3) { + handler2.onError?.(error3); + } + } + /** + * Loads snapshots from file + * + * @param {string} [filePath] - Optional file path to load snapshots from. + * @returns {Promise} - Resolves when snapshots are loaded. + */ + async loadSnapshots(filePath) { + await this[kSnapshotRecorder].loadSnapshots(filePath || this[kSnapshotPath]); + this[kSnapshotLoaded] = true; + if (this[kSnapshotMode] === "playback") { + this.#setupMockInterceptors(); + } + } + /** + * Saves snapshots to file + * + * @param {string} [filePath] - Optional file path to save snapshots to. + * @returns {Promise} - Resolves when snapshots are saved. + */ + async saveSnapshots(filePath) { + return this[kSnapshotRecorder].saveSnapshots(filePath || this[kSnapshotPath]); + } + /** + * Sets up MockAgent interceptors based on recorded snapshots. + * + * This method creates MockAgent interceptors for each recorded snapshot, + * allowing the SnapshotAgent to fall back to MockAgent's standard intercept + * mechanism in playback mode. Each interceptor is configured to persist + * (remain active for multiple requests) and responds with the recorded + * response data. + * + * Called automatically when loading snapshots in playback mode. + * + * @returns {void} + */ + #setupMockInterceptors() { + for (const snapshot of this[kSnapshotRecorder].getSnapshots()) { + const { request: request3, responses, response } = snapshot; + const url2 = new URL(request3.url); + const mockPool = this.get(url2.origin); + const responseData = responses ? responses[0] : response; + if (!responseData) continue; + mockPool.intercept({ + path: url2.pathname + url2.search, + method: request3.method, + headers: request3.headers, + body: request3.body + }).reply(responseData.statusCode, responseData.body, { + headers: responseData.headers, + trailers: responseData.trailers + }).persist(); + } + } + /** + * Gets the snapshot recorder + * @return {SnapshotRecorder} - The snapshot recorder instance + */ + getRecorder() { + return this[kSnapshotRecorder]; + } + /** + * Gets the current mode + * @return {import('./snapshot-utils').SnapshotMode} - The current snapshot mode + */ + getMode() { + return this[kSnapshotMode]; + } + /** + * Clears all snapshots + * @returns {void} + */ + clearSnapshots() { + this[kSnapshotRecorder].clear(); + } + /** + * Resets call counts for all snapshots (useful for test cleanup) + * @returns {void} + */ + resetCallCounts() { + this[kSnapshotRecorder].resetCallCounts(); + } + /** + * Deletes a specific snapshot by request options + * @param {import('./snapshot-recorder').SnapshotRequestOptions} requestOpts - Request options to identify the snapshot + * @return {Promise} - Returns true if the snapshot was deleted, false if not found + */ + deleteSnapshot(requestOpts) { + return this[kSnapshotRecorder].deleteSnapshot(requestOpts); + } + /** + * Gets information about a specific snapshot + * @returns {import('./snapshot-recorder').SnapshotInfo|null} - Snapshot information or null if not found + */ + getSnapshotInfo(requestOpts) { + return this[kSnapshotRecorder].getSnapshotInfo(requestOpts); + } + /** + * Replaces all snapshots with new data (full replacement) + * @param {Array<{hash: string; snapshot: import('./snapshot-recorder').SnapshotEntryshotEntry}>|Record} snapshotData - New snapshot data to replace existing snapshots + * @returns {void} + */ + replaceSnapshots(snapshotData) { + this[kSnapshotRecorder].replaceSnapshots(snapshotData); + } + /** + * Closes the agent, saving snapshots and cleaning up resources. + * + * @returns {Promise} + */ + async close() { + await this[kSnapshotRecorder].close(); + await this[kRealAgent]?.close(); + await super.close(); + } + }; + module2.exports = SnapshotAgent; + } +}); + // node_modules/undici/lib/global.js var require_global2 = __commonJS({ "node_modules/undici/lib/global.js"(exports2, module2) { "use strict"; - var globalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1"); + var globalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.2"); + var legacyGlobalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1"); var { InvalidArgumentError } = require_errors(); var Agent = require_agent(); if (getGlobalDispatcher() === void 0) { @@ -11596,13 +15131,35 @@ var require_global2 = __commonJS({ enumerable: false, configurable: false }); + Object.defineProperty(globalThis, legacyGlobalDispatcher, { + value: agent, + writable: true, + enumerable: false, + configurable: false + }); } function getGlobalDispatcher() { - return globalThis[globalDispatcher]; + return globalThis[legacyGlobalDispatcher]; } + var installedExports = ( + /** @type {const} */ + [ + "fetch", + "Headers", + "Response", + "Request", + "FormData", + "WebSocket", + "CloseEvent", + "ErrorEvent", + "MessageEvent", + "EventSource" + ] + ); module2.exports = { setGlobalDispatcher, - getGlobalDispatcher + getGlobalDispatcher, + installedExports }; } }); @@ -11611,39 +15168,220 @@ var require_global2 = __commonJS({ var require_decorator_handler = __commonJS({ "node_modules/undici/lib/handler/decorator-handler.js"(exports2, module2) { "use strict"; + var assert = require("node:assert"); + var WrapHandler = require_wrap_handler(); module2.exports = class DecoratorHandler { #handler; + #onCompleteCalled = false; + #onErrorCalled = false; + #onResponseStartCalled = false; constructor(handler2) { if (typeof handler2 !== "object" || handler2 === null) { throw new TypeError("handler must be an object"); } - this.#handler = handler2; + this.#handler = WrapHandler.wrap(handler2); } - onConnect(...args) { - return this.#handler.onConnect?.(...args); + onRequestStart(...args) { + this.#handler.onRequestStart?.(...args); } - onError(...args) { - return this.#handler.onError?.(...args); + onRequestUpgrade(...args) { + assert(!this.#onCompleteCalled); + assert(!this.#onErrorCalled); + return this.#handler.onRequestUpgrade?.(...args); } - onUpgrade(...args) { - return this.#handler.onUpgrade?.(...args); + onResponseStart(...args) { + assert(!this.#onCompleteCalled); + assert(!this.#onErrorCalled); + assert(!this.#onResponseStartCalled); + this.#onResponseStartCalled = true; + return this.#handler.onResponseStart?.(...args); } - onResponseStarted(...args) { - return this.#handler.onResponseStarted?.(...args); + onResponseData(...args) { + assert(!this.#onCompleteCalled); + assert(!this.#onErrorCalled); + return this.#handler.onResponseData?.(...args); } - onHeaders(...args) { - return this.#handler.onHeaders?.(...args); + onResponseEnd(...args) { + assert(!this.#onCompleteCalled); + assert(!this.#onErrorCalled); + this.#onCompleteCalled = true; + return this.#handler.onResponseEnd?.(...args); } - onData(...args) { - return this.#handler.onData?.(...args); + onResponseError(...args) { + this.#onErrorCalled = true; + return this.#handler.onResponseError?.(...args); } - onComplete(...args) { - return this.#handler.onComplete?.(...args); + /** + * @deprecated + */ + onBodySent() { } - onBodySent(...args) { - return this.#handler.onBodySent?.(...args); + }; + } +}); + +// node_modules/undici/lib/handler/redirect-handler.js +var require_redirect_handler = __commonJS({ + "node_modules/undici/lib/handler/redirect-handler.js"(exports2, module2) { + "use strict"; + var util4 = require_util(); + var { kBodyUsed, kRedirectCacheControl } = require_symbols(); + var assert = require("node:assert"); + var { InvalidArgumentError } = require_errors(); + var EE = require("node:events"); + var redirectableStatusCodes = [300, 301, 302, 303, 307, 308]; + var kBody = /* @__PURE__ */ Symbol("body"); + var noop3 = () => { + }; + var BodyAsyncIterable = class { + constructor(body) { + this[kBody] = body; + this[kBodyUsed] = false; + } + async *[Symbol.asyncIterator]() { + assert(!this[kBodyUsed], "disturbed"); + this[kBodyUsed] = true; + yield* this[kBody]; + } + }; + var RedirectHandler = class _RedirectHandler { + static buildDispatch(dispatcher, maxRedirections) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError("maxRedirections must be a positive number"); + } + const dispatch = dispatcher.dispatch.bind(dispatcher); + return (opts, originalHandler) => dispatch(opts, new _RedirectHandler(dispatch, maxRedirections, opts, originalHandler)); + } + constructor(dispatch, maxRedirections, opts, handler2) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError("maxRedirections must be a positive number"); + } + this.dispatch = dispatch; + this.location = null; + const { maxRedirections: _2, ...cleanOpts } = opts; + this.opts = cleanOpts; + this.maxRedirections = maxRedirections; + this.handler = handler2; + this.history = []; + Object.defineProperty(this.history, kRedirectCacheControl, { + value: [], + enumerable: false + }); + if (util4.isStream(this.opts.body)) { + if (util4.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") { + this.opts.body = new BodyAsyncIterable(this.opts.body); + } else if (this.opts.body && typeof this.opts.body !== "string" && !ArrayBuffer.isView(this.opts.body) && util4.isIterable(this.opts.body) && !util4.isFormDataLike(this.opts.body)) { + this.opts.body = new BodyAsyncIterable(this.opts.body); + } + } + onRequestStart(controller, context5) { + this.handler.onRequestStart?.(controller, { ...context5, history: this.history }); + } + onRequestUpgrade(controller, statusCode, headers, socket) { + this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket); + } + onResponseStart(controller, statusCode, headers, statusMessage) { + if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) { + throw new Error("max redirects"); + } + if ((statusCode === 301 || statusCode === 302) && this.opts.method === "POST") { + this.opts.method = "GET"; + if (util4.isStream(this.opts.body)) { + util4.destroy(this.opts.body.on("error", noop3)); + } + this.opts.body = null; + } + if (statusCode === 303 && this.opts.method !== "HEAD") { + this.opts.method = "GET"; + if (util4.isStream(this.opts.body)) { + util4.destroy(this.opts.body.on("error", noop3)); + } + this.opts.body = null; + } + this.location = this.history.length >= this.maxRedirections || util4.isDisturbed(this.opts.body) || redirectableStatusCodes.indexOf(statusCode) === -1 ? null : headers.location; + if (this.opts.origin) { + this.history.push(new URL(this.opts.path, this.opts.origin)); + } + if (!this.location) { + this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage); + return; + } + this.history[kRedirectCacheControl].push(headers["cache-control"]); + const { origin, pathname, search } = util4.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))); + const path30 = search ? `${pathname}${search}` : pathname; + const redirectUrlString = `${origin}${path30}`; + for (const historyUrl of this.history) { + if (historyUrl.toString() === redirectUrlString) { + throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`); + } + } + this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin); + this.opts.path = path30; + this.opts.origin = origin; + this.opts.query = null; + } + onResponseData(controller, chunk) { + if (this.location) { + } else { + this.handler.onResponseData?.(controller, chunk); + } + } + onResponseEnd(controller, trailers) { + if (this.location) { + this.dispatch(this.opts, this); + } else { + this.handler.onResponseEnd(controller, trailers); + } + } + onResponseError(controller, error3) { + this.handler.onResponseError?.(controller, error3); } }; + function shouldRemoveHeader(header, removeContent, unknownOrigin) { + if (header.length === 4) { + return util4.headerNameToString(header) === "host"; + } + if (removeContent && util4.headerNameToString(header).startsWith("content-")) { + return true; + } + if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { + const name = util4.headerNameToString(header); + return name === "authorization" || name === "cookie" || name === "proxy-authorization"; + } + return false; + } + 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") { + const entries = util4.hasSafeIterator(headers) ? headers : Object.entries(headers); + for (const [key, value] of entries) { + if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { + ret.push(key, value); + } + } + } else { + assert(headers == null, "headers must be an object or an array"); + } + return ret; + } + module2.exports = RedirectHandler; } }); @@ -11652,21 +15390,99 @@ var require_redirect = __commonJS({ "node_modules/undici/lib/interceptor/redirect.js"(exports2, module2) { "use strict"; var RedirectHandler = require_redirect_handler(); - module2.exports = (opts) => { - const globalMaxRedirections = opts?.maxRedirections; + function createRedirectInterceptor({ maxRedirections: defaultMaxRedirections } = {}) { return (dispatch) => { - return function redirectInterceptor(opts2, handler2) { - const { maxRedirections = globalMaxRedirections, ...baseOpts } = opts2; - if (!maxRedirections) { - return dispatch(opts2, handler2); + return function Intercept(opts, handler2) { + const { maxRedirections = defaultMaxRedirections, ...rest } = opts; + if (maxRedirections == null || maxRedirections === 0) { + return dispatch(opts, handler2); } - const redirectHandler = new RedirectHandler( - dispatch, - maxRedirections, - opts2, - handler2 - ); - return dispatch(baseOpts, redirectHandler); + const dispatchOpts = { ...rest }; + const redirectHandler = new RedirectHandler(dispatch, maxRedirections, dispatchOpts, handler2); + return dispatch(dispatchOpts, redirectHandler); + }; + }; + } + module2.exports = createRedirectInterceptor; + } +}); + +// node_modules/undici/lib/interceptor/response-error.js +var require_response_error = __commonJS({ + "node_modules/undici/lib/interceptor/response-error.js"(exports2, module2) { + "use strict"; + var DecoratorHandler = require_decorator_handler(); + var { ResponseError } = require_errors(); + var ResponseErrorHandler = class extends DecoratorHandler { + #statusCode; + #contentType; + #decoder; + #headers; + #body; + constructor(_opts, { handler: handler2 }) { + super(handler2); + } + #checkContentType(contentType) { + return (this.#contentType ?? "").indexOf(contentType) === 0; + } + onRequestStart(controller, context5) { + this.#statusCode = 0; + this.#contentType = null; + this.#decoder = null; + this.#headers = null; + this.#body = ""; + return super.onRequestStart(controller, context5); + } + onResponseStart(controller, statusCode, headers, statusMessage) { + this.#statusCode = statusCode; + this.#headers = headers; + this.#contentType = headers["content-type"]; + if (this.#statusCode < 400) { + return super.onResponseStart(controller, statusCode, headers, statusMessage); + } + if (this.#checkContentType("application/json") || this.#checkContentType("text/plain")) { + this.#decoder = new TextDecoder("utf-8"); + } + } + onResponseData(controller, chunk) { + if (this.#statusCode < 400) { + return super.onResponseData(controller, chunk); + } + this.#body += this.#decoder?.decode(chunk, { stream: true }) ?? ""; + } + onResponseEnd(controller, trailers) { + if (this.#statusCode >= 400) { + this.#body += this.#decoder?.decode(void 0, { stream: false }) ?? ""; + if (this.#checkContentType("application/json")) { + try { + this.#body = JSON.parse(this.#body); + } catch { + } + } + let err; + const stackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + try { + err = new ResponseError("Response Error", this.#statusCode, { + body: this.#body, + headers: this.#headers + }); + } finally { + Error.stackTraceLimit = stackTraceLimit; + } + super.onResponseError(controller, err); + } else { + super.onResponseEnd(controller, trailers); + } + } + onResponseError(controller, err) { + super.onResponseError(controller, err); + } + }; + module2.exports = () => { + return (dispatch) => { + return function Intercept(opts, handler2) { + return dispatch(opts, new ResponseErrorHandler(opts, { handler: handler2 })); }; }; }; @@ -11701,80 +15517,62 @@ var require_retry = __commonJS({ var require_dump = __commonJS({ "node_modules/undici/lib/interceptor/dump.js"(exports2, module2) { "use strict"; - var util3 = require_util(); var { InvalidArgumentError, RequestAbortedError } = require_errors(); var DecoratorHandler = require_decorator_handler(); var DumpHandler = class extends DecoratorHandler { #maxSize = 1024 * 1024; - #abort = null; #dumped = false; - #aborted = false; #size = 0; - #reason = null; - #handler = null; - constructor({ maxSize }, handler2) { - super(handler2); + aborted = false; + reason = false; + constructor({ maxSize, signal }, handler2) { if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) { throw new InvalidArgumentError("maxSize must be a number greater than 0"); } + super(handler2); this.#maxSize = maxSize ?? this.#maxSize; - this.#handler = handler2; } - onConnect(abort) { - this.#abort = abort; - this.#handler.onConnect(this.#customAbort.bind(this)); + #abort(reason) { + this.aborted = true; + this.reason = reason; } - #customAbort(reason) { - this.#aborted = true; - this.#reason = reason; + onRequestStart(controller, context5) { + controller.abort = this.#abort.bind(this); + return super.onRequestStart(controller, context5); } - // TODO: will require adjustment after new hooks are out - onHeaders(statusCode, rawHeaders, resume, statusMessage) { - const headers = util3.parseHeaders(rawHeaders); + onResponseStart(controller, statusCode, headers, statusMessage) { 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) { + if (this.aborted === true) { return true; } - return this.#handler.onHeaders( - statusCode, - rawHeaders, - resume, - statusMessage - ); + return super.onResponseStart(controller, statusCode, headers, statusMessage); } - onError(err) { - if (this.#dumped) { - return; - } - err = this.#reason ?? err; - this.#handler.onError(err); + onResponseError(controller, err) { + super.onResponseError(controller, this.aborted === true ? this.reason : err); } - onData(chunk) { + onResponseData(controller, chunk) { this.#size = this.#size + chunk.length; - if (this.#size >= this.#maxSize) { + if (this.#size > this.#maxSize) { + throw new RequestAbortedError( + `Response size (${this.#size}) larger than maxSize (${this.#maxSize})` + ); + } + 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); + onResponseEnd(controller, trailers) { + if (this.aborted === true) { + super.onResponseError(controller, this.reason); return; } - this.#handler.onComplete(trailers); + super.onResponseEnd(controller, this.#dumped ? {} : trailers); } }; function createDumpInterceptor({ maxSize: defaultMaxSize } = { @@ -11783,10 +15581,7 @@ var require_dump = __commonJS({ return (dispatch) => { return function Intercept(opts, handler2) { const { dumpMaxSize = defaultMaxSize } = opts; - const dumpHandler = new DumpHandler( - { maxSize: dumpMaxSize }, - handler2 - ); + const dumpHandler = new DumpHandler({ maxSize: dumpMaxSize, signal: opts.signal }, handler2); return dispatch(opts, dumpHandler); }; }; @@ -11804,14 +15599,116 @@ var require_dns = __commonJS({ var DecoratorHandler = require_decorator_handler(); var { InvalidArgumentError, InformationalError } = require_errors(); var maxInt = Math.pow(2, 31) - 1; + function hasSafeIterator(headers) { + const prototype = Object.getPrototypeOf(headers); + const ownIterator = Object.prototype.hasOwnProperty.call(headers, Symbol.iterator); + return ownIterator || prototype != null && prototype !== Object.prototype && typeof headers[Symbol.iterator] === "function"; + } + function isHostHeader(key) { + return typeof key === "string" && key.toLowerCase() === "host"; + } + function normalizeHeaders(headers) { + if (headers == null) { + return null; + } + if (Array.isArray(headers)) { + if (headers.length === 0 || !Array.isArray(headers[0])) { + return headers; + } + const normalized = []; + for (const header of headers) { + if (Array.isArray(header) && header.length === 2) { + normalized.push(header[0], header[1]); + } else { + normalized.push(header); + } + } + return normalized; + } + if (typeof headers === "object" && hasSafeIterator(headers)) { + const normalized = []; + for (const header of headers) { + if (Array.isArray(header) && header.length === 2) { + normalized.push(header[0], header[1]); + } else { + normalized.push(header); + } + } + return normalized; + } + return headers; + } + function hasHostHeader(headers) { + if (headers == null) { + return false; + } + if (Array.isArray(headers)) { + if (headers.length === 0) { + return false; + } + for (let i = 0; i < headers.length; i += 2) { + if (isHostHeader(headers[i])) { + return true; + } + } + return false; + } + if (typeof headers === "object") { + for (const key in headers) { + if (isHostHeader(key)) { + return true; + } + } + } + return false; + } + function withHostHeader(host, headers) { + const normalizedHeaders = normalizeHeaders(headers); + if (hasHostHeader(normalizedHeaders)) { + return normalizedHeaders; + } + if (Array.isArray(normalizedHeaders)) { + return ["host", host, ...normalizedHeaders]; + } + if (normalizedHeaders && typeof normalizedHeaders === "object") { + return { + host, + ...normalizedHeaders + }; + } + return { host }; + } + var DNSStorage = class { + #maxItems = 0; + #records = /* @__PURE__ */ new Map(); + constructor(opts) { + this.#maxItems = opts.maxItems; + } + get size() { + return this.#records.size; + } + get(hostname) { + return this.#records.get(hostname) ?? null; + } + set(hostname, records) { + this.#records.set(hostname, records); + } + delete(hostname) { + this.#records.delete(hostname); + } + // Delegate to storage decide can we do more lookups or not + full() { + return this.size >= this.#maxItems; + } + }; var DNSInstance = class { #maxTTL = 0; #maxItems = 0; - #records = /* @__PURE__ */ new Map(); dualStack = true; affinity = null; lookup = null; pick = null; + storage = null; constructor(opts) { this.#maxTTL = opts.maxTTL; this.#maxItems = opts.maxItems; @@ -11819,14 +15716,12 @@ var require_dns = __commonJS({ this.affinity = opts.affinity; this.lookup = opts.lookup ?? this.#defaultLookup; this.pick = opts.pick ?? this.#defaultPick; - } - get full() { - return this.#records.size === this.#maxItems; + this.storage = opts.storage ?? new DNSStorage(opts); } runLookup(origin, opts, cb) { - const ips = this.#records.get(origin.hostname); - if (ips == null && this.full) { - cb(null, origin.origin); + const ips = this.storage.get(origin.hostname); + if (ips == null && this.storage.full()) { + cb(null, origin); return; } const newOpts = { @@ -11845,7 +15740,7 @@ var require_dns = __commonJS({ return; } this.setRecords(origin, addresses); - const records = this.#records.get(origin.hostname); + const records = this.storage.get(origin.hostname); const ip = this.pick( origin, records, @@ -11861,7 +15756,7 @@ var require_dns = __commonJS({ } cb( null, - `${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}` + new URL(`${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`) ); }); } else { @@ -11871,7 +15766,7 @@ var require_dns = __commonJS({ newOpts.affinity ); if (ip == null) { - this.#records.delete(origin.hostname); + this.storage.delete(origin.hostname); this.runLookup(origin, opts, cb); return; } @@ -11885,7 +15780,7 @@ var require_dns = __commonJS({ } cb( null, - `${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}` + new URL(`${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`) ); } } @@ -11950,13 +15845,39 @@ var require_dns = __commonJS({ } return ip; } + pickFamily(origin, ipFamily) { + const records = this.storage.get(origin.hostname)?.records; + if (!records) { + return null; + } + const family = records[ipFamily]; + if (!family) { + return null; + } + if (family.offset == null || family.offset === maxInt) { + family.offset = 0; + } else { + family.offset++; + } + const position = family.offset % family.ips.length; + const ip = family.ips[position] ?? null; + if (ip == null) { + return ip; + } + if (Date.now() - ip.timestamp > ip.ttl) { + family.ips.splice(position, 1); + } + return ip; + } setRecords(origin, addresses) { const timestamp = Date.now(); const records = { records: { 4: null, 6: null } }; + let minTTL = this.#maxTTL; for (const record of addresses) { record.timestamp = timestamp; if (typeof record.ttl === "number") { record.ttl = Math.min(record.ttl, this.#maxTTL); + minTTL = Math.min(minTTL, record.ttl); } else { record.ttl = this.#maxTTL; } @@ -11964,7 +15885,10 @@ var require_dns = __commonJS({ familyRecords.ips.push(record); records.records[record.family] = familyRecords; } - this.#records.set(origin.hostname, records); + this.storage.set(origin.hostname, records, { ttl: minTTL }); + } + deleteRecords(origin) { + this.storage.delete(origin.hostname); } getHandler(meta, opts) { return new DNSDispatchHandler(this, meta, opts); @@ -11974,41 +15898,59 @@ var require_dns = __commonJS({ #state = null; #opts = null; #dispatch = null; - #handler = null; #origin = null; - constructor(state, { origin, handler: handler2, dispatch }, opts) { + #controller = null; + #newOrigin = null; + #firstTry = true; + constructor(state, { origin, handler: handler2, dispatch, newOrigin }, opts) { super(handler2); this.#origin = origin; - this.#handler = handler2; + this.#newOrigin = newOrigin; this.#opts = { ...opts }; this.#state = state; this.#dispatch = dispatch; } - onError(err) { + onResponseError(controller, err) { switch (err.code) { case "ETIMEDOUT": case "ECONNREFUSED": { if (this.#state.dualStack) { - this.#state.runLookup(this.#origin, this.#opts, (err2, newOrigin) => { - if (err2) { - return this.#handler.onError(err2); - } - const dispatchOpts = { - ...this.#opts, - origin: newOrigin - }; - this.#dispatch(dispatchOpts, this); - }); + if (!this.#firstTry) { + super.onResponseError(controller, err); + return; + } + this.#firstTry = false; + const otherFamily = this.#newOrigin.hostname[0] === "[" ? 4 : 6; + const ip = this.#state.pickFamily(this.#origin, otherFamily); + if (ip == null) { + super.onResponseError(controller, err); + return; + } + let port; + if (typeof ip.port === "number") { + port = `:${ip.port}`; + } else if (this.#origin.port !== "") { + port = `:${this.#origin.port}`; + } else { + port = ""; + } + const dispatchOpts = { + ...this.#opts, + origin: `${this.#origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`, + headers: withHostHeader(this.#origin.host, this.#opts.headers) + }; + this.#dispatch(dispatchOpts, this); return; } - this.#handler.onError(err); - return; + super.onResponseError(controller, err); + break; } case "ENOTFOUND": - this.#state.deleteRecord(this.#origin); - // eslint-disable-next-line no-fallthrough + this.#state.deleteRecords(this.#origin); + super.onResponseError(controller, err); + break; default: - this.#handler.onError(err); + super.onResponseError(controller, err); break; } } @@ -12034,6 +15976,9 @@ var require_dns = __commonJS({ if (interceptorOpts?.pick != null && typeof interceptorOpts?.pick !== "function") { throw new InvalidArgumentError("Invalid pick. Must be a function"); } + if (interceptorOpts?.storage != null && (typeof interceptorOpts?.storage?.get !== "function" || typeof interceptorOpts?.storage?.set !== "function" || typeof interceptorOpts?.storage?.full !== "function" || typeof interceptorOpts?.storage?.delete !== "function")) { + throw new InvalidArgumentError("Invalid storage. Must be a object with methods: { get, set, full, delete }"); + } const dualStack = interceptorOpts?.dualStack ?? true; let affinity; if (dualStack) { @@ -12048,33 +15993,33 @@ var require_dns = __commonJS({ pick: interceptorOpts?.pick ?? null, dualStack, affinity, - maxItems: interceptorOpts?.maxItems ?? Infinity + maxItems: interceptorOpts?.maxItems ?? Infinity, + storage: interceptorOpts?.storage }; - const instance = new DNSInstance(opts); + const instance8 = new DNSInstance(opts); return (dispatch) => { return function dnsInterceptor(origDispatchOpts, handler2) { const origin = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin); if (isIP(origin.hostname) !== 0) { return dispatch(origDispatchOpts, handler2); } - instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => { + instance8.runLookup(origin, origDispatchOpts, (err, newOrigin) => { if (err) { - return handler2.onError(err); + return handler2.onResponseError(null, err); } - let dispatchOpts = null; - dispatchOpts = { + const dispatchOpts = { ...origDispatchOpts, servername: origin.hostname, // For SNI on TLS - origin: newOrigin, - headers: { - host: origin.hostname, - ...origDispatchOpts.headers - } + origin: newOrigin.origin, + headers: withHostHeader(origin.host, origDispatchOpts.headers) }; dispatch( dispatchOpts, - instance.getHandler({ origin, dispatch, handler: handler2 }, origDispatchOpts) + instance8.getHandler( + { origin, dispatch, handler: handler2, newOrigin }, + origDispatchOpts + ) ); }); return true; @@ -12084,8488 +16029,10812 @@ var require_dns = __commonJS({ } }); -// node_modules/undici/lib/web/fetch/headers.js -var require_headers = __commonJS({ - "node_modules/undici/lib/web/fetch/headers.js"(exports2, module2) { +// node_modules/undici/lib/util/cache.js +var require_cache = __commonJS({ + "node_modules/undici/lib/util/cache.js"(exports2, module2) { "use strict"; - var { kConstruct } = require_symbols(); - var { kEnumerableProperty } = require_util(); var { - iteratorMixin, - isValidHeaderName, - isValidHeaderValue - } = require_util2(); - var { webidl } = require_webidl(); - var assert = require("node:assert"); - var util3 = require("node:util"); - var kHeadersMap = /* @__PURE__ */ Symbol("headers map"); - var kHeadersSortedMap = /* @__PURE__ */ Symbol("headers map sorted"); - function isHTTPWhiteSpaceCharCode(code) { - return code === 10 || code === 13 || code === 9 || code === 32; + safeHTTPMethods, + pathHasQueryOrFragment, + hasSafeIterator, + isValidHTTPToken + } = require_util(); + var { serializePathWithQuery } = require_util(); + var MAX_DELTA_SECONDS = 2147483647; + var RESTRICTIVE_DIRECTIVE_NAMES = ["no-store", "private", "no-cache"]; + var kInvalidCacheControlDirectives = /* @__PURE__ */ Symbol("invalid cache-control directives"); + function trimOWS(value) { + return value.replace(/^[\t ]+|[\t ]+$/g, ""); } - function headerValueNormalize(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 arrayIncludes(array2, value) { + for (let i = 0; i < array2.length; i++) { + if (array2[i] === value) { + return true; + } + } + return false; } - function fill(headers, object2) { - if (Array.isArray(object2)) { - for (let i = 0; i < object2.length; ++i) { - const header = object2[i]; - if (header.length !== 2) { - throw webidl.errors.exception({ - header: "Headers constructor", - message: `expected name/value pair to be length 2, found ${header.length}.` - }); - } - appendHeader(headers, header[0], header[1]); + function trimOWSStart(value) { + return value.replace(/^[\t ]+/, ""); + } + function trimOWSEnd(value) { + return value.replace(/[\t ]+$/, ""); + } + function findUnescapedQuote(value, start) { + let escaped = false; + for (let i = start; i < value.length; i++) { + if (escaped) { + escaped = false; + } else if (value[i] === "\\") { + escaped = true; + } else if (value[i] === '"') { + return i; } - } else if (typeof object2 === "object" && object2 !== null) { - const keys = Object.keys(object2); - for (let i = 0; i < keys.length; ++i) { - appendHeader(headers, keys[i], object2[keys[i]]); + } + return -1; + } + function splitCacheControlHeaderValue(value) { + const directives = []; + let start = 0; + let quoteStart = -1; + let inQuote = false; + let escaped = false; + for (let i = 0; i < value.length; i++) { + if (inQuote) { + if (escaped) { + escaped = false; + } else if (value[i] === "\\") { + escaped = true; + } else if (value[i] === '"') { + inQuote = false; + quoteStart = -1; + } + } else if (value[i] === '"') { + inQuote = true; + quoteStart = i; + } else if (value[i] === ",") { + directives.push({ value: value.substring(start, i), fromMalformedQuote: false }); + start = i + 1; + } + } + if (!inQuote) { + directives.push({ value: value.substring(start), fromMalformedQuote: false }); + return directives; + } + const tail = value.substring(start); + const quoteOffset = quoteStart - start; + let tailStart = 0; + for (let i = 0; i < tail.length; i++) { + if (tail[i] === ",") { + directives.push({ + value: tail.substring(tailStart, i), + fromMalformedQuote: tailStart > quoteOffset + }); + tailStart = i + 1; } - } else { - throw webidl.errors.conversionFailed({ - prefix: "Headers constructor", - argument: "Argument 1", - types: ["sequence>", "record"] - }); } + directives.push({ + value: tail.substring(tailStart), + fromMalformedQuote: tailStart > quoteOffset + }); + return directives; } - function appendHeader(headers, name, value) { - value = headerValueNormalize(value); - 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" + function markInvalidCacheControlDirective(directives, key) { + let invalidDirectives = directives[kInvalidCacheControlDirectives]; + if (invalidDirectives === void 0) { + invalidDirectives = /* @__PURE__ */ new Set(); + Object.defineProperty(directives, kInvalidCacheControlDirectives, { + value: invalidDirectives }); } - if (getHeadersGuard(headers) === "immutable") { - throw new TypeError("immutable"); - } - return getHeadersList(headers).append(name, value, false); + invalidDirectives.add(key); } - function compareHeaderName(a, b) { - return a[0] < b[0] ? -1 : 1; + function hasInvalidCacheControlDirective(directives, key) { + return directives[kInvalidCacheControlDirectives]?.has(key) === true; } - var HeadersList = class _HeadersList { - /** @type {[string, string][]|null} */ - cookies = null; - constructor(init2) { - if (init2 instanceof _HeadersList) { - this[kHeadersMap] = new Map(init2[kHeadersMap]); - this[kHeadersSortedMap] = init2[kHeadersSortedMap]; - this.cookies = init2.cookies === null ? null : [...init2.cookies]; + function getMalformedRestrictiveDirectiveName(key) { + for (const directiveName of RESTRICTIVE_DIRECTIVE_NAMES) { + if (key.startsWith(directiveName) && key.length > directiveName.length && !isValidHTTPToken(key[directiveName.length])) { + return directiveName; + } + } + let tokenOnlyKey = ""; + let hasInvalidTokenChar = false; + for (let i = 0; i < key.length; i++) { + if (isValidHTTPToken(key[i])) { + tokenOnlyKey += key[i]; } else { - this[kHeadersMap] = new Map(init2); - this[kHeadersSortedMap] = null; + hasInvalidTokenChar = true; } } - /** - * @see https://fetch.spec.whatwg.org/#header-list-contains - * @param {string} name - * @param {boolean} isLowerCase - */ - contains(name, isLowerCase) { - return this[kHeadersMap].has(isLowerCase ? name : name.toLowerCase()); + if (hasInvalidTokenChar && arrayIncludes(RESTRICTIVE_DIRECTIVE_NAMES, tokenOnlyKey)) { + return tokenOnlyKey; } - clear() { - this[kHeadersMap].clear(); - this[kHeadersSortedMap] = null; - this.cookies = null; + } + function makeCacheKey(opts) { + if (!opts.origin) { + throw new Error("opts.origin is undefined"); } - /** - * @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; - const lowercaseName = isLowerCase ? name : name.toLowerCase(); - const exists = this[kHeadersMap].get(lowercaseName); - if (exists) { - const delimiter = lowercaseName === "cookie" ? "; " : ", "; - this[kHeadersMap].set(lowercaseName, { - name: exists.name, - value: `${exists.value}${delimiter}${value}` - }); + let fullPath = opts.path || "/"; + if (opts.query && !pathHasQueryOrFragment(fullPath)) { + fullPath = serializePathWithQuery(fullPath, opts.query); + } + return { + origin: opts.origin.toString(), + method: opts.method, + path: fullPath, + headers: opts.headers + }; + } + function appendHeader(headers, key, val) { + const headerName = key.toLowerCase(); + const current = headers[headerName]; + const values = Array.isArray(val) ? val : [val]; + if (current === void 0) { + headers[headerName] = Array.isArray(val) ? val.slice() : val; + } else if (Array.isArray(current)) { + current.push(...values); + } else { + headers[headerName] = [current, ...values]; + } + } + function normalizeHeaders(opts) { + let headers; + if (opts.headers == null) { + headers = {}; + } else if (typeof opts.headers === "object") { + headers = {}; + if (hasSafeIterator(opts.headers)) { + for (const x of opts.headers) { + if (!Array.isArray(x)) { + throw new Error("opts.headers is not a valid header map"); + } + const [key, val] = x; + if (typeof key !== "string" || typeof val !== "string") { + throw new Error("opts.headers is not a valid header map"); + } + appendHeader(headers, key, val); + } } else { - this[kHeadersMap].set(lowercaseName, { name, value }); - } - if (lowercaseName === "set-cookie") { - (this.cookies ??= []).push(value); + for (const key of Object.keys(opts.headers)) { + appendHeader(headers, key, opts.headers[key]); + } } + } else { + throw new Error("opts.headers is not an object"); } - /** - * @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]; - } - this[kHeadersMap].set(lowercaseName, { name, value }); + return headers; + } + function assertCacheKey(key) { + if (typeof key !== "object") { + throw new TypeError(`expected key to be object, got ${typeof key}`); } - /** - * @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; + for (const property of ["origin", "method", "path"]) { + if (typeof key[property] !== "string") { + throw new TypeError(`expected key.${property} to be string, got ${typeof key[property]}`); } - 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) { - return this[kHeadersMap].get(isLowerCase ? name : name.toLowerCase())?.value ?? null; + if (key.headers !== void 0 && typeof key.headers !== "object") { + throw new TypeError(`expected headers to be object, got ${typeof key}`); } - *[Symbol.iterator]() { - for (const { 0: name, 1: { value } } of this[kHeadersMap]) { - yield [name, value]; - } + } + function assertCacheValue(value) { + if (typeof value !== "object") { + throw new TypeError(`expected value to be object, got ${typeof value}`); } - get entries() { - const headers = {}; - if (this[kHeadersMap].size !== 0) { - for (const { name, value } of this[kHeadersMap].values()) { - headers[name] = value; - } + for (const property of ["statusCode", "cachedAt", "staleAt", "deleteAt"]) { + if (typeof value[property] !== "number") { + throw new TypeError(`expected value.${property} to be number, got ${typeof value[property]}`); } - return headers; } - rawValues() { - return this[kHeadersMap].values(); + if (typeof value.statusMessage !== "string") { + throw new TypeError(`expected value.statusMessage to be string, got ${typeof value.statusMessage}`); } - 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]); + if (value.headers != null && typeof value.headers !== "object") { + throw new TypeError(`expected value.rawHeaders to be object, got ${typeof value.headers}`); + } + if (value.vary !== void 0 && typeof value.vary !== "object") { + throw new TypeError(`expected value.vary to be object, got ${typeof value.vary}`); + } + if (value.etag !== void 0 && typeof value.etag !== "string") { + throw new TypeError(`expected value.etag to be string, got ${typeof value.etag}`); + } + } + function parseCacheControlHeader(header) { + const output = {}; + const invalidNumericDirectives = /* @__PURE__ */ new Set(); + const invalidNoArgumentDirectives = /* @__PURE__ */ new Set(); + const directives = splitCacheControlHeaderValue(Array.isArray(header) ? header.join(",") : header); + for (let i = 0; i < directives.length; i++) { + const directiveRecord = directives[i]; + const directive = directiveRecord.value.toLowerCase(); + const fromMalformedQuote = directiveRecord.fromMalformedQuote; + const keyValueDelimiter = directive.indexOf("="); + let key; + let value; + let keyHasTrailingWhitespace = false; + let valueHasLeadingWhitespace = false; + if (keyValueDelimiter !== -1) { + const rawKey = directive.substring(0, keyValueDelimiter); + const rawValue = directive.substring(keyValueDelimiter + 1); + keyHasTrailingWhitespace = trimOWSEnd(rawKey) !== rawKey; + valueHasLeadingWhitespace = trimOWSStart(rawValue) !== rawValue; + key = trimOWS(rawKey); + value = trimOWSStart(rawValue); + } else { + key = trimOWS(directive); + } + const malformedRestrictiveDirectiveName = getMalformedRestrictiveDirectiveName(key); + if (malformedRestrictiveDirectiveName !== void 0) { + output[malformedRestrictiveDirectiveName] = true; + continue; + } + switch (key) { + case "min-fresh": + case "max-stale": + case "max-age": + case "s-maxage": + case "stale-while-revalidate": + case "stale-if-error": { + if (fromMalformedQuote || invalidNumericDirectives.has(key)) { + continue; + } + if (value === void 0 || keyHasTrailingWhitespace || valueHasLeadingWhitespace) { + delete output[key]; + invalidNumericDirectives.add(key); + markInvalidCacheControlDirective(output, key); + continue; + } + if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') { + value = value.substring(1, value.length - 1); + } + if (!/^[0-9]+$/.test(value)) { + delete output[key]; + invalidNumericDirectives.add(key); + markInvalidCacheControlDirective(output, key); + continue; + } + const parsedValue = Math.min(parseInt(value, 10), MAX_DELTA_SECONDS); + if (key === "min-fresh") { + if (!(key in output) || output[key] < parsedValue) { + output[key] = parsedValue; } - } else { - headers.push([name, value]); + } else if (!(key in output) || output[key] > parsedValue) { + output[key] = parsedValue; } + break; } - } - return headers; - } - // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set - toSortedArray() { - const size = this[kHeadersMap].size; - const array2 = new Array(size); - if (size <= 32) { - if (size === 0) { - return array2; - } - const iterator2 = this[kHeadersMap][Symbol.iterator](); - const firstValue = iterator2.next().value; - array2[0] = [firstValue[0], firstValue[1].value]; - assert(firstValue[1].value !== null); - for (let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value; i < size; ++i) { - value = iterator2.next().value; - x = array2[i] = [value[0], value[1].value]; - assert(x[1] !== null); - left = 0; - right = i; - while (left < right) { - pivot = left + (right - left >> 1); - if (array2[pivot][0] <= x[0]) { - left = pivot + 1; - } else { - right = pivot; - } + case "private": + case "no-cache": { + if (fromMalformedQuote) { + output[key] = true; + break; } - if (i !== pivot) { - j = i; - while (j > left) { - array2[j] = array2[--j]; + if (value !== void 0 && value.length === 0) { + output[key] = true; + break; + } + if (value) { + if (value[0] === '"') { + value = trimOWSEnd(value); + let fieldList = ""; + let lastQuotedPart = i; + let foundEndingQuote = false; + const closingQuote = findUnescapedQuote(value, 1); + if (closingQuote !== -1) { + fieldList = value.substring(1, closingQuote); + foundEndingQuote = true; + } else { + const fieldListParts = [value.substring(1)]; + for (let j = i + 1; j < directives.length; j++) { + const nextPart = trimOWS(directives[j].value); + const closingQuote2 = findUnescapedQuote(nextPart, 0); + lastQuotedPart = j; + if (closingQuote2 !== -1) { + fieldListParts.push(nextPart.substring(0, closingQuote2)); + foundEndingQuote = true; + break; + } + fieldListParts.push(nextPart); + } + fieldList = fieldListParts.join(","); + } + if (!foundEndingQuote) { + output[key] = true; + break; + } + i = lastQuotedPart; + const headers = fieldList.split(","); + let validFieldNames = true; + for (let j = 0; j < headers.length; j++) { + headers[j] = trimOWS(headers[j]); + if (!isValidHTTPToken(headers[j])) { + validFieldNames = false; + } + } + if (!validFieldNames) { + output[key] = true; + } else if (output[key] !== true) { + if (key in output) { + output[key] = output[key].concat(headers); + } else { + output[key] = headers; + } + } + } else { + const fieldName = trimOWS(value); + if (!isValidHTTPToken(fieldName)) { + output[key] = true; + } else if (output[key] !== true) { + if (key in output) { + output[key] = output[key].concat(fieldName); + } else { + output[key] = [fieldName]; + } + } } - array2[left] = x; + break; } } - if (!iterator2.next().done) { - throw new TypeError("Unreachable"); - } - return array2; - } else { - let i = 0; - for (const { 0: name, 1: { value } } of this[kHeadersMap]) { - array2[i++] = [name, value]; - assert(value !== null); - } - return array2.sort(compareHeaderName); + // eslint-disable-next-line no-fallthrough + case "public": + case "must-revalidate": + case "proxy-revalidate": + case "immutable": + case "no-transform": + case "must-understand": + case "only-if-cached": + if (fromMalformedQuote || invalidNoArgumentDirectives.has(key)) { + continue; + } + if (value !== void 0) { + delete output[key]; + invalidNoArgumentDirectives.add(key); + continue; + } + output[key] = true; + break; + case "no-store": + output[key] = true; + break; + default: + continue; } } - }; - var Headers = class _Headers { - #guard; - #headersList; - constructor(init2 = void 0) { - webidl.util.markAsUncloneable(this); - if (init2 === kConstruct) { - return; + return output; + } + function splitVaryHeader(varyHeader) { + const values = Array.isArray(varyHeader) ? varyHeader : [varyHeader]; + const output = []; + for (let i = 0; i < values.length; i++) { + const parts = values[i].split(","); + for (let j = 0; j < parts.length; j++) { + output.push(parts[j]); } - this.#headersList = new HeadersList(); - this.#guard = "none"; - if (init2 !== void 0) { - init2 = webidl.converters.HeadersInit(init2, "Headers contructor", "init"); - fill(this, init2); + } + return output; + } + function hasVaryStar(varyHeader) { + const values = splitVaryHeader(varyHeader); + for (let i = 0; i < values.length; i++) { + if (trimOWS(values[i]).indexOf("*") !== -1) { + return true; } } - // 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); + return false; + } + function parseVaryHeader(varyHeader, headers) { + if (hasVaryStar(varyHeader)) { + return headers; } - // 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"); - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix: "Headers.delete", - value: name, - type: "header name" - }); - } - if (this.#guard === "immutable") { - throw new TypeError("immutable"); + const output = ( + /** @type {Record} */ + {} + ); + const varyingHeaders = splitVaryHeader(varyHeader); + for (const header of varyingHeaders) { + const trimmedHeader = trimOWS(header).toLowerCase(); + if (trimmedHeader.length === 0) { + continue; } - if (!this.#headersList.contains(name, false)) { - return; + if (!isValidHTTPToken(trimmedHeader)) { + return void 0; } - this.#headersList.delete(name, false); + const headerValue = headers[trimmedHeader]; + output[trimmedHeader] = Array.isArray(headerValue) ? headerValue.slice() : headerValue ?? null; } - // 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"); - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix, - value: name, - type: "header name" - }); - } - return this.#headersList.get(name, false); + return output; + } + function isInvalidOrWildcardVaryHeader(varyHeader) { + return hasVaryStar(varyHeader) || parseVaryHeader(varyHeader, {}) === void 0; + } + function isEtagUsable(etag) { + if (etag.length <= 2) { + return 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"); - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix, - value: name, - type: "header name" - }); - } - return this.#headersList.contains(name, false); + if (etag[0] === '"' && etag[etag.length - 1] === '"') { + return !(etag[1] === '"' || etag.startsWith('"W/')); } - // 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"); - value = headerValueNormalize(value); - 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" - }); + if (etag.startsWith('W/"') && etag[etag.length - 1] === '"') { + return etag.length !== 4; + } + return false; + } + function assertCacheStore(store, name = "CacheStore") { + if (typeof store !== "object" || store === null) { + throw new TypeError(`expected type of ${name} to be a CacheStore, got ${store === null ? "null" : typeof store}`); + } + for (const fn of ["get", "createWriteStream", "delete"]) { + if (typeof store[fn] !== "function") { + throw new TypeError(`${name} needs to have a \`${fn}()\` function`); } - if (this.#guard === "immutable") { - throw new TypeError("immutable"); + } + } + function assertCacheMethods(methods, name = "CacheMethods") { + if (!Array.isArray(methods)) { + throw new TypeError(`expected type of ${name} needs to be an array, got ${methods === null ? "null" : typeof methods}`); + } + if (methods.length === 0) { + throw new TypeError(`${name} needs to have at least one method`); + } + for (const method of methods) { + if (!arrayIncludes(safeHTTPMethods, method)) { + throw new TypeError(`element of ${name}-array needs to be one of following values: ${safeHTTPMethods.join(", ")}, got ${method}`); } - this.#headersList.set(name, value, false); } - // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie - getSetCookie() { - webidl.brandCheck(this, _Headers); - const list = this.#headersList.cookies; - if (list) { - return [...list]; + } + function makeDeduplicationKey(cacheKey3, excludeHeaders) { + const headers = {}; + if (cacheKey3.headers) { + const sortedHeaders = Object.keys(cacheKey3.headers).sort(); + for (const header of sortedHeaders) { + if (excludeHeaders?.has(header.toLowerCase())) { + continue; + } + headers[header] = cacheKey3.headers[header]; } - return []; } - // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine - get [kHeadersSortedMap]() { - if (this.#headersList[kHeadersSortedMap]) { - return this.#headersList[kHeadersSortedMap]; + return JSON.stringify([cacheKey3.origin, cacheKey3.method, cacheKey3.path, headers]); + } + module2.exports = { + makeCacheKey, + normalizeHeaders, + assertCacheKey, + assertCacheValue, + parseCacheControlHeader, + hasInvalidCacheControlDirective, + parseVaryHeader, + hasVaryStar, + isInvalidOrWildcardVaryHeader, + isEtagUsable, + assertCacheMethods, + assertCacheStore, + makeDeduplicationKey + }; + } +}); + +// node_modules/undici/lib/util/date.js +var require_date = __commonJS({ + "node_modules/undici/lib/util/date.js"(exports2, module2) { + "use strict"; + function parseHttpDate(date) { + switch (date[3]) { + case ",": + return parseImfDate(date); + case " ": + return parseAscTimeDate(date); + default: + return parseRfc850Date(date); + } + } + function makeDate(year, monthIdx, day, hour, minute, second, weekday) { + const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second)); + if (year >= 0 && year <= 99) { + result.setUTCFullYear(year); + } + return result.getUTCFullYear() === year && result.getUTCMonth() === monthIdx && result.getUTCDate() === day && result.getUTCHours() === hour && result.getUTCMinutes() === minute && result.getUTCSeconds() === second && result.getUTCDay() === weekday ? result : void 0; + } + function parseImfDate(date) { + if (date.length !== 29 || date[4] !== " " || date[7] !== " " || date[11] !== " " || date[16] !== " " || date[19] !== ":" || date[22] !== ":" || date[25] !== " " || date[26] !== "G" || date[27] !== "M" || date[28] !== "T") { + return void 0; + } + let weekday = -1; + if (date[0] === "S" && date[1] === "u" && date[2] === "n") { + weekday = 0; + } else if (date[0] === "M" && date[1] === "o" && date[2] === "n") { + weekday = 1; + } else if (date[0] === "T" && date[1] === "u" && date[2] === "e") { + weekday = 2; + } else if (date[0] === "W" && date[1] === "e" && date[2] === "d") { + weekday = 3; + } else if (date[0] === "T" && date[1] === "h" && date[2] === "u") { + weekday = 4; + } else if (date[0] === "F" && date[1] === "r" && date[2] === "i") { + weekday = 5; + } else if (date[0] === "S" && date[1] === "a" && date[2] === "t") { + weekday = 6; + } else { + return void 0; + } + let day = 0; + if (date[5] === "0") { + const code = date.charCodeAt(6); + if (code < 49 || code > 57) { + return void 0; } - const headers = []; - const names = this.#headersList.toSortedArray(); - const cookies = this.#headersList.cookies; - if (cookies === null || cookies.length === 1) { - return this.#headersList[kHeadersSortedMap] = names; + day = code - 48; + } else { + const code1 = date.charCodeAt(5); + if (code1 < 49 || code1 > 51) { + return void 0; } - for (let i = 0; i < names.length; ++i) { - const { 0: name, 1: value } = names[i]; - if (name === "set-cookie") { - for (let j = 0; j < cookies.length; ++j) { - headers.push([name, cookies[j]]); - } + const code2 = date.charCodeAt(6); + if (code2 < 48 || code2 > 57) { + return void 0; + } + day = (code1 - 48) * 10 + (code2 - 48); + } + let monthIdx = -1; + if (date[8] === "J" && date[9] === "a" && date[10] === "n") { + monthIdx = 0; + } else if (date[8] === "F" && date[9] === "e" && date[10] === "b") { + monthIdx = 1; + } else if (date[8] === "M" && date[9] === "a") { + if (date[10] === "r") { + monthIdx = 2; + } else if (date[10] === "y") { + monthIdx = 4; + } else { + return void 0; + } + } else if (date[8] === "J") { + if (date[9] === "a" && date[10] === "n") { + monthIdx = 0; + } else if (date[9] === "u") { + if (date[10] === "n") { + monthIdx = 5; + } else if (date[10] === "l") { + monthIdx = 6; } else { - headers.push([name, value]); + return void 0; } + } else { + return void 0; + } + } else if (date[8] === "A") { + if (date[9] === "p" && date[10] === "r") { + monthIdx = 3; + } else if (date[9] === "u" && date[10] === "g") { + monthIdx = 7; + } else { + return void 0; } - return this.#headersList[kHeadersSortedMap] = headers; + } else if (date[8] === "S" && date[9] === "e" && date[10] === "p") { + monthIdx = 8; + } else if (date[8] === "O" && date[9] === "c" && date[10] === "t") { + monthIdx = 9; + } else if (date[8] === "N" && date[9] === "o" && date[10] === "v") { + monthIdx = 10; + } else if (date[8] === "D" && date[9] === "e" && date[10] === "c") { + monthIdx = 11; + } else { + return void 0; } - [util3.inspect.custom](depth, options) { - options.depth ??= depth; - return `Headers ${util3.formatWithOptions(options, this.#headersList.entries)}`; + const yearDigit1 = date.charCodeAt(12); + if (yearDigit1 < 48 || yearDigit1 > 57) { + return void 0; } - static getHeadersGuard(o) { - return o.#guard; + const yearDigit2 = date.charCodeAt(13); + if (yearDigit2 < 48 || yearDigit2 > 57) { + return void 0; } - static setHeadersGuard(o, guard) { - o.#guard = guard; + const yearDigit3 = date.charCodeAt(14); + if (yearDigit3 < 48 || yearDigit3 > 57) { + return void 0; } - static getHeadersList(o) { - return o.#headersList; + const yearDigit4 = date.charCodeAt(15); + if (yearDigit4 < 48 || yearDigit4 > 57) { + return void 0; } - static setHeadersList(o, list) { - o.#headersList = list; + const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48); + let hour = 0; + if (date[17] === "0") { + const code = date.charCodeAt(18); + if (code < 48 || code > 57) { + return void 0; + } + hour = code - 48; + } else { + const code1 = date.charCodeAt(17); + if (code1 < 48 || code1 > 50) { + return void 0; + } + const code2 = date.charCodeAt(18); + if (code2 < 48 || code2 > 57) { + return void 0; + } + if (code1 === 50 && code2 > 51) { + return void 0; + } + hour = (code1 - 48) * 10 + (code2 - 48); } - }; - var { 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 - }, - [util3.inspect.custom]: { - enumerable: false + let minute = 0; + if (date[20] === "0") { + const code = date.charCodeAt(21); + if (code < 48 || code > 57) { + return void 0; + } + minute = code - 48; + } else { + const code1 = date.charCodeAt(20); + if (code1 < 48 || code1 > 53) { + return void 0; + } + const code2 = date.charCodeAt(21); + if (code2 < 48 || code2 > 57) { + return void 0; + } + minute = (code1 - 48) * 10 + (code2 - 48); } - }); - webidl.converters.HeadersInit = function(V, prefix, argument) { - if (webidl.util.Type(V) === "Object") { - const iterator2 = Reflect.get(V, Symbol.iterator); - if (!util3.types.isProxy(V) && iterator2 === Headers.prototype.entries) { - try { - return getHeadersList(V).entriesList; - } catch { - } + let second = 0; + if (date[23] === "0") { + const code = date.charCodeAt(24); + if (code < 48 || code > 57) { + return void 0; } - if (typeof iterator2 === "function") { - return webidl.converters["sequence>"](V, prefix, argument, iterator2.bind(V)); + second = code - 48; + } else { + const code1 = date.charCodeAt(23); + if (code1 < 48 || code1 > 53) { + return void 0; } - return webidl.converters["record"](V, prefix, argument); + const code2 = date.charCodeAt(24); + if (code2 < 48 || code2 > 57) { + return void 0; + } + second = (code1 - 48) * 10 + (code2 - 48); } - throw webidl.errors.conversionFailed({ - prefix: "Headers constructor", - argument: "Argument 1", - types: ["sequence>", "record"] - }); - }; - module2.exports = { - fill, - // for test. - compareHeaderName, - Headers, - HeadersList, - getHeadersGuard, - setHeadersGuard, - setHeadersList, - getHeadersList - }; - } -}); - -// node_modules/undici/lib/web/fetch/response.js -var require_response = __commonJS({ - "node_modules/undici/lib/web/fetch/response.js"(exports2, module2) { - "use strict"; - var { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = require_headers(); - var { extractBody, cloneBody, mixinBody, hasFinalizationRegistry, streamRegistry, bodyUnusable } = require_body(); - var util3 = require_util(); - var nodeUtil = require("node:util"); - var { kEnumerableProperty } = util3; - var { - isValidReasonPhrase, - isCancelled, - isAborted, - isBlobLike, - serializeJavascriptValueToJSONString, - isErrorLike, - isomorphicEncode, - environmentSettingsObject: relevantRealm - } = require_util2(); - var { - redirectStatusSet, - nullBodyStatus - } = require_constants3(); - var { kState, kHeaders } = require_symbols2(); - var { webidl } = require_webidl(); - var { FormData: FormData2 } = require_formdata(); - var { URLSerializer } = require_data_url(); - var { kConstruct } = require_symbols(); - var assert = require("node:assert"); - var { types: types2 } = require("node:util"); - var textEncoder = new TextEncoder("utf-8"); - var Response = class _Response { - // Creates network error Response. - static error() { - const responseObject = fromInnerResponse(makeNetworkError(), "immutable"); - return responseObject; + return makeDate(year, monthIdx, day, hour, minute, second, weekday); + } + function parseAscTimeDate(date) { + if (date.length !== 24 || date[7] !== " " || date[10] !== " " || date[19] !== " ") { + return void 0; } - // https://fetch.spec.whatwg.org/#dom-response-json - static json(data, init2 = {}) { - webidl.argumentLengthCheck(arguments, 1, "Response.json"); - if (init2 !== null) { - init2 = webidl.converters.ResponseInit(init2); - } - const bytes = textEncoder.encode( - serializeJavascriptValueToJSONString(data) - ); - const body = extractBody(bytes); - const responseObject = fromInnerResponse(makeResponse({}), "response"); - initializeResponse(responseObject, init2, { body: body[0], type: "application/json" }); - return responseObject; + let weekday = -1; + if (date[0] === "S" && date[1] === "u" && date[2] === "n") { + weekday = 0; + } else if (date[0] === "M" && date[1] === "o" && date[2] === "n") { + weekday = 1; + } else if (date[0] === "T" && date[1] === "u" && date[2] === "e") { + weekday = 2; + } else if (date[0] === "W" && date[1] === "e" && date[2] === "d") { + weekday = 3; + } else if (date[0] === "T" && date[1] === "h" && date[2] === "u") { + weekday = 4; + } else if (date[0] === "F" && date[1] === "r" && date[2] === "i") { + weekday = 5; + } else if (date[0] === "S" && date[1] === "a" && date[2] === "t") { + weekday = 6; + } else { + return void 0; } - // Creates a redirect Response that redirects to url with status status. - static redirect(url2, status = 302) { - webidl.argumentLengthCheck(arguments, 1, "Response.redirect"); - url2 = webidl.converters.USVString(url2); - status = webidl.converters["unsigned short"](status); - let parsedURL; - try { - parsedURL = new URL(url2, relevantRealm.settingsObject.baseUrl); - } catch (err) { - throw new TypeError(`Failed to parse URL from ${url2}`, { cause: err }); + let monthIdx = -1; + if (date[4] === "J" && date[5] === "a" && date[6] === "n") { + monthIdx = 0; + } else if (date[4] === "F" && date[5] === "e" && date[6] === "b") { + monthIdx = 1; + } else if (date[4] === "M" && date[5] === "a") { + if (date[6] === "r") { + monthIdx = 2; + } else if (date[6] === "y") { + monthIdx = 4; + } else { + return void 0; } - if (!redirectStatusSet.has(status)) { - throw new RangeError(`Invalid status code ${status}`); + } else if (date[4] === "J") { + if (date[5] === "a" && date[6] === "n") { + monthIdx = 0; + } else if (date[5] === "u") { + if (date[6] === "n") { + monthIdx = 5; + } else if (date[6] === "l") { + monthIdx = 6; + } else { + return void 0; + } + } else { + return void 0; } - const responseObject = fromInnerResponse(makeResponse({}), "immutable"); - responseObject[kState].status = status; - const value = isomorphicEncode(URLSerializer(parsedURL)); - responseObject[kState].headersList.append("location", value, true); - return responseObject; + } else if (date[4] === "A") { + if (date[5] === "p" && date[6] === "r") { + monthIdx = 3; + } else if (date[5] === "u" && date[6] === "g") { + monthIdx = 7; + } else { + return void 0; + } + } else if (date[4] === "S" && date[5] === "e" && date[6] === "p") { + monthIdx = 8; + } else if (date[4] === "O" && date[5] === "c" && date[6] === "t") { + monthIdx = 9; + } else if (date[4] === "N" && date[5] === "o" && date[6] === "v") { + monthIdx = 10; + } else if (date[4] === "D" && date[5] === "e" && date[6] === "c") { + monthIdx = 11; + } else { + return void 0; } - // https://fetch.spec.whatwg.org/#dom-response - constructor(body = null, init2 = {}) { - webidl.util.markAsUncloneable(this); - if (body === kConstruct) { - return; + let day = 0; + if (date[8] === " ") { + const code = date.charCodeAt(9); + if (code < 49 || code > 57) { + return void 0; } - if (body !== null) { - body = webidl.converters.BodyInit(body); + day = code - 48; + } else { + const code1 = date.charCodeAt(8); + if (code1 < 49 || code1 > 51) { + return void 0; } - init2 = webidl.converters.ResponseInit(init2); - this[kState] = makeResponse({}); - this[kHeaders] = new Headers(kConstruct); - setHeadersGuard(this[kHeaders], "response"); - setHeadersList(this[kHeaders], this[kState].headersList); - let bodyWithType = null; - if (body != null) { - const [extractedBody, type] = extractBody(body); - bodyWithType = { body: extractedBody, type }; + const code2 = date.charCodeAt(9); + if (code2 < 48 || code2 > 57) { + return void 0; } - initializeResponse(this, init2, bodyWithType); + day = (code1 - 48) * 10 + (code2 - 48); } - // Returns response’s type, e.g., "cors". - get type() { - webidl.brandCheck(this, _Response); - return this[kState].type; + let hour = 0; + if (date[11] === "0") { + const code = date.charCodeAt(12); + if (code < 48 || code > 57) { + return void 0; + } + hour = code - 48; + } else { + const code1 = date.charCodeAt(11); + if (code1 < 48 || code1 > 50) { + return void 0; + } + const code2 = date.charCodeAt(12); + if (code2 < 48 || code2 > 57) { + return void 0; + } + if (code1 === 50 && code2 > 51) { + return void 0; + } + hour = (code1 - 48) * 10 + (code2 - 48); } - // Returns response’s URL, if it has one; otherwise the empty string. - get url() { - webidl.brandCheck(this, _Response); - const urlList = this[kState].urlList; - const url2 = urlList[urlList.length - 1] ?? null; - if (url2 === null) { - return ""; + let minute = 0; + if (date[14] === "0") { + const code = date.charCodeAt(15); + if (code < 48 || code > 57) { + return void 0; } - return URLSerializer(url2, true); + minute = code - 48; + } else { + const code1 = date.charCodeAt(14); + if (code1 < 48 || code1 > 53) { + return void 0; + } + const code2 = date.charCodeAt(15); + if (code2 < 48 || code2 > 57) { + return void 0; + } + minute = (code1 - 48) * 10 + (code2 - 48); } - // Returns whether response was obtained through a redirect. - get redirected() { - webidl.brandCheck(this, _Response); - return this[kState].urlList.length > 1; + let second = 0; + if (date[17] === "0") { + const code = date.charCodeAt(18); + if (code < 48 || code > 57) { + return void 0; + } + second = code - 48; + } else { + const code1 = date.charCodeAt(17); + if (code1 < 48 || code1 > 53) { + return void 0; + } + const code2 = date.charCodeAt(18); + if (code2 < 48 || code2 > 57) { + return void 0; + } + second = (code1 - 48) * 10 + (code2 - 48); } - // Returns response’s status. - get status() { - webidl.brandCheck(this, _Response); - return this[kState].status; + const yearDigit1 = date.charCodeAt(20); + if (yearDigit1 < 48 || yearDigit1 > 57) { + return void 0; } - // Returns whether response’s status is an ok status. - get ok() { - webidl.brandCheck(this, _Response); - return this[kState].status >= 200 && this[kState].status <= 299; + const yearDigit2 = date.charCodeAt(21); + if (yearDigit2 < 48 || yearDigit2 > 57) { + return void 0; } - // Returns response’s status message. - get statusText() { - webidl.brandCheck(this, _Response); - return this[kState].statusText; + const yearDigit3 = date.charCodeAt(22); + if (yearDigit3 < 48 || yearDigit3 > 57) { + return void 0; } - // Returns response’s headers as Headers. - get headers() { - webidl.brandCheck(this, _Response); - return this[kHeaders]; + const yearDigit4 = date.charCodeAt(23); + if (yearDigit4 < 48 || yearDigit4 > 57) { + return void 0; } - get body() { - webidl.brandCheck(this, _Response); - return this[kState].body ? this[kState].body.stream : null; + const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48); + return makeDate(year, monthIdx, day, hour, minute, second, weekday); + } + function parseRfc850Date(date) { + let commaIndex = -1; + let weekday = -1; + if (date[0] === "S") { + if (date[1] === "u" && date[2] === "n" && date[3] === "d" && date[4] === "a" && date[5] === "y") { + weekday = 0; + commaIndex = 6; + } else if (date[1] === "a" && date[2] === "t" && date[3] === "u" && date[4] === "r" && date[5] === "d" && date[6] === "a" && date[7] === "y") { + weekday = 6; + commaIndex = 8; + } + } else if (date[0] === "M" && date[1] === "o" && date[2] === "n" && date[3] === "d" && date[4] === "a" && date[5] === "y") { + weekday = 1; + commaIndex = 6; + } else if (date[0] === "T") { + if (date[1] === "u" && date[2] === "e" && date[3] === "s" && date[4] === "d" && date[5] === "a" && date[6] === "y") { + weekday = 2; + commaIndex = 7; + } else if (date[1] === "h" && date[2] === "u" && date[3] === "r" && date[4] === "s" && date[5] === "d" && date[6] === "a" && date[7] === "y") { + weekday = 4; + commaIndex = 8; + } + } else if (date[0] === "W" && date[1] === "e" && date[2] === "d" && date[3] === "n" && date[4] === "e" && date[5] === "s" && date[6] === "d" && date[7] === "a" && date[8] === "y") { + weekday = 3; + commaIndex = 9; + } else if (date[0] === "F" && date[1] === "r" && date[2] === "i" && date[3] === "d" && date[4] === "a" && date[5] === "y") { + weekday = 5; + commaIndex = 6; + } else { + return void 0; } - get bodyUsed() { - webidl.brandCheck(this, _Response); - return !!this[kState].body && util3.isDisturbed(this[kState].body.stream); + if (date[commaIndex] !== "," || date.length - commaIndex - 1 !== 23 || date[commaIndex + 1] !== " " || date[commaIndex + 4] !== "-" || date[commaIndex + 8] !== "-" || date[commaIndex + 11] !== " " || date[commaIndex + 14] !== ":" || date[commaIndex + 17] !== ":" || date[commaIndex + 20] !== " " || date[commaIndex + 21] !== "G" || date[commaIndex + 22] !== "M" || date[commaIndex + 23] !== "T") { + return void 0; } - // Returns a clone of response. - clone() { - webidl.brandCheck(this, _Response); - if (bodyUnusable(this)) { - throw webidl.errors.exception({ - header: "Response.clone", - message: "Body has already been consumed." - }); + let day = 0; + if (date[commaIndex + 2] === "0") { + const code = date.charCodeAt(commaIndex + 3); + if (code < 49 || code > 57) { + return void 0; } - const clonedResponse = cloneResponse(this[kState]); - if (hasFinalizationRegistry && this[kState].body?.stream) { - streamRegistry.register(this, new WeakRef(this[kState].body.stream)); + day = code - 48; + } else { + const code1 = date.charCodeAt(commaIndex + 2); + if (code1 < 49 || code1 > 51) { + return void 0; } - return fromInnerResponse(clonedResponse, getHeadersGuard(this[kHeaders])); - } - [nodeUtil.inspect.custom](depth, options) { - if (options.depth === null) { - options.depth = 2; + const code2 = date.charCodeAt(commaIndex + 3); + if (code2 < 48 || code2 > 57) { + return void 0; } - 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)}`; + day = (code1 - 48) * 10 + (code2 - 48); + } + let monthIdx = -1; + if (date[commaIndex + 5] === "J" && date[commaIndex + 6] === "a" && date[commaIndex + 7] === "n") { + monthIdx = 0; + } else if (date[commaIndex + 5] === "F" && date[commaIndex + 6] === "e" && date[commaIndex + 7] === "b") { + monthIdx = 1; + } else if (date[commaIndex + 5] === "M" && date[commaIndex + 6] === "a" && date[commaIndex + 7] === "r") { + monthIdx = 2; + } else if (date[commaIndex + 5] === "A" && date[commaIndex + 6] === "p" && date[commaIndex + 7] === "r") { + monthIdx = 3; + } else if (date[commaIndex + 5] === "M" && date[commaIndex + 6] === "a" && date[commaIndex + 7] === "y") { + monthIdx = 4; + } else if (date[commaIndex + 5] === "J" && date[commaIndex + 6] === "u" && date[commaIndex + 7] === "n") { + monthIdx = 5; + } else if (date[commaIndex + 5] === "J" && date[commaIndex + 6] === "u" && date[commaIndex + 7] === "l") { + monthIdx = 6; + } else if (date[commaIndex + 5] === "A" && date[commaIndex + 6] === "u" && date[commaIndex + 7] === "g") { + monthIdx = 7; + } else if (date[commaIndex + 5] === "S" && date[commaIndex + 6] === "e" && date[commaIndex + 7] === "p") { + monthIdx = 8; + } else if (date[commaIndex + 5] === "O" && date[commaIndex + 6] === "c" && date[commaIndex + 7] === "t") { + monthIdx = 9; + } else if (date[commaIndex + 5] === "N" && date[commaIndex + 6] === "o" && date[commaIndex + 7] === "v") { + monthIdx = 10; + } else if (date[commaIndex + 5] === "D" && date[commaIndex + 6] === "e" && date[commaIndex + 7] === "c") { + monthIdx = 11; + } else { + return void 0; } - }; - 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 + const yearDigit1 = date.charCodeAt(commaIndex + 9); + if (yearDigit1 < 48 || yearDigit1 > 57) { + return void 0; } - }); - Object.defineProperties(Response, { - json: kEnumerableProperty, - redirect: kEnumerableProperty, - error: kEnumerableProperty - }); - function cloneResponse(response) { - if (response.internalResponse) { - return filterResponse( - cloneResponse(response.internalResponse), - response.type - ); + const yearDigit2 = date.charCodeAt(commaIndex + 10); + if (yearDigit2 < 48 || yearDigit2 > 57) { + return void 0; } - const newResponse = makeResponse({ ...response, body: null }); - if (response.body != null) { - newResponse.body = cloneBody(newResponse, response.body); + let year = (yearDigit1 - 48) * 10 + (yearDigit2 - 48); + year += year < 70 ? 2e3 : 1900; + let hour = 0; + if (date[commaIndex + 12] === "0") { + const code = date.charCodeAt(commaIndex + 13); + if (code < 48 || code > 57) { + return void 0; + } + hour = code - 48; + } else { + const code1 = date.charCodeAt(commaIndex + 12); + if (code1 < 48 || code1 > 50) { + return void 0; + } + const code2 = date.charCodeAt(commaIndex + 13); + if (code2 < 48 || code2 > 57) { + return void 0; + } + if (code1 === 50 && code2 > 51) { + return void 0; + } + hour = (code1 - 48) * 10 + (code2 - 48); } - return newResponse; + let minute = 0; + if (date[commaIndex + 15] === "0") { + const code = date.charCodeAt(commaIndex + 16); + if (code < 48 || code > 57) { + return void 0; + } + minute = code - 48; + } else { + const code1 = date.charCodeAt(commaIndex + 15); + if (code1 < 48 || code1 > 53) { + return void 0; + } + const code2 = date.charCodeAt(commaIndex + 16); + if (code2 < 48 || code2 > 57) { + return void 0; + } + minute = (code1 - 48) * 10 + (code2 - 48); + } + let second = 0; + if (date[commaIndex + 18] === "0") { + const code = date.charCodeAt(commaIndex + 19); + if (code < 48 || code > 57) { + return void 0; + } + second = code - 48; + } else { + const code1 = date.charCodeAt(commaIndex + 18); + if (code1 < 48 || code1 > 53) { + return void 0; + } + const code2 = date.charCodeAt(commaIndex + 19); + if (code2 < 48 || code2 > 57) { + return void 0; + } + second = (code1 - 48) * 10 + (code2 - 48); + } + return makeDate(year, monthIdx, day, hour, minute, second, weekday); } - function makeResponse(init2) { - return { - aborted: false, - rangeRequested: false, - timingAllowPassed: false, - requestIncludesCredentials: false, - type: "default", - status: 200, - timingInfo: null, - cacheState: "", - statusText: "", - ...init2, - headersList: init2?.headersList ? new HeadersList(init2?.headersList) : new HeadersList(), - urlList: init2?.urlList ? [...init2.urlList] : [] - }; + module2.exports = { + parseHttpDate + }; + } +}); + +// node_modules/undici/lib/handler/cache-handler.js +var require_cache_handler = __commonJS({ + "node_modules/undici/lib/handler/cache-handler.js"(exports2, module2) { + "use strict"; + var util4 = require_util(); + var { kRedirectCacheControl } = require_symbols(); + var { + parseCacheControlHeader, + hasInvalidCacheControlDirective, + parseVaryHeader, + hasVaryStar, + isInvalidOrWildcardVaryHeader, + isEtagUsable + } = require_cache(); + var { parseHttpDate } = require_date(); + function noop3() { } - 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" - }); + function sameOrigin(a, b) { + try { + return new URL(String(a)).origin === new URL(String(b)).origin; + } catch { + return String(a) === String(b); + } } - function isNetworkError(response) { - return ( - // A network error is a response whose type is "error", - response.type === "error" && // status is 0 - response.status === 0 - ); + var HEURISTICALLY_CACHEABLE_STATUS_CODES = [ + 200, + 203, + 204, + 206, + 300, + 301, + 308, + 404, + 405, + 410, + 414, + 501 + ]; + var NOT_UNDERSTOOD_STATUS_CODES = [ + 206 + ]; + var MAX_RESPONSE_AGE = 2147483647e3; + function trimOWS(value) { + return value.replace(/^[\t ]+|[\t ]+$/g, ""); } - 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; + function arrayIncludes(array2, value) { + for (let i = 0; i < array2.length; i++) { + if (array2[i] === value) { return true; } - }); - } - function filterResponse(response, type) { - if (type === "basic") { - return makeFilteredResponse(response, { - type: "basic", - headersList: response.headersList - }); - } else if (type === "cors") { - return makeFilteredResponse(response, { - type: "cors", - headersList: response.headersList - }); - } else if (type === "opaque") { - return makeFilteredResponse(response, { - type: "opaque", - urlList: Object.freeze([]), - status: 0, - statusText: "", - body: null - }); - } else if (type === "opaqueredirect") { - return makeFilteredResponse(response, { - type: "opaqueredirect", - status: 0, - statusText: "", - headersList: [], - body: null - }); - } else { - assert(false); } + return false; } - function makeAppropriateNetworkError(fetchParams, err = null) { - assert(isCancelled(fetchParams)); - 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 })); - } - function initializeResponse(response, init2, body) { - if (init2.status !== null && (init2.status < 200 || init2.status > 599)) { - throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.'); - } - if ("statusText" in init2 && init2.statusText != null) { - if (!isValidReasonPhrase(String(init2.statusText))) { - throw new TypeError("Invalid statusText"); + function appendConnectionHeaderTokens(headersToRemove, connectionHeader) { + const values = Array.isArray(connectionHeader) ? connectionHeader : [connectionHeader]; + for (let i = 0; i < values.length; i++) { + const tokens = values[i].split(","); + for (let j = 0; j < tokens.length; j++) { + headersToRemove.push(trimOWS(tokens[j]).toLowerCase()); } } - if ("status" in init2 && init2.status != null) { - response[kState].status = init2.status; + } + function getSameOriginPath(cacheKey3, location) { + if (typeof location !== "string") { + return void 0; } - if ("statusText" in init2 && init2.statusText != null) { - response[kState].statusText = init2.statusText; + let originUrl; + let requestUrl; + let locationUrl; + try { + originUrl = new URL(cacheKey3.origin); + requestUrl = new URL(cacheKey3.path, originUrl); + locationUrl = new URL(location, requestUrl); + } catch { + return void 0; } - if ("headers" in init2 && init2.headers != null) { - fill(response[kHeaders], init2.headers); + if (locationUrl.origin !== originUrl.origin) { + return void 0; } - if (body) { - if (nullBodyStatus.includes(response.status)) { - throw webidl.errors.exception({ - header: "Response constructor", - message: `Invalid response status code ${response.status}` + return locationUrl.pathname + locationUrl.search; + } + function deleteCachedUri(store, cacheKey3, path30) { + deleteCachedValue(store, { + ...cacheKey3, + path: path30 + }); + for (let i = 0; i < util4.safeHTTPMethods.length; i++) { + const method = util4.safeHTTPMethods[i]; + if (method !== cacheKey3.method) { + deleteCachedValue(store, { + ...cacheKey3, + method, + path: path30 }); } - response[kState].body = body.body; - if (body.type != null && !response[kState].headersList.contains("content-type", true)) { - response[kState].headersList.append("content-type", body.type, true); - } } } - 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) { - streamRegistry.register(response, new WeakRef(innerResponse.body.stream)); + function deleteLocationTargets(store, cacheKey3, headerValue) { + if (headerValue === void 0) { + return; + } + const values = Array.isArray(headerValue) ? headerValue : [headerValue]; + for (let i = 0; i < values.length; i++) { + const path30 = getSameOriginPath(cacheKey3, values[i]); + if (path30 !== void 0) { + deleteCachedUri(store, cacheKey3, path30); + } } - return response; } - webidl.converters.ReadableStream = webidl.interfaceConverter( - ReadableStream - ); - webidl.converters.FormData = webidl.interfaceConverter( - FormData2 - ); - webidl.converters.URLSearchParams = webidl.interfaceConverter( - URLSearchParams - ); - webidl.converters.XMLHttpRequestBodyInit = function(V, prefix, name) { - if (typeof V === "string") { - return webidl.converters.USVString(V, prefix, name); + function invalidateUnsafeRequest(store, cacheKey3, resHeaders) { + deleteCachedUri(store, cacheKey3, cacheKey3.path); + deleteLocationTargets(store, cacheKey3, resHeaders.location); + deleteLocationTargets(store, cacheKey3, resHeaders["content-location"]); + } + var CacheHandler = class { + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey} + */ + #cacheKey; + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions['type']} + */ + #cacheType; + /** + * @type {number | undefined} + */ + #cacheByDefault; + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheStore} + */ + #store; + /** + * @type {import('../../types/dispatcher.d.ts').default.DispatchHandler} + */ + #handler; + /** + * @type {import('node:stream').Writable | undefined} + */ + #writeStream; + /** + * The URLs visited while following redirects, shared by reference from the + * redirect handler through the request context. Carries the suppressed hops' + * cache-control under {@link kRedirectCacheControl}. + * @type {URL[] | undefined} + */ + #history; + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} opts + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey + * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler + */ + constructor({ store, type, cacheByDefault }, cacheKey3, handler2) { + this.#store = store; + this.#cacheType = type; + this.#cacheByDefault = cacheByDefault; + this.#cacheKey = cacheKey3; + this.#handler = handler2; } - if (isBlobLike(V)) { - return webidl.converters.Blob(V, prefix, name, { strict: false }); + onRequestStart(controller, context5) { + this.#writeStream?.destroy(); + this.#writeStream = void 0; + this.#history = context5?.history; + this.#handler.onRequestStart?.(controller, context5); } - if (ArrayBuffer.isView(V) || types2.isArrayBuffer(V)) { - return webidl.converters.BufferSource(V, prefix, name); + onRequestUpgrade(controller, statusCode, headers, socket) { + this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket); } - if (util3.isFormDataLike(V)) { - return webidl.converters.FormData(V, prefix, name, { strict: false }); + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {number} statusCode + * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders + * @param {string} statusMessage + */ + onResponseStart(controller, statusCode, resHeaders, statusMessage) { + const downstreamOnHeaders = () => this.#handler.onResponseStart?.( + controller, + statusCode, + resHeaders, + statusMessage + ); + const handler2 = this; + if (!arrayIncludes(util4.safeHTTPMethods, this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) { + invalidateUnsafeRequest(this.#store, this.#cacheKey, resHeaders); + return downstreamOnHeaders(); + } + if (this.#history && this.#history.length > 0) { + const finalUrl = this.#history[this.#history.length - 1]; + if (!sameOrigin(finalUrl.origin, this.#cacheKey.origin)) { + return downstreamOnHeaders(); + } + } + const redirectCacheControl = this.#history?.[kRedirectCacheControl]; + if (redirectCacheControl) { + for (const hopCacheControl of redirectCacheControl) { + const hopDirectives = hopCacheControl ? parseCacheControlHeader(hopCacheControl) : {}; + if (hopDirectives["no-store"] === true || this.#cacheType === "shared" && hopDirectives.private === true) { + return downstreamOnHeaders(); + } + } + } + const cacheControlHeader = resHeaders["cache-control"]; + const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {}; + if (revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives)) { + deleteCachedValue(this.#store, this.#cacheKey); + return downstreamOnHeaders(); + } + const heuristicallyCacheable = resHeaders["last-modified"] && arrayIncludes(HEURISTICALLY_CACHEABLE_STATUS_CODES, statusCode); + if (!cacheControlHeader && !resHeaders["expires"] && !heuristicallyCacheable && !this.#cacheByDefault) { + if (statusCode === 304 && resHeaders.vary && isInvalidOrWildcardVaryHeader(resHeaders.vary)) { + deleteCachedValue(this.#store, this.#cacheKey); + } + return downstreamOnHeaders(); + } + if (!canCacheResponse(this.#cacheType, this.#cacheKey.method, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) { + if (statusCode === 304 && (cacheControlHeader || revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives))) { + deleteCachedValue(this.#store, this.#cacheKey); + } + return downstreamOnHeaders(); + } + const now = Date.now(); + const resAge = Object.hasOwn(resHeaders, "age") ? getAge(resHeaders.age) : void 0; + if (resAge !== void 0 && resAge >= MAX_RESPONSE_AGE) { + deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey); + return downstreamOnHeaders(); + } + const resDate = Object.hasOwn(resHeaders, "date") ? getDate2(resHeaders.date) : void 0; + if (resDate === null) { + deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey); + return downstreamOnHeaders(); + } + const apparentAge = resDate ? Math.max(0, now - resDate.getTime()) : 0; + const currentAge = Math.max(apparentAge, resAge ?? 0); + const staleAt = determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ?? this.#cacheByDefault; + if (staleAt === void 0 || currentAge >= staleAt) { + if (cacheControlHeader || staleAt !== void 0) { + deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey); + } + return downstreamOnHeaders(); + } + const baseTime = now - currentAge; + const absoluteStaleAt = staleAt + baseTime; + if (now >= absoluteStaleAt) { + deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey); + return downstreamOnHeaders(); + } + let varyDirectives; + if (this.#cacheKey.headers && resHeaders.vary) { + varyDirectives = parseVaryHeader(resHeaders.vary, this.#cacheKey.headers); + if (!varyDirectives) { + return downstreamOnHeaders(); + } + } + const cachedAt = baseTime; + const deleteAt = determineDeleteAt(baseTime, now, cacheControlDirectives, absoluteStaleAt); + const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives); + const value = { + statusCode, + statusMessage, + headers: strippedHeaders, + vary: varyDirectives, + cacheControlDirectives, + cachedAt, + staleAt: absoluteStaleAt, + deleteAt + }; + if (statusCode === 304) { + const handle304 = (cachedValue) => { + if (!cachedValue) { + return downstreamOnHeaders(); + } + value.statusCode = cachedValue.statusCode; + value.statusMessage = cachedValue.statusMessage; + value.etag = cachedValue.etag; + value.vary = varyDirectives ?? cachedValue.vary; + value.headers = { ...cachedValue.headers, ...strippedHeaders }; + downstreamOnHeaders(); + this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value); + if (!this.#writeStream || !cachedValue?.body) { + return; + } + if (typeof cachedValue.body.values === "function") { + const bodyIterator = cachedValue.body.values(); + const streamCachedBody = () => { + for (const chunk of bodyIterator) { + const full = this.#writeStream.write(chunk) === false; + this.#handler.onResponseData?.(controller, chunk); + if (full) { + break; + } + } + }; + this.#writeStream.on("error", function() { + handler2.#writeStream = void 0; + handler2.#store.delete(handler2.#cacheKey); + }).on("drain", () => { + streamCachedBody(); + }).on("close", function() { + if (handler2.#writeStream === this) { + handler2.#writeStream = void 0; + } + }); + streamCachedBody(); + } else if (typeof cachedValue.body.on === "function") { + cachedValue.body.on("data", (chunk) => { + this.#writeStream.write(chunk); + this.#handler.onResponseData?.(controller, chunk); + }).on("end", () => { + this.#writeStream.end(); + }).on("error", () => { + this.#writeStream = void 0; + this.#store.delete(this.#cacheKey); + }); + this.#writeStream.on("error", function() { + handler2.#writeStream = void 0; + handler2.#store.delete(handler2.#cacheKey); + }).on("close", function() { + if (handler2.#writeStream === this) { + handler2.#writeStream = void 0; + } + }); + } + }; + const result = this.#store.get(this.#cacheKey); + if (result && typeof result.then === "function") { + result.then(handle304); + } else { + handle304(result); + } + } else { + if (typeof resHeaders.etag === "string" && isEtagUsable(resHeaders.etag)) { + value.etag = resHeaders.etag; + } + this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value); + if (!this.#writeStream) { + return downstreamOnHeaders(); + } + this.#writeStream.on("drain", () => controller.resume()).on("error", function() { + handler2.#writeStream = void 0; + handler2.#store.delete(handler2.#cacheKey); + }).on("close", function() { + if (handler2.#writeStream === this) { + handler2.#writeStream = void 0; + } + controller.resume(); + }); + downstreamOnHeaders(); + } } - if (V instanceof URLSearchParams) { - return webidl.converters.URLSearchParams(V, prefix, name); + onResponseData(controller, chunk) { + if (this.#writeStream?.write(chunk) === false) { + controller.pause(); + } + this.#handler.onResponseData?.(controller, chunk); } - return webidl.converters.DOMString(V, prefix, name); - }; - webidl.converters.BodyInit = function(V, prefix, argument) { - if (V instanceof ReadableStream) { - return webidl.converters.ReadableStream(V, prefix, argument); + onResponseEnd(controller, trailers) { + this.#writeStream?.end(); + this.#handler.onResponseEnd?.(controller, trailers); } - if (V?.[Symbol.asyncIterator]) { - return V; + onResponseError(controller, err) { + this.#writeStream?.destroy(err); + this.#writeStream = void 0; + this.#handler.onResponseError?.(controller, err); } - 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 + function deleteCachedValue(store, cacheKey3) { + try { + store.delete(cacheKey3)?.catch?.(noop3); + } catch { } - ]); - module2.exports = { - isNetworkError, - makeNetworkError, - makeResponse, - makeAppropriateNetworkError, - filterResponse, - Response, - cloneResponse, - fromInnerResponse - }; - } -}); - -// node_modules/undici/lib/web/fetch/dispatcher-weakref.js -var require_dispatcher_weakref = __commonJS({ - "node_modules/undici/lib/web/fetch/dispatcher-weakref.js"(exports2, module2) { - "use strict"; - var { kConnected, kSize } = require_symbols(); - var CompatWeakRef = class { - constructor(value) { - this.value = value; + } + function deleteCachedValueIfNotModified(statusCode, store, cacheKey3) { + if (statusCode === 304) { + deleteCachedValue(store, cacheKey3); + } + } + function revalidationResponseDisallowsCachedReuse(cacheType, resHeaders, cacheControlDirectives) { + return cacheControlDirectives["no-store"] === true || cacheType === "shared" && (cacheControlDirectives.private === true || Object.hasOwn(resHeaders, "set-cookie")) || (resHeaders.vary ? isInvalidOrWildcardVaryHeader(resHeaders.vary) : false); + } + function canCacheResponse(cacheType, method, statusCode, resHeaders, cacheControlDirectives, reqHeaders) { + if (!arrayIncludes(util4.safeHTTPMethods, method)) { + return false; } - deref() { - return this.value[kConnected] === 0 && this.value[kSize] === 0 ? void 0 : this.value; + if (statusCode < 200 || arrayIncludes(NOT_UNDERSTOOD_STATUS_CODES, statusCode)) { + return false; } - }; - var CompatFinalizer = class { - constructor(finalizer) { - this.finalizer = finalizer; + if (!arrayIncludes(HEURISTICALLY_CACHEABLE_STATUS_CODES, statusCode) && !resHeaders["expires"] && !cacheControlDirectives.public && cacheControlDirectives["max-age"] === void 0 && // RFC 9111: a private response directive, if the cache is not shared + !(cacheControlDirectives.private && cacheType === "private") && !(cacheControlDirectives["s-maxage"] !== void 0 && cacheType === "shared")) { + return false; } - register(dispatcher, key) { - if (dispatcher.on) { - dispatcher.on("disconnect", () => { - if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { - this.finalizer(key); - } - }); + if (cacheControlDirectives["no-store"]) { + return false; + } + if (cacheType === "shared" && (cacheControlDirectives.private === true || Object.hasOwn(resHeaders, "set-cookie"))) { + return false; + } + if (resHeaders.vary && hasVaryStar(resHeaders.vary)) { + return false; + } + if (reqHeaders != null && Object.hasOwn(reqHeaders, "authorization")) { + if (!cacheControlDirectives.public && !cacheControlDirectives["s-maxage"] && !cacheControlDirectives["must-revalidate"]) { + return false; + } + if (typeof reqHeaders.authorization !== "string") { + return false; + } + if (Array.isArray(cacheControlDirectives["no-cache"]) && arrayIncludes(cacheControlDirectives["no-cache"], "authorization")) { + return false; + } + if (Array.isArray(cacheControlDirectives["private"]) && arrayIncludes(cacheControlDirectives["private"], "authorization")) { + return false; } } - unregister(key) { + return true; + } + function getDate2(dateHeader) { + let dateValue = dateHeader; + if (Array.isArray(dateValue)) { + if (dateValue.length !== 1) { + return null; + } + dateValue = dateValue[0]; } - }; - module2.exports = function() { - if (process.env.NODE_V8_COVERAGE && process.version.startsWith("v18")) { - process._rawDebug("Using compatibility WeakRef and FinalizationRegistry"); - return { - WeakRef: CompatWeakRef, - FinalizationRegistry: CompatFinalizer - }; + if (typeof dateValue !== "string") { + return null; } - return { WeakRef, FinalizationRegistry }; - }; + return parseHttpDate(dateValue); + } + function getAge(ageHeader) { + let ageValue = ageHeader; + if (Array.isArray(ageValue)) { + if (ageValue.length !== 1) { + return MAX_RESPONSE_AGE; + } + ageValue = ageValue[0]; + } + if (typeof ageValue !== "string" || !/^[\t ]*[0-9]+[\t ]*$/.test(ageValue)) { + return MAX_RESPONSE_AGE; + } + const age = BigInt(ageValue.replace(/^[\t ]+|[\t ]+$/g, "")); + if (age >= BigInt(MAX_RESPONSE_AGE / 1e3)) { + return MAX_RESPONSE_AGE; + } + return Number(age) * 1e3; + } + function determineStaleAt(cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) { + if (cacheType === "shared") { + if (hasInvalidCacheControlDirective(cacheControlDirectives, "s-maxage")) { + return 0; + } + const sMaxAge = cacheControlDirectives["s-maxage"]; + if (sMaxAge !== void 0) { + return sMaxAge * 1e3; + } + } + if (hasInvalidCacheControlDirective(cacheControlDirectives, "max-age")) { + return 0; + } + const maxAge = cacheControlDirectives["max-age"]; + if (maxAge !== void 0) { + return maxAge * 1e3; + } + if (Object.hasOwn(resHeaders, "expires")) { + if (typeof resHeaders.expires !== "string") { + return 0; + } + const expiresDate = parseHttpDate(resHeaders.expires); + if (!expiresDate) { + return 0; + } + if (now >= expiresDate.getTime()) { + return 0; + } + if (responseDate) { + if (responseDate >= expiresDate) { + return 0; + } + const freshnessLifetime = expiresDate.getTime() - responseDate.getTime(); + if (age !== void 0 && age >= freshnessLifetime) { + return 0; + } + return freshnessLifetime; + } + return expiresDate.getTime() - now; + } + if (typeof resHeaders["last-modified"] === "string") { + const lastModified = parseHttpDate(resHeaders["last-modified"]); + if (lastModified) { + if (lastModified.getTime() >= now) { + return void 0; + } + const responseAge = now - lastModified.getTime(); + return responseAge * 0.1; + } + } + if (cacheControlDirectives.immutable) { + return 31536e6; + } + return void 0; + } + function determineDeleteAt(baseTime, cachedAt, cacheControlDirectives, staleAt) { + let staleWhileRevalidate = -Infinity; + let staleIfError = -Infinity; + let immutable = -Infinity; + if (cacheControlDirectives["stale-while-revalidate"]) { + staleWhileRevalidate = staleAt + cacheControlDirectives["stale-while-revalidate"] * 1e3; + } + if (cacheControlDirectives["stale-if-error"]) { + staleIfError = staleAt + cacheControlDirectives["stale-if-error"] * 1e3; + } + if (cacheControlDirectives.immutable && staleWhileRevalidate === -Infinity && staleIfError === -Infinity) { + immutable = cachedAt + 31536e6; + } + if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) { + const freshnessLifetime = staleAt - baseTime; + const datePrecisionPadding = Math.min(Math.max(cachedAt - baseTime, 0), 1e3); + return staleAt + freshnessLifetime + datePrecisionPadding; + } + return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable); + } + function stripNecessaryHeaders(resHeaders, cacheControlDirectives) { + const headersToRemove = [ + "connection", + "proxy-authenticate", + "proxy-authentication-info", + "proxy-authorization", + "proxy-connection", + "te", + "transfer-encoding", + "upgrade", + // We'll add age back when serving it + "age" + ]; + if (resHeaders["connection"]) { + appendConnectionHeaderTokens(headersToRemove, resHeaders["connection"]); + } + if (Array.isArray(cacheControlDirectives["no-cache"])) { + headersToRemove.push(...cacheControlDirectives["no-cache"]); + } + if (Array.isArray(cacheControlDirectives["private"])) { + headersToRemove.push(...cacheControlDirectives["private"]); + } + let strippedHeaders; + for (const headerName of headersToRemove) { + if (Object.hasOwn(resHeaders, headerName)) { + strippedHeaders ??= { ...resHeaders }; + delete strippedHeaders[headerName]; + } + } + return strippedHeaders ?? resHeaders; + } + module2.exports = CacheHandler; } }); -// node_modules/undici/lib/web/fetch/request.js -var require_request2 = __commonJS({ - "node_modules/undici/lib/web/fetch/request.js"(exports2, module2) { +// node_modules/undici/lib/cache/memory-cache-store.js +var require_memory_cache_store = __commonJS({ + "node_modules/undici/lib/cache/memory-cache-store.js"(exports2, module2) { "use strict"; - var { extractBody, mixinBody, cloneBody, bodyUnusable } = require_body(); - var { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require_headers(); - var { FinalizationRegistry: FinalizationRegistry2 } = require_dispatcher_weakref()(); - var util3 = require_util(); - var nodeUtil = require("node:util"); - var { - isValidHTTPToken, - sameOrigin, - environmentSettingsObject - } = require_util2(); - var { - forbiddenMethodsSet, - corsSafeListedMethodsSet, - referrerPolicy, - requestRedirect, - requestMode, - requestCredentials, - requestCache, - requestDuplex - } = require_constants3(); - var { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util3; - var { kHeaders, kSignal, kState, kDispatcher } = require_symbols2(); - var { webidl } = require_webidl(); - var { URLSerializer } = require_data_url(); - var { kConstruct } = require_symbols(); - var assert = require("node:assert"); - var { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = require("node:events"); - var kAbortController = /* @__PURE__ */ Symbol("abortController"); - var requestFinalizer = new FinalizationRegistry2(({ signal, abort }) => { - signal.removeEventListener("abort", abort); - }); - var dependentControllerMap = /* @__PURE__ */ new WeakMap(); - function buildAbort(acRef) { - return abort; - function abort() { - const ac = acRef.deref(); - if (ac !== void 0) { - requestFinalizer.unregister(abort); - this.removeEventListener("abort", abort); - ac.abort(this.reason); - const controllerList = dependentControllerMap.get(ac.signal); - if (controllerList !== void 0) { - if (controllerList.size !== 0) { - for (const ref of controllerList) { - const ctrl = ref.deref(); - if (ctrl !== void 0) { - ctrl.abort(this.reason); + var { Writable } = require("node:stream"); + var { EventEmitter: EventEmitter2 } = require("node:events"); + var { assertCacheKey, assertCacheValue } = require_cache(); + var MemoryCacheStore = class extends EventEmitter2 { + #maxCount = 1024; + #maxSize = 104857600; + // 100MB + #maxEntrySize = 5242880; + // 5MB + #size = 0; + #count = 0; + #entries = /* @__PURE__ */ new Map(); + #hasEmittedMaxSizeEvent = false; + /** + * @param {import('../../types/cache-interceptor.d.ts').default.MemoryCacheStoreOpts | undefined} [opts] + */ + constructor(opts) { + super(); + if (opts) { + if (typeof opts !== "object") { + throw new TypeError("MemoryCacheStore options must be an object"); + } + if (opts.maxCount !== void 0) { + if (typeof opts.maxCount !== "number" || !Number.isInteger(opts.maxCount) || opts.maxCount < 0) { + throw new TypeError("MemoryCacheStore options.maxCount must be a non-negative integer"); + } + this.#maxCount = opts.maxCount; + } + if (opts.maxSize !== void 0) { + if (typeof opts.maxSize !== "number" || !Number.isInteger(opts.maxSize) || opts.maxSize < 0) { + throw new TypeError("MemoryCacheStore options.maxSize must be a non-negative integer"); + } + this.#maxSize = opts.maxSize; + } + if (opts.maxEntrySize !== void 0) { + if (typeof opts.maxEntrySize !== "number" || !Number.isInteger(opts.maxEntrySize) || opts.maxEntrySize < 0) { + throw new TypeError("MemoryCacheStore options.maxEntrySize must be a non-negative integer"); + } + this.#maxEntrySize = opts.maxEntrySize; + } + } + } + /** + * Get the current size of the cache in bytes + * @returns {number} The current size of the cache in bytes + */ + get size() { + return this.#size; + } + /** + * Check if the cache is full (either max size or max count reached) + * @returns {boolean} True if the cache is full, false otherwise + */ + isFull() { + return this.#size >= this.#maxSize || this.#count >= this.#maxCount; + } + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} req + * @returns {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined} + */ + get(key) { + assertCacheKey(key); + const topLevelKey = `${key.origin}:${key.path}`; + const now = Date.now(); + const entries = this.#entries.get(topLevelKey); + const entry = entries ? findEntry(key, entries, now) : null; + return entry == null ? void 0 : { + statusMessage: entry.statusMessage, + statusCode: entry.statusCode, + headers: entry.headers, + body: entry.body, + vary: entry.vary ? entry.vary : void 0, + etag: entry.etag, + cacheControlDirectives: entry.cacheControlDirectives, + cachedAt: entry.cachedAt, + staleAt: entry.staleAt, + deleteAt: entry.deleteAt + }; + } + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} val + * @returns {Writable | undefined} + */ + createWriteStream(key, val) { + assertCacheKey(key); + assertCacheValue(val); + const topLevelKey = `${key.origin}:${key.path}`; + const store = this; + const entry = { ...key, ...val, body: [], size: 0 }; + return new Writable({ + write(chunk, encoding, callback) { + if (typeof chunk === "string") { + chunk = Buffer.from(chunk, encoding); + } + entry.size += chunk.byteLength; + if (entry.size >= store.#maxEntrySize) { + this.destroy(); + } else { + entry.body.push(chunk); + } + callback(null); + }, + final(callback) { + let entries = store.#entries.get(topLevelKey); + if (!entries) { + entries = []; + store.#entries.set(topLevelKey, entries); + } + const previousEntry = findEntry(key, entries, Date.now()); + if (previousEntry) { + const index2 = entries.indexOf(previousEntry); + entries.splice(index2, 1, entry); + store.#size -= previousEntry.size; + } else { + entries.push(entry); + store.#count += 1; + } + store.#size += entry.size; + if (store.#size > store.#maxSize || store.#count > store.#maxCount) { + if (!store.#hasEmittedMaxSizeEvent) { + store.emit("maxSizeExceeded", { + size: store.#size, + maxSize: store.#maxSize, + count: store.#count, + maxCount: store.#maxCount + }); + store.#hasEmittedMaxSizeEvent = true; + } + for (const [key2, entries2] of store.#entries) { + for (const entry2 of entries2.splice(0, entries2.length / 2)) { + store.#size -= entry2.size; + store.#count -= 1; + } + if (entries2.length === 0) { + store.#entries.delete(key2); } } - controllerList.clear(); + if (store.#size < store.#maxSize && store.#count < store.#maxCount) { + store.#hasEmittedMaxSizeEvent = false; + } } - dependentControllerMap.delete(ac.signal); + callback(null); } + }); + } + /** + * @param {CacheKey} key + */ + delete(key) { + if (typeof key !== "object") { + throw new TypeError(`expected key to be object, got ${typeof key}`); + } + const topLevelKey = `${key.origin}:${key.path}`; + for (const entry of this.#entries.get(topLevelKey) ?? []) { + this.#size -= entry.size; + this.#count -= 1; + } + this.#entries.delete(topLevelKey); + } + }; + function findEntry(key, entries, now) { + for (let i = 0; i < entries.length; i++) { + const entry = entries[i]; + if (entry.deleteAt > now && entry.method === key.method && varyMatches(key, entry)) { + return entry; } } } - var patchMethodWarning = false; - var Request = class _Request { - // https://fetch.spec.whatwg.org/#dom-request - constructor(input, init2 = {}) { - webidl.util.markAsUncloneable(this); - if (input === kConstruct) { - return; + function varyMatches(key, entry) { + if (entry.vary == null) { + return true; + } + for (const headerName in entry.vary) { + if (Object.hasOwn(entry.vary, headerName) && !headerValueEquals(key.headers?.[headerName], entry.vary[headerName])) { + return false; } - const prefix = "Request constructor"; - webidl.argumentLengthCheck(arguments, 1, prefix); - input = webidl.converters.RequestInfo(input, prefix, "input"); - init2 = webidl.converters.RequestInit(init2, prefix, "init"); - let request3 = null; - let fallbackMode = null; - const baseUrl = environmentSettingsObject.settingsObject.baseUrl; - let signal = null; - if (typeof input === "string") { - this[kDispatcher] = init2.dispatcher; - let parsedURL; - try { - parsedURL = new URL(input, baseUrl); - } catch (err) { - throw new TypeError("Failed to parse URL from " + input, { cause: err }); - } - if (parsedURL.username || parsedURL.password) { - throw new TypeError( - "Request cannot be constructed from a URL that includes credentials: " + input - ); + } + return true; + } + function headerValueEquals(lhs, rhs) { + if (lhs == null && rhs == null) { + return true; + } + if (lhs == null && rhs != null || lhs != null && rhs == null) { + return false; + } + if (Array.isArray(lhs) && Array.isArray(rhs)) { + if (lhs.length !== rhs.length) { + return false; + } + for (let i = 0; i < lhs.length; i++) { + if (lhs[i] !== rhs[i]) { + return false; } - request3 = makeRequest({ urlList: [parsedURL] }); - fallbackMode = "cors"; - } else { - this[kDispatcher] = init2.dispatcher || input[kDispatcher]; - assert(input instanceof _Request); - request3 = input[kState]; - signal = input[kSignal]; } - const origin = environmentSettingsObject.settingsObject.origin; - let window2 = "client"; - if (request3.window?.constructor?.name === "EnvironmentSettingsObject" && sameOrigin(request3.window, origin)) { - window2 = request3.window; + return true; + } + return lhs === rhs; + } + module2.exports = MemoryCacheStore; + } +}); + +// node_modules/undici/lib/handler/cache-revalidation-handler.js +var require_cache_revalidation_handler = __commonJS({ + "node_modules/undici/lib/handler/cache-revalidation-handler.js"(exports2, module2) { + "use strict"; + var assert = require("node:assert"); + var CacheRevalidationHandler = class { + #successful = false; + /** + * @type {((success: boolean, context?: any, statusCode?: number, headers?: import('../../types/header.d.ts').IncomingHttpHeaders) => void) | null} + */ + #callback; + /** + * @type {(import('../../types/dispatcher.d.ts').default.DispatchHandler)} + */ + #handler; + #context; + /** + * @type {boolean} + */ + #allowErrorStatusCodes; + /** + * @param {(success: boolean, context?: any, statusCode?: number, headers?: import('../../types/header.d.ts').IncomingHttpHeaders) => void} callback Function to call if the cached value is valid + * @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler + * @param {boolean} allowErrorStatusCodes + */ + constructor(callback, handler2, allowErrorStatusCodes) { + if (typeof callback !== "function") { + throw new TypeError("callback must be a function"); } - if (init2.window != null) { - throw new TypeError(`'window' option '${window2}' must be null`); + this.#callback = callback; + this.#handler = handler2; + this.#allowErrorStatusCodes = allowErrorStatusCodes; + } + onRequestStart(_2, context5) { + this.#successful = false; + this.#context = context5; + } + onRequestUpgrade(controller, statusCode, headers, socket) { + this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket); + } + onResponseStart(controller, statusCode, headers, statusMessage) { + assert(this.#callback != null); + this.#successful = statusCode === 304 || this.#allowErrorStatusCodes && statusCode >= 500 && statusCode <= 504; + this.#callback(this.#successful, this.#context, statusCode, headers); + this.#callback = null; + if (this.#successful) { + return true; } - if ("window" in init2) { - window2 = "no-window"; + this.#handler.onRequestStart?.(controller, this.#context); + this.#handler.onResponseStart?.( + controller, + statusCode, + headers, + statusMessage + ); + } + onResponseData(controller, chunk) { + if (this.#successful) { + return; } - request3 = 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: request3.method, - // header list A copy of request’s header list. - // undici implementation note: headersList is cloned in makeRequest - headersList: request3.headersList, - // unsafe-request flag Set. - unsafeRequest: request3.unsafeRequest, - // client This’s relevant settings object. - client: environmentSettingsObject.settingsObject, - // window window. - window: window2, - // priority request’s priority. - priority: request3.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: request3.origin, - // referrer request’s referrer. - referrer: request3.referrer, - // referrer policy request’s referrer policy. - referrerPolicy: request3.referrerPolicy, - // mode request’s mode. - mode: request3.mode, - // credentials mode request’s credentials mode. - credentials: request3.credentials, - // cache mode request’s cache mode. - cache: request3.cache, - // redirect mode request’s redirect mode. - redirect: request3.redirect, - // integrity metadata request’s integrity metadata. - integrity: request3.integrity, - // keepalive request’s keepalive. - keepalive: request3.keepalive, - // reload-navigation flag request’s reload-navigation flag. - reloadNavigation: request3.reloadNavigation, - // history-navigation flag request’s history-navigation flag. - historyNavigation: request3.historyNavigation, - // URL list A clone of request’s URL list. - urlList: [...request3.urlList] - }); - const initHasKey = Object.keys(init2).length !== 0; - if (initHasKey) { - if (request3.mode === "navigate") { - request3.mode = "same-origin"; - } - request3.reloadNavigation = false; - request3.historyNavigation = false; - request3.origin = "client"; - request3.referrer = "client"; - request3.referrerPolicy = ""; - request3.url = request3.urlList[request3.urlList.length - 1]; - request3.urlList = [request3.url]; + return this.#handler.onResponseData?.(controller, chunk); + } + onResponseEnd(controller, trailers) { + if (this.#successful) { + return; } - if (init2.referrer !== void 0) { - const referrer = init2.referrer; - if (referrer === "") { - request3.referrer = "no-referrer"; - } else { - let parsedReferrer; - try { - parsedReferrer = new URL(referrer, baseUrl); - } catch (err) { - throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }); - } - if (parsedReferrer.protocol === "about:" && parsedReferrer.hostname === "client" || origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) { - request3.referrer = "client"; - } else { - request3.referrer = parsedReferrer; - } - } + this.#handler.onResponseEnd?.(controller, trailers); + } + onResponseError(controller, err) { + if (this.#successful) { + return; } - if (init2.referrerPolicy !== void 0) { - request3.referrerPolicy = init2.referrerPolicy; + if (this.#callback) { + this.#callback(false); + this.#callback = null; } - let mode; - if (init2.mode !== void 0) { - mode = init2.mode; + if (typeof this.#handler.onResponseError === "function") { + this.#handler.onResponseError(controller, err); } else { - mode = fallbackMode; - } - if (mode === "navigate") { - throw webidl.errors.exception({ - header: "Request constructor", - message: "invalid request mode navigate." - }); - } - if (mode != null) { - request3.mode = mode; + throw err; } - if (init2.credentials !== void 0) { - request3.credentials = init2.credentials; + } + }; + module2.exports = CacheRevalidationHandler; + } +}); + +// node_modules/undici/lib/interceptor/cache.js +var require_cache2 = __commonJS({ + "node_modules/undici/lib/interceptor/cache.js"(exports2, module2) { + "use strict"; + var assert = require("node:assert"); + var { Readable: Readable4 } = require("node:stream"); + var util4 = require_util(); + var CacheHandler = require_cache_handler(); + var MemoryCacheStore = require_memory_cache_store(); + var CacheRevalidationHandler = require_cache_revalidation_handler(); + var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader, isInvalidOrWildcardVaryHeader } = require_cache(); + var { AbortError: AbortError2 } = require_errors(); + var { parseHttpDate } = require_date(); + function assertCacheOrigins(origins, name) { + if (origins === void 0) return; + if (!Array.isArray(origins)) { + throw new TypeError(`expected ${name} to be an array or undefined, got ${typeof origins}`); + } + for (let i = 0; i < origins.length; i++) { + const origin = origins[i]; + if (typeof origin !== "string" && !(origin instanceof RegExp)) { + throw new TypeError(`expected ${name}[${i}] to be a string or RegExp, got ${typeof origin}`); } - if (init2.cache !== void 0) { - request3.cache = init2.cache; + } + } + var nop = () => { + }; + function trimOWS(value) { + return value.replace(/^[\t ]+|[\t ]+$/g, ""); + } + function arrayIncludes(array2, value) { + for (let i = 0; i < array2.length; i++) { + if (array2[i] === value) { + return true; } - if (request3.cache === "only-if-cached" && request3.mode !== "same-origin") { - throw new TypeError( - "'only-if-cached' can be set only with 'same-origin' mode" - ); + } + return false; + } + function hasPragmaNoCache(headers) { + const pragma = headers?.pragma; + if (!pragma) { + return false; + } + const values = Array.isArray(pragma) ? pragma : [pragma]; + for (let i = 0; i < values.length; i++) { + const value = values[i]; + if (typeof value !== "string") { + continue; } - if (init2.redirect !== void 0) { - request3.redirect = init2.redirect; + const directives = value.split(","); + for (let j = 0; j < directives.length; j++) { + if (trimOWS(directives[j]).toLowerCase() === "no-cache") { + return true; + } } - if (init2.integrity != null) { - request3.integrity = String(init2.integrity); + } + return false; + } + function needsRevalidation(result, cacheControlDirectives, { headers = {} }) { + if (cacheControlDirectives?.["no-cache"]) { + return true; + } + if (result.cacheControlDirectives?.["no-cache"] && !Array.isArray(result.cacheControlDirectives["no-cache"])) { + return true; + } + if (headers["if-modified-since"] || headers["if-none-match"]) { + return true; + } + return false; + } + function staleResponseRequiresRevalidation(result, cacheType) { + return result.cacheControlDirectives?.["must-revalidate"] === true || cacheType === "shared" && (result.cacheControlDirectives?.["proxy-revalidate"] === true || // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.10 + // s-maxage implies proxy-revalidate for shared caches. + result.cacheControlDirectives?.["s-maxage"] !== void 0); + } + function revalidationResponseDisallowsCachedReuse(cacheType, headers) { + if (headers.vary && isInvalidOrWildcardVaryHeader(headers.vary) || cacheType === "shared" && Object.hasOwn(headers, "set-cookie")) { + return true; + } + const cacheControl = headers["cache-control"]; + if (!cacheControl) { + return false; + } + const cacheControlDirectives = parseCacheControlHeader(cacheControl); + return cacheControlDirectives["no-store"] === true || cacheType === "shared" && cacheControlDirectives.private === true; + } + function revalidationResponseUpdatesCacheControl(headers) { + return headers["cache-control"] !== void 0; + } + function deleteCachedValue(store, cacheKey3) { + try { + store.delete(cacheKey3)?.catch?.(nop); + } catch { + } + } + function getUsableLastModified(headers) { + const lastModified = headers?.["last-modified"]; + if (typeof lastModified === "string" && parseHttpDate(lastModified)) { + return lastModified; + } + } + function makeRevalidationHeaders(opts, result) { + const headers = { + ...opts.headers, + "if-modified-since": getUsableLastModified(result.headers) ?? new Date(result.cachedAt).toUTCString() + }; + if (result.etag) { + headers["if-none-match"] = result.etag; + } + if (result.vary) { + for (const key in result.vary) { + if (result.vary[key] != null) { + headers[key] = result.vary[key]; + } } - if (init2.keepalive !== void 0) { - request3.keepalive = Boolean(init2.keepalive); + } + return headers; + } + function isStale(result, cacheControlDirectives, cacheType) { + const now = Date.now(); + if (now > result.staleAt) { + if (!staleResponseRequiresRevalidation(result, cacheType) && cacheControlDirectives?.["max-stale"]) { + const gracePeriod = result.staleAt + cacheControlDirectives["max-stale"] * 1e3; + return now > gracePeriod; } - if (init2.method !== void 0) { - let method = init2.method; - const mayBeNormalized = normalizedMethodRecords[method]; - if (mayBeNormalized !== void 0) { - request3.method = mayBeNormalized; - } else { - if (!isValidHTTPToken(method)) { - throw new TypeError(`'${method}' is not a valid HTTP method.`); + return true; + } + if (cacheControlDirectives?.["min-fresh"]) { + const timeLeftTillStale = result.staleAt - now; + const threshold = cacheControlDirectives["min-fresh"] * 1e3; + return timeLeftTillStale <= threshold; + } + return false; + } + function withinStaleWhileRevalidateWindow(result, cacheType) { + const staleWhileRevalidate = result.cacheControlDirectives?.["stale-while-revalidate"]; + if (!staleWhileRevalidate || staleResponseRequiresRevalidation(result, cacheType)) { + return false; + } + const now = Date.now(); + const staleWhileRevalidateExpiry = result.staleAt + staleWhileRevalidate * 1e3; + return now <= staleWhileRevalidateExpiry; + } + function handleUncachedResponse(dispatch, globalOpts, cacheKey3, handler2, opts, reqCacheControl) { + if (reqCacheControl?.["only-if-cached"]) { + let aborted = false; + try { + if (typeof handler2.onConnect === "function") { + handler2.onConnect(() => { + aborted = true; + }); + if (aborted) { + return; } - const upperCase = method.toUpperCase(); - if (forbiddenMethodsSet.has(upperCase)) { - throw new TypeError(`'${method}' HTTP method is unsupported.`); + } + if (typeof handler2.onHeaders === "function") { + handler2.onHeaders(504, [], nop, "Gateway Timeout"); + if (aborted) { + return; } - method = normalizedMethodRecordsBase[upperCase] ?? method; - request3.method = method; } - if (!patchMethodWarning && request3.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; + if (typeof handler2.onComplete === "function") { + handler2.onComplete([]); + } + } catch (err) { + if (typeof handler2.onError === "function") { + handler2.onError(err); } } - if (init2.signal !== void 0) { - signal = init2.signal; + return true; + } + return dispatch(opts, new CacheHandler(globalOpts, cacheKey3, handler2)); + } + function sendCachedValue(handler2, opts, result, age, context5, isStale2) { + const stream2 = util4.isStream(result.body) ? result.body : Readable4.from(result.body ?? []); + assert(!stream2.destroyed, "stream should not be destroyed"); + assert(!stream2.readableDidRead, "stream should not be readableDidRead"); + const controller = { + resume() { + stream2.resume(); + }, + pause() { + stream2.pause(); + }, + get paused() { + return stream2.isPaused(); + }, + get aborted() { + return stream2.destroyed; + }, + get reason() { + return stream2.errored; + }, + abort(reason) { + stream2.destroy(reason ?? new AbortError2()); } - this[kState] = request3; - const ac = new AbortController(); - this[kSignal] = ac.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); + }; + stream2.on("error", function(err) { + if (!this.readableEnded) { + if (typeof handler2.onResponseError === "function") { + handler2.onResponseError(controller, err); } else { - this[kAbortController] = ac; - const acRef = new WeakRef(ac); - const abort = buildAbort(acRef); - try { - if (typeof getMaxListeners === "function" && getMaxListeners(signal) === defaultMaxListeners) { - setMaxListeners(1500, signal); - } else if (getEventListeners(signal, "abort").length >= defaultMaxListeners) { - setMaxListeners(1500, signal); - } - } catch { - } - util3.addAbortListener(signal, abort); - requestFinalizer.register(ac, { signal, abort }, abort); + throw err; } } - this[kHeaders] = new Headers(kConstruct); - setHeadersList(this[kHeaders], request3.headersList); - setHeadersGuard(this[kHeaders], "request"); - if (mode === "no-cors") { - if (!corsSafeListedMethodsSet.has(request3.method)) { - throw new TypeError( - `'${request3.method} is unsupported in no-cors mode.` + }).on("close", function() { + if (!this.errored) { + handler2.onResponseEnd?.(controller, {}); + } + }); + handler2.onRequestStart?.(controller, context5); + if (stream2.destroyed) { + return; + } + const headers = { ...result.headers, age: String(age) }; + if (isStale2) { + headers.warning = '110 - "response is stale"'; + } + handler2.onResponseStart?.(controller, result.statusCode, headers, result.statusMessage); + if (opts.method === "HEAD") { + stream2.destroy(); + } else { + stream2.on("data", function(chunk) { + handler2.onResponseData?.(controller, chunk); + }); + } + } + function handleResult(dispatch, globalOpts, cacheKey3, handler2, opts, reqCacheControl, result) { + if (!result) { + return handleUncachedResponse(dispatch, globalOpts, cacheKey3, handler2, opts, reqCacheControl); + } + if (globalOpts.type === "shared" && Object.hasOwn(result.headers, "set-cookie")) { + if (util4.isStream(result.body)) { + result.body.on("error", nop).destroy(); + } + deleteCachedValue(globalOpts.store, cacheKey3); + return handleUncachedResponse(dispatch, globalOpts, cacheKey3, handler2, opts, reqCacheControl); + } + const now = Date.now(); + if (now > result.deleteAt) { + return dispatch(opts, new CacheHandler(globalOpts, cacheKey3, handler2)); + } + const age = Math.round((now - result.cachedAt) / 1e3); + const requestMaxAgeExpired = reqCacheControl?.["max-age"] !== void 0 && age >= reqCacheControl["max-age"]; + const stale = requestMaxAgeExpired || isStale(result, reqCacheControl, globalOpts.type); + const revalidate = requestMaxAgeExpired || needsRevalidation(result, reqCacheControl, opts); + if (stale || revalidate) { + if (util4.isStream(opts.body) && util4.bodyLength(opts.body) !== 0) { + return dispatch(opts, new CacheHandler(globalOpts, cacheKey3, handler2)); + } + if (!revalidate && withinStaleWhileRevalidateWindow(result, globalOpts.type)) { + sendCachedValue(handler2, opts, result, age, null, true); + queueMicrotask(() => { + const headers2 = makeRevalidationHeaders(opts, result); + dispatch( + { + ...opts, + headers: headers2 + }, + new CacheHandler(globalOpts, cacheKey3, { + // Silent handler that just updates the cache + onRequestStart() { + }, + onRequestUpgrade() { + }, + onResponseStart() { + }, + onResponseData() { + }, + onResponseEnd() { + }, + onResponseError() { + } + }) ); - } - setHeadersGuard(this[kHeaders], "request-no-cors"); + }); + return true; } - if (initHasKey) { - const headersList = getHeadersList(this[kHeaders]); - const headers = init2.headers !== void 0 ? init2.headers : new HeadersList(headersList); - headersList.clear(); - if (headers instanceof HeadersList) { - for (const { name, value } of headers.rawValues()) { - headersList.append(name, value, false); - } - headersList.cookies = headers.cookies; - } else { - fillHeaders(this[kHeaders], headers); + let withinStaleIfErrorThreshold = false; + if (!staleResponseRequiresRevalidation(result, globalOpts.type)) { + const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"]; + if (staleIfErrorExpiry) { + withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3; } } - const inputBody = input instanceof _Request ? input[kState].body : null; - if ((init2.body != null || inputBody != null) && (request3.method === "GET" || request3.method === "HEAD")) { - throw new TypeError("Request with GET/HEAD method cannot have body."); + const headers = makeRevalidationHeaders(opts, result); + return dispatch( + { + ...opts, + headers + }, + new CacheRevalidationHandler( + (success, context5, statusCode, headers2) => { + if (success) { + if (statusCode === 304) { + if (revalidationResponseDisallowsCachedReuse(globalOpts.type, headers2)) { + if (util4.isStream(result.body)) { + result.body.on("error", nop).destroy(); + } + deleteCachedValue(globalOpts.store, cacheKey3); + return dispatch(opts, new CacheHandler(globalOpts, cacheKey3, handler2)); + } + if (revalidationResponseUpdatesCacheControl(headers2)) { + deleteCachedValue(globalOpts.store, cacheKey3); + } + } + sendCachedValue(handler2, opts, result, age, context5, stale); + } else if (util4.isStream(result.body)) { + result.body.on("error", nop).destroy(); + } + }, + new CacheHandler(globalOpts, cacheKey3, handler2), + withinStaleIfErrorThreshold + ) + ); + } + if (util4.isStream(opts.body)) { + opts.body.on("error", nop).destroy(); + } + sendCachedValue(handler2, opts, result, age, null, false); + } + module2.exports = (opts = {}) => { + const { + store = new MemoryCacheStore(), + methods = ["GET"], + cacheByDefault = void 0, + type = "shared", + origins = void 0 + } = opts; + if (typeof opts !== "object" || opts === null) { + throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`); + } + assertCacheStore(store, "opts.store"); + assertCacheMethods(methods, "opts.methods"); + assertCacheOrigins(origins, "opts.origins"); + if (typeof cacheByDefault !== "undefined" && typeof cacheByDefault !== "number") { + throw new TypeError(`expected opts.cacheByDefault to be number or undefined, got ${typeof cacheByDefault}`); + } + if (typeof type !== "undefined" && type !== "shared" && type !== "private") { + throw new TypeError(`expected opts.type to be shared, private, or undefined, got ${typeof type}`); + } + const globalOpts = { + store, + methods, + cacheByDefault, + type + }; + const safeMethodsToNotCache = []; + for (let i = 0; i < util4.safeHTTPMethods.length; i++) { + const method = util4.safeHTTPMethods[i]; + if (!arrayIncludes(methods, method)) { + safeMethodsToNotCache.push(method); } - let initBody = null; - if (init2.body != null) { - const [extractedBody, contentType] = extractBody( - init2.body, - request3.keepalive - ); - initBody = extractedBody; - if (contentType && !getHeadersList(this[kHeaders]).contains("content-type", true)) { - this[kHeaders].append("content-type", contentType); + } + return (dispatch) => { + return (opts2, handler2) => { + if (!opts2.origin || arrayIncludes(safeMethodsToNotCache, opts2.method)) { + return dispatch(opts2, handler2); } - } - const inputOrInitBody = initBody ?? inputBody; - if (inputOrInitBody != null && inputOrInitBody.source == null) { - if (initBody != null && init2.duplex == null) { - throw new TypeError("RequestInit: duplex option is required when sending a body."); + if (origins !== void 0) { + const requestOrigin = opts2.origin.toString().toLowerCase(); + let isAllowed = false; + for (let i = 0; i < origins.length; i++) { + const allowed = origins[i]; + if (typeof allowed === "string") { + if (allowed.toLowerCase() === requestOrigin) { + isAllowed = true; + break; + } + } else if (allowed.test(requestOrigin)) { + isAllowed = true; + break; + } + } + if (!isAllowed) { + return dispatch(opts2, handler2); + } } - if (request3.mode !== "same-origin" && request3.mode !== "cors") { - throw new TypeError( - 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' - ); + opts2 = { + ...opts2, + headers: normalizeHeaders(opts2) + }; + const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : hasPragmaNoCache(opts2.headers) ? { "no-cache": true } : void 0; + if (reqCacheControl?.["no-store"]) { + return dispatch(opts2, handler2); } - request3.useCORSPreflightFlag = true; - } - let finalBody = inputOrInitBody; - if (initBody == null && inputBody != null) { - if (bodyUnusable(input)) { - throw new TypeError( - "Cannot construct a Request with a Request object that has already been used." + const cacheKey3 = makeCacheKey(opts2); + if (!arrayIncludes(util4.safeHTTPMethods, opts2.method)) { + return dispatch(opts2, new CacheHandler(globalOpts, cacheKey3, handler2)); + } + const result = store.get(cacheKey3); + if (result && typeof result.then === "function") { + return result.then((result2) => handleResult( + dispatch, + globalOpts, + cacheKey3, + handler2, + opts2, + reqCacheControl, + result2 + )); + } else { + return handleResult( + dispatch, + globalOpts, + cacheKey3, + handler2, + opts2, + reqCacheControl, + result ); } - const identityTransform = new TransformStream(); - inputBody.stream.pipeThrough(identityTransform); - finalBody = { - source: inputBody.source, - length: inputBody.length, - stream: identityTransform.readable - }; + }; + }; + }; + } +}); + +// node_modules/undici/lib/interceptor/decompress.js +var require_decompress = __commonJS({ + "node_modules/undici/lib/interceptor/decompress.js"(exports2, module2) { + "use strict"; + var { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = require("node:zlib"); + var { pipeline: pipeline2, Transform: TransformStream2 } = require("node:stream"); + var { InvalidArgumentError, ResponseExceededMaxSizeError } = require_errors(); + var DecoratorHandler = require_decorator_handler(); + var { runtimeFeatures } = require_runtime_features(); + var DecompressController = class { + #onPause; + #onResume; + #onAbort; + #paused = false; + constructor(onPause, onResume, onAbort) { + this.#onPause = onPause; + this.#onResume = onResume; + this.#onAbort = onAbort; + this.target = null; + } + pause() { + if (this.#paused) { + return; } - this[kState].body = finalBody; + this.#paused = true; + this.#onPause(); } - // Returns request’s HTTP method, which is "GET" by default. - get method() { - webidl.brandCheck(this, _Request); - return this[kState].method; + resume() { + if (!this.#paused) { + return; + } + this.#paused = false; + this.#onResume(); } - // Returns the URL of request as a string. - get url() { - webidl.brandCheck(this, _Request); - return URLSerializer(this[kState].url); + abort(reason) { + this.target?.abort(reason); + this.#onAbort(reason); } - // 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); - return this[kHeaders]; + get paused() { + return this.#paused; } - // Returns the kind of resource requested by request, e.g., "document" - // or "script". - get destination() { - webidl.brandCheck(this, _Request); - return this[kState].destination; + get aborted() { + return this.target?.aborted ?? false; } - // 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); - if (this[kState].referrer === "no-referrer") { - return ""; + get reason() { + return this.target?.reason ?? null; + } + get rawHeaders() { + return this.target?.rawHeaders ?? null; + } + set rawHeaders(value) { + if (this.target) { + this.target.rawHeaders = value; } - if (this[kState].referrer === "client") { - return "about:client"; + } + get rawTrailers() { + return this.target?.rawTrailers ?? null; + } + set rawTrailers(value) { + if (this.target) { + this.target.rawTrailers = value; } - 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); - return this[kState].referrerPolicy; + }; + var supportedEncodings = { + gzip: createGunzip, + "x-gzip": createGunzip, + br: createBrotliDecompress, + deflate: createInflate, + compress: createInflate, + "x-compress": createInflate, + ...runtimeFeatures.has("zstd") ? { zstd: createZstdDecompress } : {} + }; + var defaultSkipStatusCodes = ( + /** @type {const} */ + [204, 304] + ); + var defaultMaxSize = 0; + function createMaxSizeLimiter(maxSize) { + let size = 0; + return new TransformStream2({ + transform(chunk, _encoding, callback) { + const decompressedSize = size + chunk.length; + if (decompressedSize > maxSize) { + callback(new ResponseExceededMaxSizeError( + `Decompressed response size (${decompressedSize}) exceeded maxSize (${maxSize})` + )); + return; + } + size = decompressedSize; + callback(null, chunk); + } + }); + } + var warningEmitted = ( + /** @type {boolean} */ + false + ); + var DecompressHandler = class extends DecoratorHandler { + /** @type {Transform[]} */ + #decompressors = []; + /** @type {Record | undefined} */ + #trailers; + /** @type {Readonly} */ + #skipStatusCodes; + /** @type {boolean} */ + #skipErrorResponses; + /** @type {number} */ + #maxSize; + /** @type {number} */ + #decompressedSize = 0; + /** @type {boolean} */ + #terminated = false; + /** @type {boolean} */ + #inputEnded = false; + /** @type {boolean} */ + #inputBackpressured = false; + /** @type {boolean} */ + #upstreamPaused = false; + /** @type {boolean} */ + #draining = false; + /** @type {boolean} */ + #drainRequested = false; + /** @type {boolean} */ + #completionPending = false; + /** @type {DecompressorStream | undefined} */ + #finalDecompressor; + /** @type {DecompressController} */ + #controller; + constructor(handler2, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true, maxSize = defaultMaxSize } = {}) { + if (!Number.isSafeInteger(maxSize) || maxSize < 0) { + throw new InvalidArgumentError("maxSize must be a non-negative integer"); + } + super(handler2); + this.#skipStatusCodes = skipStatusCodes; + this.#skipErrorResponses = skipErrorResponses; + this.#maxSize = maxSize; + this.#controller = new DecompressController( + () => this.#onDownstreamPause(), + () => this.#onDownstreamResume(), + (reason) => { + if (this.#inputEnded && !this.#terminated) { + this.onResponseError(this.#controller, reason); + } + } + ); } - // 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); - return this[kState].mode; + #onDownstreamPause() { + this.#pauseUpstream(); } - // 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() { - return this[kState].credentials; + #onDownstreamResume() { + const drainWasDeferred = this.#draining; + this.#drainOutput(); + if (!drainWasDeferred) { + this.#resumeUpstreamIfNeeded(); + this.#finishIfReady(); + } } - // 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); - return this[kState].cache; + #pauseUpstream() { + if (!this.#upstreamPaused && !this.#terminated) { + this.#upstreamPaused = true; + this.#controller.target?.pause(); + } } - // 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); - return this[kState].redirect; + #resumeUpstreamIfNeeded() { + if (this.#upstreamPaused && !this.#controller.paused && !this.#inputBackpressured) { + this.#upstreamPaused = false; + if (!this.#inputEnded) { + this.#controller.target?.resume(); + } + } } - // 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); - return this[kState].integrity; + #drainOutput() { + if (this.#terminated || this.#controller.paused || !this.#finalDecompressor) { + return; + } + if (this.#draining) { + this.#drainRequested = true; + return; + } + this.#draining = true; + try { + do { + this.#drainRequested = false; + let chunk; + while (!this.#terminated && !this.#controller.paused && (chunk = this.#finalDecompressor.read()) !== null) { + if (this.#maxSize > 0) { + const decompressedSize = this.#decompressedSize + chunk.length; + if (decompressedSize > this.#maxSize) { + this.#fail(new ResponseExceededMaxSizeError( + `Decompressed response size (${decompressedSize}) exceeded maxSize (${this.#maxSize})` + )); + return; + } + this.#decompressedSize = decompressedSize; + } + try { + const result = super.onResponseData(this.#controller, chunk); + if (result === false && !this.#controller.paused) { + this.#controller.pause(); + } + } catch (err) { + this.#fail(err); + return; + } + } + } while (this.#drainRequested && !this.#terminated && !this.#controller.paused); + } finally { + this.#draining = false; + } + this.#resumeUpstreamIfNeeded(); + this.#finishIfReady(); } - // Returns a boolean indicating whether or not request can outlive the - // global in which it was created. - get keepalive() { - webidl.brandCheck(this, _Request); - return this[kState].keepalive; + #finishIfReady() { + if (this.#terminated || !this.#completionPending || this.#controller.paused || this.#draining) { + return; + } + this.#cleanupDecompressors(); + try { + super.onResponseEnd(this.#controller, this.#trailers); + } catch (err) { + this.#fail(err); + return; + } + this.#terminated = true; } - // Returns a boolean indicating whether or not request is for a reload - // navigation. - get isReloadNavigation() { - webidl.brandCheck(this, _Request); - return this[kState].reloadNavigation; + #onDecompressionEnd() { + if (this.#terminated) { + return; + } + this.#completionPending = true; + this.#drainOutput(); + this.#finishIfReady(); } - // 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); - return this[kState].historyNavigation; + /** + * Determines if decompression should be skipped based on encoding and status code + * @param {string} contentEncoding - Content-Encoding header value + * @param {number} statusCode - HTTP status code of the response + * @returns {boolean} - True if decompression should be skipped + */ + #shouldSkipDecompression(contentEncoding, statusCode) { + if (!contentEncoding || statusCode < 200) return true; + if (this.#skipStatusCodes.includes(statusCode)) return true; + if (this.#skipErrorResponses && statusCode >= 400) return true; + return false; } - // 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); - return this[kSignal]; + /** + * Creates a chain of decompressors for multiple content encodings + * + * @param {string} encodings - Comma-separated list of content encodings + * @returns {Array} - Array of decompressor and limiting streams + * @throws {Error} - If the number of content-encodings exceeds the maximum allowed + */ + #createDecompressionChain(encodings) { + const parts = encodings.split(","); + const maxContentEncodings = 5; + if (parts.length > maxContentEncodings) { + throw new Error(`too many content-encodings in response: ${parts.length}, maximum allowed is ${maxContentEncodings}`); + } + const decompressors = []; + for (let i = parts.length - 1; i >= 0; i--) { + const encoding = parts[i].trim(); + if (!encoding) continue; + if (!supportedEncodings[encoding]) { + decompressors.length = 0; + return decompressors; + } + decompressors.push(supportedEncodings[encoding]()); + } + if (decompressors.length < 2) { + return decompressors; + } + const streams = []; + for (let i = 0; i < decompressors.length; i++) { + streams.push(decompressors[i]); + if (i < decompressors.length - 1 && this.#maxSize > 0) { + streams.push(createMaxSizeLimiter(this.#maxSize)); + } + } + return streams; } - get body() { - webidl.brandCheck(this, _Request); - return this[kState].body ? this[kState].body.stream : null; + /** + * Stops decompression and reports an error. + * @param {Error} error - The decompression error + * @returns {void} + */ + #fail(error3) { + if (this.#terminated) { + return; + } + if (this.#inputEnded) { + this.onResponseError(this.#controller, error3); + } else { + this.#controller.abort(error3); + } } - get bodyUsed() { - webidl.brandCheck(this, _Request); - return !!this[kState].body && util3.isDisturbed(this[kState].body.stream); + /** + * Sets up event handlers for the final decompressor stream. + * @param {DecompressorStream} decompressor - The decompressor stream + * @returns {void} + */ + #setupDecompressorEvents(decompressor) { + this.#finalDecompressor = decompressor; + decompressor.on("readable", () => this.#drainOutput()); + decompressor.on("error", (error3) => this.#fail(error3)); } - get duplex() { - webidl.brandCheck(this, _Request); - return "half"; + /** + * Sets up event handling for a single decompressor + * @returns {void} + */ + #setupSingleDecompressor() { + const decompressor = this.#decompressors[0]; + this.#setupDecompressorEvents(decompressor); + decompressor.on("end", () => this.#onDecompressionEnd()); } - // Returns a clone of request. - clone() { - webidl.brandCheck(this, _Request); - if (bodyUnusable(this)) { - throw new TypeError("unusable"); + /** + * Sets up event handling for multiple chained decompressors using pipeline + * @returns {void} + */ + #setupMultipleDecompressors() { + const lastDecompressor = this.#decompressors[this.#decompressors.length - 1]; + this.#setupDecompressorEvents(lastDecompressor); + pipeline2(this.#decompressors, (err) => { + if (this.#terminated) { + return; + } + if (err) { + this.#fail(err); + return; + } + this.#onDecompressionEnd(); + }); + } + #setupInputBackpressure() { + const decompressor = this.#decompressors[0]; + decompressor.on("drain", () => { + if (this.#terminated) { + return; + } + this.#inputBackpressured = false; + if (!this.#controller.paused) { + this.#drainOutput(); + this.#resumeUpstreamIfNeeded(); + } + }); + } + /** + * Cleans up decompressor references to prevent memory leaks + * @returns {void} + */ + #cleanupDecompressors() { + this.#decompressors.length = 0; + this.#finalDecompressor = void 0; + } + onRequestStart(controller, context5) { + this.#controller.target = controller; + return super.onRequestStart(this.#controller, context5); + } + onRequestUpgrade(controller, statusCode, headers, socket) { + return super.onRequestUpgrade(this.#controller, statusCode, headers, socket); + } + /** + * @param {Controller} controller + * @param {number} statusCode + * @param {Record} headers + * @param {string} statusMessage + * @returns {void} + */ + onResponseStart(controller, statusCode, headers, statusMessage) { + const contentEncoding = headers["content-encoding"]; + if (this.#shouldSkipDecompression(contentEncoding, statusCode)) { + return super.onResponseStart(this.#controller, statusCode, headers, statusMessage); + } + const decompressors = this.#createDecompressionChain(contentEncoding.toLowerCase()); + if (decompressors.length === 0) { + this.#cleanupDecompressors(); + return super.onResponseStart(this.#controller, statusCode, headers, statusMessage); + } + this.#decompressors = decompressors; + const { "content-encoding": _2, "content-length": __, ...newHeaders } = headers; + if (this.#controller.rawHeaders) { + const rawHeaders = this.#controller.rawHeaders; + if (Array.isArray(rawHeaders)) { + const filteredHeaders = []; + for (let i = 0; i < rawHeaders.length; i += 2) { + const headerName = rawHeaders[i]; + const name = Buffer.isBuffer(headerName) ? headerName.toString("latin1") : `${headerName}`; + const lowerName = name.toLowerCase(); + if (lowerName === "content-encoding" || lowerName === "content-length") { + continue; + } + filteredHeaders.push(rawHeaders[i], rawHeaders[i + 1]); + } + rawHeaders.splice(0, rawHeaders.length, ...filteredHeaders); + } else if (typeof rawHeaders === "object") { + for (const name of Object.keys(rawHeaders)) { + const lowerName = name.toLowerCase(); + if (lowerName === "content-encoding" || lowerName === "content-length") { + delete rawHeaders[name]; + } + } + } } - const clonedRequest = cloneRequest(this[kState]); - const ac = new AbortController(); - if (this.signal.aborted) { - ac.abort(this.signal.reason); + this.#setupInputBackpressure(); + if (this.#decompressors.length === 1) { + this.#setupSingleDecompressor(); } else { - let list = dependentControllerMap.get(this.signal); - if (list === void 0) { - list = /* @__PURE__ */ new Set(); - dependentControllerMap.set(this.signal, list); + this.#setupMultipleDecompressors(); + } + return super.onResponseStart(this.#controller, statusCode, newHeaders, statusMessage); + } + /** + * @param {Controller} controller + * @param {Buffer} chunk + * @returns {void} + */ + onResponseData(controller, chunk) { + if (this.#decompressors.length > 0) { + if (!this.#decompressors[0].write(chunk)) { + this.#inputBackpressured = true; + this.#pauseUpstream(); } - const acRef = new WeakRef(ac); - list.add(acRef); - util3.addAbortListener( - ac.signal, - buildAbort(acRef) - ); + return; } - return fromInnerRequest(clonedRequest, ac.signal, getHeadersGuard(this[kHeaders])); + return super.onResponseData(this.#controller, chunk); } - [nodeUtil.inspect.custom](depth, options) { - if (options.depth === null) { - options.depth = 2; + /** + * @param {Controller} controller + * @param {Record | undefined} trailers + * @returns {void} + */ + onResponseEnd(controller, trailers) { + if (this.#decompressors.length > 0) { + this.#inputEnded = true; + this.#trailers = trailers; + this.#decompressors[0].end(); + return; } - 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)}`; + return super.onResponseEnd(this.#controller, trailers); + } + /** + * @param {Controller} controller + * @param {Error} err + * @returns {void} + */ + onResponseError(controller, err) { + if (this.#terminated) { + return; + } + this.#terminated = true; + for (const decompressor of this.#decompressors) { + decompressor.destroy(); + } + this.#cleanupDecompressors(); + super.onResponseError(this.#controller, err); } }; - mixinBody(Request); - function makeRequest(init2) { - return { - method: init2.method ?? "GET", - localURLsOnly: init2.localURLsOnly ?? false, - unsafeRequest: init2.unsafeRequest ?? false, - body: init2.body ?? null, - client: init2.client ?? null, - reservedClient: init2.reservedClient ?? null, - replacesClientId: init2.replacesClientId ?? "", - window: init2.window ?? "client", - keepalive: init2.keepalive ?? false, - serviceWorkers: init2.serviceWorkers ?? "all", - initiator: init2.initiator ?? "", - destination: init2.destination ?? "", - priority: init2.priority ?? null, - origin: init2.origin ?? "client", - policyContainer: init2.policyContainer ?? "client", - referrer: init2.referrer ?? "client", - referrerPolicy: init2.referrerPolicy ?? "", - mode: init2.mode ?? "no-cors", - useCORSPreflightFlag: init2.useCORSPreflightFlag ?? false, - credentials: init2.credentials ?? "same-origin", - useCredentials: init2.useCredentials ?? false, - cache: init2.cache ?? "default", - redirect: init2.redirect ?? "follow", - integrity: init2.integrity ?? "", - cryptoGraphicsNonceMetadata: init2.cryptoGraphicsNonceMetadata ?? "", - parserMetadata: init2.parserMetadata ?? "", - reloadNavigation: init2.reloadNavigation ?? false, - historyNavigation: init2.historyNavigation ?? false, - userActivation: init2.userActivation ?? false, - taintedOrigin: init2.taintedOrigin ?? false, - redirectCount: init2.redirectCount ?? 0, - responseTainting: init2.responseTainting ?? "basic", - preventNoCacheCacheControlHeaderModification: init2.preventNoCacheCacheControlHeaderModification ?? false, - done: init2.done ?? false, - timingAllowFailed: init2.timingAllowFailed ?? false, - urlList: init2.urlList, - url: init2.urlList[0], - headersList: init2.headersList ? new HeadersList(init2.headersList) : new HeadersList() + function createDecompressInterceptor(options = {}) { + if (!warningEmitted) { + process.emitWarning( + "DecompressInterceptor is experimental and subject to change", + "ExperimentalWarning" + ); + warningEmitted = true; + } + return (dispatch) => { + return (opts, handler2) => { + const decompressHandler = new DecompressHandler(handler2, options); + return dispatch(opts, decompressHandler); + }; }; } - function cloneRequest(request3) { - const newRequest = makeRequest({ ...request3, body: null }); - if (request3.body != null) { - newRequest.body = cloneBody(newRequest, request3.body); + module2.exports = createDecompressInterceptor; + } +}); + +// node_modules/undici/lib/handler/deduplication-handler.js +var require_deduplication_handler = __commonJS({ + "node_modules/undici/lib/handler/deduplication-handler.js"(exports2, module2) { + "use strict"; + var { RequestAbortedError } = require_errors(); + var DEFAULT_MAX_BUFFER_SIZE = 5 * 1024 * 1024; + var DeduplicationHandler = class { + /** + * @type {DispatchHandler} + */ + #primaryHandler; + /** + * Whether the primary request has started (onRequestStart received). Until + * then the request context is unknown and cannot be given to waiting handlers. + * @type {boolean} + */ + #requestStarted = false; + /** + * The primary request context, replayed to waiting handlers so they observe + * the same redirect history as the primary. + * @type {any} + */ + #context = null; + /** + * @type {WaitingHandler[]} + */ + #waitingHandlers = []; + /** + * @type {number} + */ + #maxBufferSize = DEFAULT_MAX_BUFFER_SIZE; + /** + * @type {number} + */ + #statusCode = 0; + /** + * @type {Record} + */ + #headers = {}; + /** + * @type {string} + */ + #statusMessage = ""; + /** + * @type {boolean} + */ + #aborted = false; + /** + * @type {boolean} + */ + #responseStarted = false; + /** + * @type {boolean} + */ + #responseDataStarted = false; + /** + * @type {boolean} + */ + #completed = false; + /** + * @type {import('../../types/dispatcher.d.ts').default.DispatchController | null} + */ + #controller = null; + /** + * @type {(() => void) | null} + */ + #onComplete = null; + /** + * @param {DispatchHandler} primaryHandler The primary handler + * @param {() => void} onComplete Callback when request completes + * @param {number} [maxBufferSize] Maximum paused buffer size per waiting handler + */ + constructor(primaryHandler, onComplete, maxBufferSize = DEFAULT_MAX_BUFFER_SIZE) { + this.#primaryHandler = primaryHandler; + this.#onComplete = onComplete; + this.#maxBufferSize = maxBufferSize; } - return newRequest; - } - function fromInnerRequest(innerRequest, signal, guard) { - const request3 = new Request(kConstruct); - request3[kState] = innerRequest; - request3[kSignal] = signal; - request3[kHeaders] = new Headers(kConstruct); - setHeadersList(request3[kHeaders], innerRequest.headersList); - setHeadersGuard(request3[kHeaders], guard); - return request3; - } - 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 + /** + * Add a waiting handler that will receive response events. + * Returns false if deduplication can no longer safely attach this handler. + * + * @param {DispatchHandler} handler + * @returns {boolean} + */ + addWaitingHandler(handler2) { + if (this.#completed || this.#responseDataStarted) { + return false; + } + const waitingHandler = this.#createWaitingHandler(handler2); + const waitingController = waitingHandler.controller; + try { + if (this.#requestStarted) { + handler2.onRequestStart?.(waitingController, this.#context); + if (waitingController.aborted) { + waitingHandler.done = true; + return true; + } + if (this.#responseStarted) { + handler2.onResponseStart?.( + waitingController, + this.#statusCode, + this.#headers, + this.#statusMessage + ); + } + } else { + waitingHandler.pendingStart = true; + } + } catch { + waitingHandler.done = true; + return true; + } + if (!waitingController.aborted) { + this.#waitingHandlers.push(waitingHandler); + } + return true; } - }); - webidl.converters.Request = webidl.interfaceConverter( - Request - ); - webidl.converters.RequestInfo = function(V, prefix, argument) { - if (typeof V === "string") { - return webidl.converters.USVString(V, prefix, argument); + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {any} context + */ + onRequestStart(controller, context5) { + this.#controller = controller; + if (!this.#requestStarted) { + this.#requestStarted = true; + this.#context = context5; + for (const waitingHandler of this.#waitingHandlers) { + if (waitingHandler.pendingStart && !waitingHandler.done && !waitingHandler.controller.aborted) { + waitingHandler.pendingStart = false; + try { + waitingHandler.handler.onRequestStart?.(waitingHandler.controller, context5); + } catch { + waitingHandler.done = true; + } + } + } + this.#pruneDoneWaitingHandlers(); + } + this.#primaryHandler.onRequestStart?.(controller, context5); } - if (V instanceof Request) { - return webidl.converters.Request(V, prefix, argument); + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {number} statusCode + * @param {import('../../types/header.d.ts').IncomingHttpHeaders} headers + * @param {Socket} socket + */ + onRequestUpgrade(controller, statusCode, headers, socket) { + this.#primaryHandler.onRequestUpgrade?.(controller, statusCode, headers, socket); } - return webidl.converters.USVString(V, prefix, argument); - }; - webidl.converters.AbortSignal = webidl.interfaceConverter( - AbortSignal - ); - 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 - } - ]); - module2.exports = { Request, makeRequest, fromInnerRequest, cloneRequest }; - } -}); - -// node_modules/undici/lib/web/fetch/index.js -var require_fetch = __commonJS({ - "node_modules/undici/lib/web/fetch/index.js"(exports2, module2) { - "use strict"; - var { - makeNetworkError, - makeAppropriateNetworkError, - filterResponse, - makeResponse, - fromInnerResponse - } = require_response(); - var { HeadersList } = require_headers(); - var { Request, cloneRequest } = require_request2(); - var zlib3 = require("node:zlib"); - var { - 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_util2(); - var { kState, kDispatcher } = require_symbols2(); - var assert = require("node:assert"); - var { safelyExtractBody, extractBody } = require_body(); - var { - redirectStatusSet, - nullBodyStatus, - safeMethodsSet, - requestBodyHeader, - subresourceSet - } = require_constants3(); - var EE = require("node:events"); - var { Readable: Readable3, pipeline: pipeline2, finished } = require("node:stream"); - var { addAbortListener, isErrored, isReadable, bufferToLowerCasedHeaderName } = require_util(); - var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url(); - var { getGlobalDispatcher } = require_global2(); - var { webidl } = require_webidl(); - var { STATUS_CODES } = require("node:http"); - var GET_OR_HEAD = ["GET", "HEAD"]; - var defaultUserAgent = typeof __UNDICI_IS_NODE__ !== "undefined" || typeof esbuildDetection !== "undefined" ? "node" : "undici"; - var resolveObjectURL; - var Fetch = class extends EE { - constructor(dispatcher) { - super(); - this.dispatcher = dispatcher; - this.connection = null; - this.dump = false; - this.state = "ongoing"; + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {number} statusCode + * @param {Record} headers + * @param {string} statusMessage + */ + onResponseStart(controller, statusCode, headers, statusMessage) { + this.#responseStarted = true; + this.#statusCode = statusCode; + this.#headers = headers; + this.#statusMessage = statusMessage; + this.#primaryHandler.onResponseStart?.(controller, statusCode, headers, statusMessage); + for (const waitingHandler of this.#waitingHandlers) { + const { handler: handler2, controller: waitingController } = waitingHandler; + if (waitingHandler.done || waitingController.aborted) { + waitingHandler.done = true; + continue; + } + try { + handler2.onResponseStart?.( + waitingController, + statusCode, + headers, + statusMessage + ); + } catch { + } + if (waitingController.aborted) { + waitingHandler.done = true; + } + } + this.#pruneDoneWaitingHandlers(); } - terminate(reason) { - if (this.state !== "ongoing") { + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {Buffer} chunk + */ + onResponseData(controller, chunk) { + if (this.#aborted || this.#completed) { return; } - this.state = "terminated"; - this.connection?.destroy(reason); - this.emit("terminated", reason); + this.#responseDataStarted = true; + this.#primaryHandler.onResponseData?.(controller, chunk); + for (const waitingHandler of this.#waitingHandlers) { + const { handler: handler2, controller: waitingController } = waitingHandler; + if (waitingHandler.done || waitingController.aborted) { + waitingHandler.done = true; + continue; + } + if (waitingController.paused) { + this.#bufferWaitingChunk(waitingHandler, chunk); + continue; + } + try { + handler2.onResponseData?.(waitingController, chunk); + } catch { + } + if (waitingController.aborted) { + waitingHandler.done = true; + waitingHandler.bufferedChunks = []; + waitingHandler.bufferedBytes = 0; + } + } + this.#pruneDoneWaitingHandlers(); } - // https://fetch.spec.whatwg.org/#fetch-controller-abort - abort(error3) { - if (this.state !== "ongoing") { + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {object} trailers + */ + onResponseEnd(controller, trailers) { + if (this.#aborted || this.#completed) { return; } - this.state = "aborted"; - if (!error3) { - error3 = new DOMException("The operation was aborted.", "AbortError"); + this.#completed = true; + this.#primaryHandler.onResponseEnd?.(controller, trailers); + for (const waitingHandler of this.#waitingHandlers) { + if (waitingHandler.done || waitingHandler.controller.aborted) { + waitingHandler.done = true; + continue; + } + this.#flushWaitingHandler(waitingHandler); + if (waitingHandler.done || waitingHandler.controller.aborted) { + waitingHandler.done = true; + continue; + } + if (waitingHandler.controller.paused && waitingHandler.bufferedChunks.length > 0) { + waitingHandler.pendingTrailers = trailers; + continue; + } + try { + waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, trailers); + } catch { + } + waitingHandler.done = true; } - this.serializedAbortReason = error3; - this.connection?.destroy(error3); - this.emit("terminated", error3); - } - }; - function handleFetchDone(response) { - finalizeAndReportTiming(response, "fetch"); - } - function fetch(input, init2 = void 0) { - webidl.argumentLengthCheck(arguments, 1, "globalThis.fetch"); - let p = createDeferredPromise(); - let requestObject; - try { - requestObject = new Request(input, init2); - } catch (e) { - p.reject(e); - return p.promise; - } - const request3 = requestObject[kState]; - if (requestObject.signal.aborted) { - abortFetch(p, request3, null, requestObject.signal.reason); - return p.promise; - } - const globalObject = request3.client.globalObject; - if (globalObject?.constructor?.name === "ServiceWorkerGlobalScope") { - request3.serviceWorkers = "none"; + this.#pruneDoneWaitingHandlers(); + this.#onComplete?.(); } - let responseObject = null; - let locallyAborted = false; - let controller = null; - addAbortListener( - requestObject.signal, - () => { - locallyAborted = true; - assert(controller != null); - controller.abort(requestObject.signal.reason); - const realResponse = responseObject?.deref(); - abortFetch(p, request3, realResponse, requestObject.signal.reason); - } - ); - const processResponse = (response) => { - if (locallyAborted) { + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {Error} err + */ + onResponseError(controller, err) { + if (this.#completed) { return; } - if (response.aborted) { - abortFetch(p, request3, responseObject, controller.serializedAbortReason); + this.#aborted = true; + this.#completed = true; + this.#primaryHandler.onResponseError?.(controller, err); + for (const waitingHandler of this.#waitingHandlers) { + this.#errorWaitingHandler(waitingHandler, err); + } + this.#waitingHandlers = []; + this.#onComplete?.(); + } + /** + * @param {DispatchHandler} handler + * @returns {WaitingHandler} + */ + #createWaitingHandler(handler2) { + const waitingHandler = { + handler: handler2, + controller: null, + bufferedChunks: [], + bufferedBytes: 0, + pendingTrailers: null, + done: false, + pendingStart: false + }; + const state = { + aborted: false, + paused: false, + reason: null + }; + waitingHandler.controller = { + resume: () => { + if (state.aborted) { + return; + } + state.paused = false; + this.#flushWaitingHandler(waitingHandler); + if (this.#completed && waitingHandler.pendingTrailers && waitingHandler.bufferedChunks.length === 0 && !state.paused && !state.aborted) { + try { + waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, waitingHandler.pendingTrailers); + } catch { + } + waitingHandler.pendingTrailers = null; + waitingHandler.done = true; + } + this.#pruneDoneWaitingHandlers(); + }, + pause: () => { + if (!state.aborted) { + state.paused = true; + } + }, + get paused() { + return state.paused; + }, + get aborted() { + return state.aborted; + }, + get reason() { + return state.reason; + }, + abort: (reason) => { + state.aborted = true; + state.reason = reason ?? null; + waitingHandler.done = true; + waitingHandler.pendingTrailers = null; + waitingHandler.bufferedChunks = []; + waitingHandler.bufferedBytes = 0; + } + }; + return waitingHandler; + } + /** + * @param {WaitingHandler} waitingHandler + * @param {Buffer} chunk + */ + #bufferWaitingChunk(waitingHandler, chunk) { + if (waitingHandler.done || waitingHandler.controller.aborted) { + waitingHandler.done = true; + waitingHandler.bufferedChunks = []; + waitingHandler.bufferedBytes = 0; return; } - if (response.type === "error") { - p.reject(new TypeError("fetch failed", { cause: response.error })); - return; + const bufferedChunk = Buffer.from(chunk); + waitingHandler.bufferedChunks.push(bufferedChunk); + waitingHandler.bufferedBytes += bufferedChunk.length; + if (waitingHandler.bufferedBytes > this.#maxBufferSize) { + const err = new RequestAbortedError(`Deduplicated waiting handler exceeded maxBufferSize (${this.#maxBufferSize} bytes) while paused`); + this.#errorWaitingHandler(waitingHandler, err); } - responseObject = new WeakRef(fromInnerResponse(response, "immutable")); - p.resolve(responseObject.deref()); - p = null; - }; - controller = fetching({ - request: request3, - processResponseEndOfBody: handleFetchDone, - processResponse, - dispatcher: requestObject[kDispatcher] - // undici - }); - return p.promise; - } - function finalizeAndReportTiming(response, initiatorType = "other") { - if (response.type === "error" && response.aborted) { - return; - } - if (!response.urlList?.length) { - return; - } - const originalURL = response.urlList[0]; - let timingInfo = response.timingInfo; - let cacheState = response.cacheState; - if (!urlIsHttpHttpsScheme(originalURL)) { - return; - } - if (timingInfo === null) { - return; - } - if (!response.timingAllowPassed) { - timingInfo = createOpaqueTimingInfo({ - startTime: timingInfo.startTime - }); - cacheState = ""; - } - timingInfo.endTime = coarsenedSharedCurrentTime(); - response.timingInfo = timingInfo; - markResourceTiming( - timingInfo, - originalURL.href, - initiatorType, - globalThis, - cacheState - ); - } - var markResourceTiming = performance.markResourceTiming; - function abortFetch(p, request3, responseObject, error3) { - if (p) { - p.reject(error3); } - if (request3.body != null && isReadable(request3.body?.stream)) { - request3.body.stream.cancel(error3).catch((err) => { - if (err.code === "ERR_INVALID_STATE") { - return; + /** + * @param {WaitingHandler} waitingHandler + */ + #flushWaitingHandler(waitingHandler) { + const { handler: handler2, controller } = waitingHandler; + while (!waitingHandler.done && !controller.aborted && !controller.paused && waitingHandler.bufferedChunks.length > 0) { + const bufferedChunk = waitingHandler.bufferedChunks.shift(); + waitingHandler.bufferedBytes -= bufferedChunk.length; + try { + handler2.onResponseData?.(controller, bufferedChunk); + } catch { } - throw err; - }); - } - if (responseObject == null) { - return; - } - const response = responseObject[kState]; - if (response.body != null && isReadable(response.body?.stream)) { - response.body.stream.cancel(error3).catch((err) => { - if (err.code === "ERR_INVALID_STATE") { - return; + if (controller.aborted) { + waitingHandler.done = true; + waitingHandler.pendingTrailers = null; + waitingHandler.bufferedChunks = []; + waitingHandler.bufferedBytes = 0; + break; } - throw err; - }); - } - } - function fetching({ - request: request3, - processRequestBodyChunkLength, - processRequestEndOfBody, - processResponse, - processResponseEndOfBody, - processResponseConsumeBody, - useParallelQueue = false, - dispatcher = getGlobalDispatcher() - // undici - }) { - assert(dispatcher); - let taskDestination = null; - let crossOriginIsolatedCapability = false; - if (request3.client != null) { - taskDestination = request3.client.globalObject; - crossOriginIsolatedCapability = request3.client.crossOriginIsolatedCapability; - } - const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability); - const timingInfo = createOpaqueTimingInfo({ - startTime: currentTime - }); - const fetchParams = { - controller: new Fetch(dispatcher), - request: request3, - timingInfo, - processRequestBodyChunkLength, - processRequestEndOfBody, - processResponse, - processResponseConsumeBody, - processResponseEndOfBody, - taskDestination, - crossOriginIsolatedCapability - }; - assert(!request3.body || request3.body.stream); - if (request3.window === "client") { - request3.window = request3.client?.globalObject?.constructor?.name === "Window" ? request3.client : "no-window"; - } - if (request3.origin === "client") { - request3.origin = request3.client.origin; - } - if (request3.policyContainer === "client") { - if (request3.client != null) { - request3.policyContainer = clonePolicyContainer( - request3.client.policyContainer - ); - } else { - request3.policyContainer = makePolicyContainer(); } } - if (!request3.headersList.contains("accept", true)) { - const value = "*/*"; - request3.headersList.append("accept", value, true); - } - if (!request3.headersList.contains("accept-language", true)) { - request3.headersList.append("accept-language", "*", true); - } - if (request3.priority === null) { - } - if (subresourceSet.has(request3.destination)) { - } - mainFetch(fetchParams).catch((err) => { - fetchParams.controller.terminate(err); - }); - return fetchParams.controller; - } - async function mainFetch(fetchParams, recursive = false) { - const request3 = fetchParams.request; - let response = null; - if (request3.localURLsOnly && !urlIsLocal(requestCurrentURL(request3))) { - response = makeNetworkError("local URLs only"); - } - tryUpgradeRequestToAPotentiallyTrustworthyURL(request3); - if (requestBadPort(request3) === "blocked") { - response = makeNetworkError("bad port"); - } - if (request3.referrerPolicy === "") { - request3.referrerPolicy = request3.policyContainer.referrerPolicy; + /** + * @param {WaitingHandler} waitingHandler + * @param {Error} err + */ + #errorWaitingHandler(waitingHandler, err) { + if (waitingHandler.done) { + return; + } + waitingHandler.done = true; + waitingHandler.pendingTrailers = null; + waitingHandler.bufferedChunks = []; + waitingHandler.bufferedBytes = 0; + try { + waitingHandler.controller.abort(err); + waitingHandler.handler.onResponseError?.(waitingHandler.controller, err); + } catch { + } } - if (request3.referrer !== "no-referrer") { - request3.referrer = determineRequestsReferrer(request3); + #pruneDoneWaitingHandlers() { + this.#waitingHandlers = this.#waitingHandlers.filter((waitingHandler) => waitingHandler.done === false); } - if (response === null) { - response = await (async () => { - const currentURL = requestCurrentURL(request3); - if ( - // - request’s current URL’s origin is same origin with request’s origin, - // and request’s response tainting is "basic" - sameOrigin(currentURL, request3.url) && request3.responseTainting === "basic" || // request’s current URL’s scheme is "data" - currentURL.protocol === "data:" || // - request’s mode is "navigate" or "websocket" - (request3.mode === "navigate" || request3.mode === "websocket") - ) { - request3.responseTainting = "basic"; - return await schemeFetch(fetchParams); + }; + module2.exports = DeduplicationHandler; + } +}); + +// node_modules/undici/lib/interceptor/deduplicate.js +var require_deduplicate = __commonJS({ + "node_modules/undici/lib/interceptor/deduplicate.js"(exports2, module2) { + "use strict"; + var diagnosticsChannel = require("node:diagnostics_channel"); + var util4 = require_util(); + var DeduplicationHandler = require_deduplication_handler(); + var { normalizeHeaders, makeCacheKey, makeDeduplicationKey } = require_cache(); + var pendingRequestsChannel = diagnosticsChannel.channel("undici:request:pending-requests"); + module2.exports = (opts = {}) => { + const { + methods = ["GET"], + skipHeaderNames = [], + excludeHeaderNames = [], + maxBufferSize = 5 * 1024 * 1024 + } = opts; + if (typeof opts !== "object" || opts === null) { + throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`); + } + if (!Array.isArray(methods)) { + throw new TypeError(`expected opts.methods to be an array, got ${typeof methods}`); + } + for (const method of methods) { + if (!util4.safeHTTPMethods.includes(method)) { + throw new TypeError(`expected opts.methods to only contain safe HTTP methods, got ${method}`); + } + } + if (!Array.isArray(skipHeaderNames)) { + throw new TypeError(`expected opts.skipHeaderNames to be an array, got ${typeof skipHeaderNames}`); + } + if (!Array.isArray(excludeHeaderNames)) { + throw new TypeError(`expected opts.excludeHeaderNames to be an array, got ${typeof excludeHeaderNames}`); + } + if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) { + throw new TypeError(`expected opts.maxBufferSize to be a positive finite number, got ${maxBufferSize}`); + } + const skipHeaderNamesSet = new Set(skipHeaderNames.map((name) => name.toLowerCase())); + const excludeHeaderNamesSet = new Set(excludeHeaderNames.map((name) => name.toLowerCase())); + const pendingRequests = /* @__PURE__ */ new Map(); + return (dispatch) => { + return (opts2, handler2) => { + if (!opts2.origin || methods.includes(opts2.method) === false) { + return dispatch(opts2, handler2); } - if (request3.mode === "same-origin") { - return makeNetworkError('request mode cannot be "same-origin"'); + opts2 = { + ...opts2, + headers: normalizeHeaders(opts2) + }; + if (skipHeaderNamesSet.size > 0) { + for (const headerName of Object.keys(opts2.headers)) { + if (skipHeaderNamesSet.has(headerName.toLowerCase())) { + return dispatch(opts2, handler2); + } + } } - if (request3.mode === "no-cors") { - if (request3.redirect !== "follow") { - return makeNetworkError( - 'redirect mode cannot be "follow" for "no-cors" request' - ); + const cacheKey3 = makeCacheKey(opts2); + const dedupeKey = makeDeduplicationKey(cacheKey3, excludeHeaderNamesSet); + const pendingHandler = pendingRequests.get(dedupeKey); + if (pendingHandler) { + if (pendingHandler.addWaitingHandler(handler2)) { + return true; } - request3.responseTainting = "opaque"; - return await schemeFetch(fetchParams); + return dispatch(opts2, handler2); } - if (!urlIsHttpHttpsScheme(requestCurrentURL(request3))) { - return makeNetworkError("URL scheme must be a HTTP(S) scheme"); + const deduplicationHandler = new DeduplicationHandler( + handler2, + () => { + pendingRequests.delete(dedupeKey); + if (pendingRequestsChannel.hasSubscribers) { + pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: "removed" }); + } + }, + maxBufferSize + ); + pendingRequests.set(dedupeKey, deduplicationHandler); + if (pendingRequestsChannel.hasSubscribers) { + pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: "added" }); } - request3.responseTainting = "cors"; - return await httpFetch(fetchParams); - })(); - } - if (recursive) { - return response; - } - if (response.status !== 0 && !response.internalResponse) { - if (request3.responseTainting === "cors") { - } - if (request3.responseTainting === "basic") { - response = filterResponse(response, "basic"); - } else if (request3.responseTainting === "cors") { - response = filterResponse(response, "cors"); - } else if (request3.responseTainting === "opaque") { - response = filterResponse(response, "opaque"); - } else { - assert(false); - } - } - let internalResponse = response.status === 0 ? response : response.internalResponse; - if (internalResponse.urlList.length === 0) { - internalResponse.urlList.push(...request3.urlList); - } - if (!request3.timingAllowFailed) { - response.timingAllowPassed = true; + return dispatch(opts2, deduplicationHandler); + }; + }; + }; + } +}); + +// node_modules/undici/lib/cache/sqlite-cache-store.js +var require_sqlite_cache_store = __commonJS({ + "node_modules/undici/lib/cache/sqlite-cache-store.js"(exports2, module2) { + "use strict"; + var { Writable } = require("node:stream"); + var { assertCacheKey, assertCacheValue } = require_cache(); + var DatabaseSync; + var VERSION8 = 3; + var MAX_ENTRY_SIZE = 2 * 1e3 * 1e3 * 1e3; + module2.exports = class SqliteCacheStore { + #maxEntrySize = MAX_ENTRY_SIZE; + #maxCount = Infinity; + /** + * @type {import('node:sqlite').DatabaseSync} + */ + #db; + /** + * @type {import('node:sqlite').StatementSync} + */ + #getValuesQuery; + /** + * @type {import('node:sqlite').StatementSync} + */ + #updateValueQuery; + /** + * @type {import('node:sqlite').StatementSync} + */ + #insertValueQuery; + /** + * @type {import('node:sqlite').StatementSync} + */ + #deleteExpiredValuesQuery; + /** + * @type {import('node:sqlite').StatementSync} + */ + #deleteByUrlQuery; + /** + * @type {import('node:sqlite').StatementSync} + */ + #countEntriesQuery; + /** + * @type {import('node:sqlite').StatementSync | null} + */ + #deleteOldValuesQuery; + /** + * @param {import('../../types/cache-interceptor.d.ts').default.SqliteCacheStoreOpts | undefined} opts + */ + constructor(opts) { + if (opts) { + if (typeof opts !== "object") { + throw new TypeError("SqliteCacheStore options must be an object"); + } + if (opts.maxEntrySize !== void 0) { + if (typeof opts.maxEntrySize !== "number" || !Number.isInteger(opts.maxEntrySize) || opts.maxEntrySize < 0) { + throw new TypeError("SqliteCacheStore options.maxEntrySize must be a non-negative integer"); + } + if (opts.maxEntrySize > MAX_ENTRY_SIZE) { + throw new TypeError("SqliteCacheStore options.maxEntrySize must be less than 2gb"); + } + this.#maxEntrySize = opts.maxEntrySize; + } + if (opts.maxCount !== void 0) { + if (typeof opts.maxCount !== "number" || !Number.isInteger(opts.maxCount) || opts.maxCount < 0) { + throw new TypeError("SqliteCacheStore options.maxCount must be a non-negative integer"); + } + this.#maxCount = opts.maxCount; + } + } + if (!DatabaseSync) { + DatabaseSync = require("node:sqlite").DatabaseSync; + } + this.#db = new DatabaseSync(opts?.location ?? ":memory:"); + this.#db.exec(` + PRAGMA journal_mode = WAL; + PRAGMA synchronous = NORMAL; + PRAGMA temp_store = memory; + PRAGMA optimize; + + CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION8} ( + -- Data specific to us + id INTEGER PRIMARY KEY AUTOINCREMENT, + url TEXT NOT NULL, + method TEXT NOT NULL, + + -- Data returned to the interceptor + body BUF NULL, + deleteAt INTEGER NOT NULL, + statusCode INTEGER NOT NULL, + statusMessage TEXT NOT NULL, + headers TEXT NULL, + cacheControlDirectives TEXT NULL, + etag TEXT NULL, + vary TEXT NULL, + cachedAt INTEGER NOT NULL, + staleAt INTEGER NOT NULL + ); + + CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION8}_getValuesQuery ON cacheInterceptorV${VERSION8}(url, method, deleteAt); + CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION8}_deleteByUrlQuery ON cacheInterceptorV${VERSION8}(deleteAt); + `); + this.#getValuesQuery = this.#db.prepare(` + SELECT + id, + body, + deleteAt, + statusCode, + statusMessage, + headers, + etag, + cacheControlDirectives, + vary, + cachedAt, + staleAt + FROM cacheInterceptorV${VERSION8} + WHERE + url = ? + AND method = ? + ORDER BY + deleteAt ASC + `); + this.#updateValueQuery = this.#db.prepare(` + UPDATE cacheInterceptorV${VERSION8} SET + body = ?, + deleteAt = ?, + statusCode = ?, + statusMessage = ?, + headers = ?, + etag = ?, + cacheControlDirectives = ?, + cachedAt = ?, + staleAt = ? + WHERE + id = ? + `); + this.#insertValueQuery = this.#db.prepare(` + INSERT INTO cacheInterceptorV${VERSION8} ( + url, + method, + body, + deleteAt, + statusCode, + statusMessage, + headers, + etag, + cacheControlDirectives, + vary, + cachedAt, + staleAt + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + this.#deleteByUrlQuery = this.#db.prepare( + `DELETE FROM cacheInterceptorV${VERSION8} WHERE url = ?` + ); + this.#countEntriesQuery = this.#db.prepare( + `SELECT COUNT(*) AS total FROM cacheInterceptorV${VERSION8}` + ); + this.#deleteExpiredValuesQuery = this.#db.prepare( + `DELETE FROM cacheInterceptorV${VERSION8} WHERE deleteAt <= ?` + ); + this.#deleteOldValuesQuery = this.#maxCount === Infinity ? null : this.#db.prepare(` + DELETE FROM cacheInterceptorV${VERSION8} + WHERE id IN ( + SELECT + id + FROM cacheInterceptorV${VERSION8} + ORDER BY cachedAt ASC + LIMIT ? + ) + `); } - if (response.type === "opaque" && internalResponse.status === 206 && internalResponse.rangeRequested && !request3.headers.contains("range", true)) { - response = internalResponse = makeNetworkError(); + close() { + this.#db.close(); } - if (response.status !== 0 && (request3.method === "HEAD" || request3.method === "CONNECT" || nullBodyStatus.includes(internalResponse.status))) { - internalResponse.body = null; - fetchParams.controller.dump = true; + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @returns {(import('../../types/cache-interceptor.d.ts').default.GetResult & { body?: Buffer }) | undefined} + */ + get(key) { + assertCacheKey(key); + const value = this.#findValue(key); + return value ? { + body: value.body ? Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength) : void 0, + statusCode: value.statusCode, + statusMessage: value.statusMessage, + headers: value.headers ? JSON.parse(value.headers) : void 0, + etag: value.etag ? value.etag : void 0, + vary: value.vary ? JSON.parse(value.vary) : void 0, + cacheControlDirectives: value.cacheControlDirectives ? JSON.parse(value.cacheControlDirectives) : void 0, + cachedAt: value.cachedAt, + staleAt: value.staleAt, + deleteAt: value.deleteAt + } : void 0; } - if (request3.integrity) { - const processBodyError = (reason) => fetchFinale(fetchParams, makeNetworkError(reason)); - if (request3.responseTainting === "opaque" || response.body == null) { - processBodyError(response.error); + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue & { body: null | Buffer | Array}} value + */ + set(key, value) { + assertCacheKey(key); + const url2 = this.#makeValueUrl(key); + const body = Array.isArray(value.body) ? Buffer.concat(value.body) : value.body; + const size = body?.byteLength; + if (size && size > this.#maxEntrySize) { return; } - const processBody = (bytes) => { - if (!bytesMatch(bytes, request3.integrity)) { - processBodyError("integrity mismatch"); - return; + const existingValue = this.#findValue(key, true); + if (existingValue) { + this.#updateValueQuery.run( + body, + value.deleteAt, + value.statusCode, + value.statusMessage, + value.headers ? JSON.stringify(value.headers) : null, + value.etag ? value.etag : null, + value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null, + value.cachedAt, + value.staleAt, + existingValue.id + ); + } else { + this.#insertValueQuery.run( + url2, + key.method, + body, + value.deleteAt, + value.statusCode, + value.statusMessage, + value.headers ? JSON.stringify(value.headers) : null, + value.etag ? value.etag : null, + value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null, + value.vary ? JSON.stringify(value.vary) : null, + value.cachedAt, + value.staleAt + ); + this.#prune(); + } + } + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} value + * @returns {Writable | undefined} + */ + createWriteStream(key, value) { + assertCacheKey(key); + assertCacheValue(value); + let size = 0; + const body = []; + const store = this; + return new Writable({ + decodeStrings: true, + write(chunk, encoding, callback) { + size += chunk.byteLength; + if (size < store.#maxEntrySize) { + body.push(chunk); + } else { + this.destroy(); + } + callback(); + }, + final(callback) { + store.set(key, { ...value, body }); + callback(); } - response.body = safelyExtractBody(bytes)[0]; - fetchFinale(fetchParams, response); - }; - await fullyReadBody(response.body, processBody, processBodyError); - } else { - fetchFinale(fetchParams, response); + }); } - } - function schemeFetch(fetchParams) { - if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { - return Promise.resolve(makeAppropriateNetworkError(fetchParams)); + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + */ + delete(key) { + if (typeof key !== "object") { + throw new TypeError(`expected key to be object, got ${typeof key}`); + } + this.#deleteByUrlQuery.run(this.#makeValueUrl(key)); } - const { request: request3 } = fetchParams; - const { protocol: scheme } = requestCurrentURL(request3); - switch (scheme) { - case "about:": { - return Promise.resolve(makeNetworkError("about scheme is not supported")); + #prune() { + if (Number.isFinite(this.#maxCount) && this.size <= this.#maxCount) { + return 0; } - case "blob:": { - if (!resolveObjectURL) { - resolveObjectURL = require("node:buffer").resolveObjectURL; - } - const blobURLEntry = requestCurrentURL(request3); - if (blobURLEntry.search.length !== 0) { - return Promise.resolve(makeNetworkError("NetworkError when attempting to fetch resource.")); - } - const blob = resolveObjectURL(blobURLEntry.toString()); - if (request3.method !== "GET" || !isBlobLike(blob)) { - return Promise.resolve(makeNetworkError("invalid method")); - } - const response = makeResponse(); - const fullLength = blob.size; - const serializedFullLength = isomorphicEncode(`${fullLength}`); - const type = blob.type; - if (!request3.headersList.contains("range", true)) { - const bodyWithType = extractBody(blob); - response.statusText = "OK"; - response.body = bodyWithType[0]; - response.headersList.set("content-length", serializedFullLength, true); - response.headersList.set("content-type", type, true); - } else { - response.rangeRequested = true; - const rangeHeader = request3.headersList.get("range", true); - const rangeValue = simpleRangeHeaderValue(rangeHeader, true); - if (rangeValue === "failure") { - return Promise.resolve(makeNetworkError("failed to fetch the data URL")); - } - let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue; - if (rangeStart === null) { - rangeStart = fullLength - rangeEnd; - rangeEnd = rangeStart + rangeEnd - 1; - } else { - if (rangeStart >= fullLength) { - return Promise.resolve(makeNetworkError("Range start is greater than the blob's size.")); - } - if (rangeEnd === null || rangeEnd >= fullLength) { - rangeEnd = fullLength - 1; - } - } - const slicedBlob = blob.slice(rangeStart, rangeEnd, type); - const slicedBodyWithType = extractBody(slicedBlob); - response.body = slicedBodyWithType[0]; - const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`); - const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength); - response.status = 206; - response.statusText = "Partial Content"; - response.headersList.set("content-length", serializedSlicedLength, true); - response.headersList.set("content-type", type, true); - response.headersList.set("content-range", contentRange, true); + { + const removed = this.#deleteExpiredValuesQuery.run(Date.now()).changes; + if (removed) { + return removed; } - return Promise.resolve(response); } - case "data:": { - const currentURL = requestCurrentURL(request3); - const dataURLStruct = dataURLProcessor(currentURL); - if (dataURLStruct === "failure") { - return Promise.resolve(makeNetworkError("failed to fetch the data URL")); + { + const removed = this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount * 0.1), 1)).changes; + if (removed) { + return removed; } - const mimeType = serializeAMimeType(dataURLStruct.mimeType); - return Promise.resolve(makeResponse({ - statusText: "OK", - headersList: [ - ["content-type", { name: "Content-Type", value: mimeType }] - ], - body: safelyExtractBody(dataURLStruct.body)[0] - })); - } - case "file:": { - return Promise.resolve(makeNetworkError("not implemented... yet...")); - } - case "http:": - case "https:": { - return httpFetch(fetchParams).catch((err) => makeNetworkError(err)); - } - default: { - return Promise.resolve(makeNetworkError("unknown scheme")); } + return 0; } - } - function finalizeResponse(fetchParams, response) { - fetchParams.request.done = true; - if (fetchParams.processResponseDone != null) { - queueMicrotask(() => fetchParams.processResponseDone(response)); + /** + * Counts the number of rows in the cache + * @returns {Number} + */ + get size() { + const { total } = this.#countEntriesQuery.get(); + return total; } - } - function fetchFinale(fetchParams, response) { - let timingInfo = fetchParams.timingInfo; - const processResponseEndOfBody = () => { - const unsafeEndTime = Date.now(); - if (fetchParams.request.destination === "document") { - fetchParams.controller.fullTimingInfo = timingInfo; + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @returns {string} + */ + #makeValueUrl(key) { + return `${key.origin}/${key.path}`; + } + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {boolean} [canBeExpired=false] + * @returns {SqliteStoreValue | undefined} + */ + #findValue(key, canBeExpired = false) { + const url2 = this.#makeValueUrl(key); + const { headers, method } = key; + const values = this.#getValuesQuery.all(url2, method); + if (values.length === 0) { + return void 0; } - fetchParams.controller.reportTimingSteps = () => { - if (fetchParams.request.url.protocol !== "https:") { - return; - } - timingInfo.endTime = unsafeEndTime; - let cacheState = response.cacheState; - const bodyInfo = response.bodyInfo; - if (!response.timingAllowPassed) { - timingInfo = createOpaqueTimingInfo(timingInfo); - cacheState = ""; + const now = Date.now(); + for (const value of values) { + if (now >= value.deleteAt && !canBeExpired) { + continue; } - let responseStatus = 0; - if (fetchParams.request.mode !== "navigator" || !response.hasCrossOriginRedirects) { - responseStatus = response.status; - const mimeType = extractMimeType(response.headersList); - if (mimeType !== "failure") { - bodyInfo.contentType = minimizeSupportedMimeType(mimeType); + let matches = true; + if (value.vary) { + const vary = JSON.parse(value.vary); + for (const header in vary) { + if (!headerValueEquals(headers[header], vary[header])) { + matches = false; + break; + } } } - if (fetchParams.request.initiatorType != null) { - markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus); - } - }; - const processResponseEndOfBodyTask = () => { - fetchParams.request.done = true; - if (fetchParams.processResponseEndOfBody != null) { - queueMicrotask(() => fetchParams.processResponseEndOfBody(response)); - } - if (fetchParams.request.initiatorType != null) { - fetchParams.controller.reportTimingSteps(); + if (matches) { + return value; } - }; - queueMicrotask(() => processResponseEndOfBodyTask()); - }; - if (fetchParams.processResponse != null) { - queueMicrotask(() => { - fetchParams.processResponse(response); - fetchParams.processResponse = null; - }); - } - const internalResponse = response.type === "error" ? response : response.internalResponse ?? response; - if (internalResponse.body == null) { - processResponseEndOfBody(); - } else { - finished(internalResponse.body.stream, () => { - processResponseEndOfBody(); - }); - } - } - async function httpFetch(fetchParams) { - const request3 = fetchParams.request; - let response = null; - let actualResponse = null; - const timingInfo = fetchParams.timingInfo; - if (request3.serviceWorkers === "all") { - } - if (response === null) { - if (request3.redirect === "follow") { - request3.serviceWorkers = "none"; - } - actualResponse = response = await httpNetworkOrCacheFetch(fetchParams); - if (request3.responseTainting === "cors" && corsCheck(request3, response) === "failure") { - return makeNetworkError("cors failure"); - } - if (TAOCheck(request3, response) === "failure") { - request3.timingAllowFailed = true; } + return void 0; } - if ((request3.responseTainting === "opaque" || response.type === "opaque") && crossOriginResourcePolicyCheck( - request3.origin, - request3.client, - request3.destination, - actualResponse - ) === "blocked") { - return makeNetworkError("blocked"); + }; + function headerValueEquals(lhs, rhs) { + if (lhs == null && rhs == null) { + return true; } - if (redirectStatusSet.has(actualResponse.status)) { - if (request3.redirect !== "manual") { - fetchParams.controller.connection.destroy(void 0, false); + if (lhs == null && rhs != null || lhs != null && rhs == null) { + return false; + } + if (Array.isArray(lhs) && Array.isArray(rhs)) { + if (lhs.length !== rhs.length) { + return false; } - if (request3.redirect === "error") { - response = makeNetworkError("unexpected redirect"); - } else if (request3.redirect === "manual") { - response = actualResponse; - } else if (request3.redirect === "follow") { - response = await httpRedirectFetch(fetchParams, response); - } else { - assert(false); + for (let i = 0; i < lhs.length; i++) { + if (lhs[i] !== rhs[i]) { + return false; + } } + return true; } - response.timingInfo = timingInfo; - return response; + return lhs === rhs; } - function httpRedirectFetch(fetchParams, response) { - const request3 = fetchParams.request; - const actualResponse = response.internalResponse ? response.internalResponse : response; - let locationURL; - try { - locationURL = responseLocationURL( - actualResponse, - requestCurrentURL(request3).hash - ); - if (locationURL == null) { - return response; + } +}); + +// node_modules/undici/lib/web/fetch/headers.js +var require_headers = __commonJS({ + "node_modules/undici/lib/web/fetch/headers.js"(exports2, module2) { + "use strict"; + var { kConstruct } = require_symbols(); + var { kEnumerableProperty } = require_util(); + var { + iteratorMixin, + isValidHeaderName, + isValidHeaderValue + } = require_util2(); + var { webidl } = require_webidl(); + var assert = require("node:assert"); + var util4 = require("node:util"); + function isHTTPWhiteSpaceCharCode(code) { + return code === 10 || code === 13 || code === 9 || code === 32; + } + function headerValueNormalize(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, object2) { + if (Array.isArray(object2)) { + for (let i = 0; i < object2.length; ++i) { + const header = object2[i]; + if (header.length !== 2) { + throw webidl.errors.exception({ + header: "Headers constructor", + message: `expected name/value pair to be length 2, found ${header.length}.` + }); + } + appendHeader(headers, header[0], header[1]); } - } catch (err) { - return Promise.resolve(makeNetworkError(err)); - } - if (!urlIsHttpHttpsScheme(locationURL)) { - return Promise.resolve(makeNetworkError("URL scheme must be a HTTP(S) scheme")); - } - if (request3.redirectCount === 20) { - return Promise.resolve(makeNetworkError("redirect count exceeded")); - } - request3.redirectCount += 1; - if (request3.mode === "cors" && (locationURL.username || locationURL.password) && !sameOrigin(request3, locationURL)) { - return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')); - } - if (request3.responseTainting === "cors" && (locationURL.username || locationURL.password)) { - return Promise.resolve(makeNetworkError( - 'URL cannot contain credentials for request mode "cors"' - )); - } - if (actualResponse.status !== 303 && request3.body != null && request3.body.source == null) { - return Promise.resolve(makeNetworkError()); - } - if ([301, 302].includes(actualResponse.status) && request3.method === "POST" || actualResponse.status === 303 && !GET_OR_HEAD.includes(request3.method)) { - request3.method = "GET"; - request3.body = null; - for (const headerName of requestBodyHeader) { - request3.headersList.delete(headerName); + } else if (typeof object2 === "object" && object2 !== null) { + const keys = Object.keys(object2); + for (let i = 0; i < keys.length; ++i) { + appendHeader(headers, keys[i], object2[keys[i]]); } - } - if (!sameOrigin(requestCurrentURL(request3), locationURL)) { - request3.headersList.delete("authorization", true); - request3.headersList.delete("proxy-authorization", true); - request3.headersList.delete("cookie", true); - request3.headersList.delete("host", true); - } - if (request3.body != null) { - assert(request3.body.source != null); - request3.body = safelyExtractBody(request3.body.source)[0]; - } - const timingInfo = fetchParams.timingInfo; - timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability); - if (timingInfo.redirectStartTime === 0) { - timingInfo.redirectStartTime = timingInfo.startTime; - } - request3.urlList.push(locationURL); - setRequestReferrerPolicyOnRedirect(request3, actualResponse); - return mainFetch(fetchParams, true); - } - async function httpNetworkOrCacheFetch(fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false) { - const request3 = fetchParams.request; - let httpFetchParams = null; - let httpRequest = null; - let response = null; - const httpCache = null; - const revalidatingFlag = false; - if (request3.window === "no-window" && request3.redirect === "error") { - httpFetchParams = fetchParams; - httpRequest = request3; } else { - httpRequest = cloneRequest(request3); - httpFetchParams = { ...fetchParams }; - httpFetchParams.request = httpRequest; - } - const includeCredentials = request3.credentials === "include" || request3.credentials === "same-origin" && request3.responseTainting === "basic"; - const contentLength = httpRequest.body ? httpRequest.body.length : null; - let contentLengthHeaderValue = null; - if (httpRequest.body == null && ["POST", "PUT"].includes(httpRequest.method)) { - contentLengthHeaderValue = "0"; - } - if (contentLength != null) { - contentLengthHeaderValue = isomorphicEncode(`${contentLength}`); - } - if (contentLengthHeaderValue != null) { - httpRequest.headersList.append("content-length", contentLengthHeaderValue, true); + throw webidl.errors.conversionFailed({ + prefix: "Headers constructor", + argument: "Argument 1", + types: ["sequence>", "record"] + }); } - if (contentLength != null && httpRequest.keepalive) { + } + function appendHeader(headers, name, value) { + value = headerValueNormalize(value); + 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" + }); } - if (httpRequest.referrer instanceof URL) { - httpRequest.headersList.append("referer", isomorphicEncode(httpRequest.referrer.href), true); + if (getHeadersGuard(headers) === "immutable") { + throw new TypeError("immutable"); } - appendRequestOriginHeader(httpRequest); - appendFetchMetadata(httpRequest); - if (!httpRequest.headersList.contains("user-agent", true)) { - httpRequest.headersList.append("user-agent", defaultUserAgent); + return getHeadersList(headers).append(name, value, false); + } + function headersListSortAndCombine(target) { + const headersList = getHeadersList(target); + if (!headersList) { + return []; } - 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"; + if (headersList.sortedMap) { + return headersList.sortedMap; } - if (httpRequest.cache === "no-cache" && !httpRequest.preventNoCacheCacheControlHeaderModification && !httpRequest.headersList.contains("cache-control", true)) { - httpRequest.headersList.append("cache-control", "max-age=0", true); + const headers = []; + const names = headersList.toSortedArray(); + const cookies = headersList.cookies; + if (cookies === null || cookies.length === 1) { + return headersList.sortedMap = names; } - if (httpRequest.cache === "no-store" || httpRequest.cache === "reload") { - if (!httpRequest.headersList.contains("pragma", true)) { - httpRequest.headersList.append("pragma", "no-cache", true); - } - if (!httpRequest.headersList.contains("cache-control", true)) { - httpRequest.headersList.append("cache-control", "no-cache", true); + for (let i = 0; i < names.length; ++i) { + const { 0: name, 1: value } = names[i]; + if (name === "set-cookie") { + for (let j = 0; j < cookies.length; ++j) { + headers.push([name, cookies[j]]); + } + } else { + headers.push([name, value]); } } - if (httpRequest.headersList.contains("range", true)) { - httpRequest.headersList.append("accept-encoding", "identity", true); - } - if (!httpRequest.headersList.contains("accept-encoding", true)) { - if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { - httpRequest.headersList.append("accept-encoding", "br, gzip, deflate", true); + return headersList.sortedMap = headers; + } + function compareHeaderName(a, b) { + return a[0] < b[0] ? -1 : 1; + } + var HeadersList = class _HeadersList { + /** @type {[string, string][]|null} */ + cookies = null; + sortedMap; + headersMap; + constructor(init2) { + if (init2 instanceof _HeadersList) { + this.headersMap = new Map(init2.headersMap); + this.sortedMap = init2.sortedMap; + this.cookies = init2.cookies === null ? null : [...init2.cookies]; } else { - httpRequest.headersList.append("accept-encoding", "gzip, deflate", true); + this.headersMap = new Map(init2); + this.sortedMap = null; } } - httpRequest.headersList.delete("host", true); - if (includeCredentials) { - } - if (httpCache == null) { - httpRequest.cache = "no-store"; + /** + * @see https://fetch.spec.whatwg.org/#header-list-contains + * @param {string} name + * @param {boolean} isLowerCase + */ + contains(name, isLowerCase) { + return this.headersMap.has(isLowerCase ? name : name.toLowerCase()); } - if (httpRequest.cache !== "no-store" && httpRequest.cache !== "reload") { + clear() { + this.headersMap.clear(); + this.sortedMap = null; + this.cookies = null; } - if (response == null) { - if (httpRequest.cache === "only-if-cached") { - return makeNetworkError("only if cached"); + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-append + * @param {string} name + * @param {string} value + * @param {boolean} isLowerCase + */ + append(name, value, isLowerCase) { + this.sortedMap = null; + const lowercaseName = isLowerCase ? name : name.toLowerCase(); + const exists = this.headersMap.get(lowercaseName); + if (exists) { + const delimiter = lowercaseName === "cookie" ? "; " : ", "; + this.headersMap.set(lowercaseName, { + name: exists.name, + value: `${exists.value}${delimiter}${value}` + }); + } else { + this.headersMap.set(lowercaseName, { name, value }); } - const forwardResponse = await httpNetworkFetch( - httpFetchParams, - includeCredentials, - isNewConnectionFetch - ); - if (!safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399) { + if (lowercaseName === "set-cookie") { + (this.cookies ??= []).push(value); } - if (revalidatingFlag && forwardResponse.status === 304) { + } + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-set + * @param {string} name + * @param {string} value + * @param {boolean} isLowerCase + */ + set(name, value, isLowerCase) { + this.sortedMap = null; + const lowercaseName = isLowerCase ? name : name.toLowerCase(); + if (lowercaseName === "set-cookie") { + this.cookies = [value]; } - if (response == null) { - response = forwardResponse; + this.headersMap.set(lowercaseName, { name, value }); + } + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-delete + * @param {string} name + * @param {boolean} isLowerCase + */ + delete(name, isLowerCase) { + this.sortedMap = null; + if (!isLowerCase) name = name.toLowerCase(); + if (name === "set-cookie") { + this.cookies = null; } + this.headersMap.delete(name); } - response.urlList = [...httpRequest.urlList]; - if (httpRequest.headersList.contains("range", true)) { - response.rangeRequested = true; + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-get + * @param {string} name + * @param {boolean} isLowerCase + * @returns {string | null} + */ + get(name, isLowerCase) { + return this.headersMap.get(isLowerCase ? name : name.toLowerCase())?.value ?? null; } - response.requestIncludesCredentials = includeCredentials; - if (response.status === 407) { - if (request3.window === "no-window") { - return makeNetworkError(); - } - if (isCancelled(fetchParams)) { - return makeAppropriateNetworkError(fetchParams); + *[Symbol.iterator]() { + for (const { 0: name, 1: { value } } of this.headersMap) { + yield [name, value]; } - return makeNetworkError("proxy authentication required"); } - 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 - (request3.body == null || request3.body.source != null) - ) { - if (isCancelled(fetchParams)) { - return makeAppropriateNetworkError(fetchParams); + get entries() { + const headers = {}; + if (this.headersMap.size !== 0) { + for (const { name, value } of this.headersMap.values()) { + headers[name] = value; + } } - fetchParams.controller.connection.destroy(); - response = await httpNetworkOrCacheFetch( - fetchParams, - isAuthenticationFetch, - true - ); + return headers; } - if (isAuthenticationFetch) { + rawValues() { + return this.headersMap.values(); } - return response; - } - 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")); + get entriesList() { + const headers = []; + if (this.headersMap.size !== 0) { + for (const { 0: lowerName, 1: { name, value } } of this.headersMap) { + if (lowerName === "set-cookie") { + for (const cookie of this.cookies) { + headers.push([name, cookie]); + } + } else { + headers.push([name, value]); } } } - }; - const request3 = fetchParams.request; - let response = null; - const timingInfo = fetchParams.timingInfo; - const httpCache = null; - if (httpCache == null) { - request3.cache = "no-store"; + return headers; } - const newConnection = forceNewConnection ? "yes" : "no"; - if (request3.mode === "websocket") { - } else { - } - let requestBody = null; - if (request3.body == null && fetchParams.processRequestEndOfBody) { - queueMicrotask(() => fetchParams.processRequestEndOfBody()); - } else if (request3.body != null) { - const processBodyChunk = async function* (bytes) { - if (isCancelled(fetchParams)) { - return; - } - yield bytes; - fetchParams.processRequestBodyChunkLength?.(bytes.byteLength); - }; - const processEndOfBody = () => { - if (isCancelled(fetchParams)) { - return; - } - if (fetchParams.processRequestEndOfBody) { - fetchParams.processRequestEndOfBody(); + // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set + toSortedArray() { + const size = this.headersMap.size; + const array2 = new Array(size); + if (size <= 32) { + if (size === 0) { + return array2; } - }; - const processBodyError = (e) => { - if (isCancelled(fetchParams)) { - return; + const iterator2 = this.headersMap[Symbol.iterator](); + const firstValue = iterator2.next().value; + array2[0] = [firstValue[0], firstValue[1].value]; + assert(firstValue[1].value !== null); + for (let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value; i < size; ++i) { + value = iterator2.next().value; + x = array2[i] = [value[0], value[1].value]; + assert(x[1] !== null); + left = 0; + right = i; + while (left < right) { + pivot = left + (right - left >> 1); + if (array2[pivot][0] <= x[0]) { + left = pivot + 1; + } else { + right = pivot; + } + } + if (i !== pivot) { + j = i; + while (j > left) { + array2[j] = array2[--j]; + } + array2[left] = x; + } } - if (e.name === "AbortError") { - fetchParams.controller.abort(); - } else { - fetchParams.controller.terminate(e); + if (!iterator2.next().done) { + throw new TypeError("Unreachable"); } - }; - requestBody = (async function* () { - try { - for await (const bytes of request3.body.stream) { - yield* processBodyChunk(bytes); - } - processEndOfBody(); - } catch (err) { - processBodyError(err); + return array2; + } else { + let i = 0; + for (const { 0: name, 1: { value } } of this.headersMap) { + array2[i++] = [name, value]; + assert(value !== null); } - })(); + return array2.sort(compareHeaderName); + } } - try { - const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }); - if (socket) { - response = makeResponse({ status, statusText, headersList, socket }); - } else { - const iterator2 = body[Symbol.asyncIterator](); - fetchParams.controller.next = () => iterator2.next(); - response = makeResponse({ status, statusText, headersList }); + }; + var Headers = class _Headers { + #guard; + /** + * @type {HeadersList} + */ + #headersList; + /** + * @param {HeadersInit|Symbol} [init] + * @returns + */ + constructor(init2 = void 0) { + webidl.util.markAsUncloneable(this); + if (init2 === kConstruct) { + return; } - } catch (err) { - if (err.name === "AbortError") { - fetchParams.controller.connection.destroy(); - return makeAppropriateNetworkError(fetchParams, err); + this.#headersList = new HeadersList(); + this.#guard = "none"; + if (init2 !== void 0) { + init2 = webidl.converters.HeadersInit(init2, "Headers constructor", "init"); + fill(this, init2); } - return makeNetworkError(err); } - const pullAlgorithm = async () => { - await fetchParams.controller.resume(); - }; - const cancelAlgorithm = (reason) => { - if (!isCancelled(fetchParams)) { - fetchParams.controller.abort(reason); + // 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"); + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: "Headers.delete", + value: name, + type: "header name" + }); } - }; - const stream2 = new ReadableStream( - { - async start(controller) { - fetchParams.controller.controller = controller; - }, - async pull(controller) { - await pullAlgorithm(controller); - }, - async cancel(reason) { - await cancelAlgorithm(reason); - }, - type: "bytes" + if (this.#guard === "immutable") { + throw new TypeError("immutable"); } - ); - response.body = { stream: stream2, source: null, length: null }; - fetchParams.controller.onAborted = onAborted; - fetchParams.controller.on("terminated", onAborted); - fetchParams.controller.resume = async () => { - while (true) { - let bytes; - let isFailure; - try { - const { done, value } = await fetchParams.controller.next(); - if (isAborted(fetchParams)) { - break; - } - bytes = done ? void 0 : value; - } catch (err) { - if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { - bytes = void 0; - } else { - bytes = err; - isFailure = true; - } - } - if (bytes === void 0) { - readableStreamClose(fetchParams.controller.controller); - finalizeResponse(fetchParams, response); - return; - } - timingInfo.decodedBodySize += bytes?.byteLength ?? 0; - if (isFailure) { - fetchParams.controller.terminate(bytes); - return; - } - const buffer = new Uint8Array(bytes); - if (buffer.byteLength) { - fetchParams.controller.controller.enqueue(buffer); - } - if (isErrored(stream2)) { - fetchParams.controller.terminate(); - return; - } - if (fetchParams.controller.controller.desiredSize <= 0) { - return; - } + if (!this.#headersList.contains(name, false)) { + return; } - }; - function onAborted(reason) { - if (isAborted(fetchParams)) { - response.aborted = true; - if (isReadable(stream2)) { - fetchParams.controller.controller.error( - fetchParams.controller.serializedAbortReason - ); - } - } else { - if (isReadable(stream2)) { - fetchParams.controller.controller.error(new TypeError("terminated", { - cause: isErrorLike(reason) ? reason : void 0 - })); - } + 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"); + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: "header name" + }); } - fetchParams.controller.connection.destroy(); + return this.#headersList.get(name, false); } - return response; - function dispatch({ body }) { - const url2 = requestCurrentURL(request3); - const agent = fetchParams.controller.dispatcher; - return new Promise((resolve14, reject) => agent.dispatch( - { - path: url2.pathname + url2.search, - origin: url2.origin, - method: request3.method, - body: agent.isMockActive ? request3.body && (request3.body.source || request3.body.stream) : body, - headers: request3.headersList.entries, - maxRedirections: 0, - upgrade: request3.mode === "websocket" ? "websocket" : void 0 - }, - { - body: null, - abort: null, - onConnect(abort) { - const { connection } = fetchParams.controller; - timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(void 0, 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; - } - timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability); - }, - onResponseStarted() { - 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 Readable3({ read: resume }); - const decoders = []; - const willFollow = location && request3.redirect === "follow" && redirectStatusSet.has(status); - if (request3.method !== "HEAD" && request3.method !== "CONNECT" && !nullBodyStatus.includes(status) && !willFollow) { - const contentEncoding = headersList.get("content-encoding", true); - const codings = contentEncoding ? contentEncoding.toLowerCase().split(",") : []; - 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(); - if (coding === "x-gzip" || coding === "gzip") { - decoders.push(zlib3.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: zlib3.constants.Z_SYNC_FLUSH, - finishFlush: zlib3.constants.Z_SYNC_FLUSH - })); - } else if (coding === "deflate") { - decoders.push(createInflate({ - flush: zlib3.constants.Z_SYNC_FLUSH, - finishFlush: zlib3.constants.Z_SYNC_FLUSH - })); - } else if (coding === "br") { - decoders.push(zlib3.createBrotliDecompress({ - flush: zlib3.constants.BROTLI_OPERATION_FLUSH, - finishFlush: zlib3.constants.BROTLI_OPERATION_FLUSH - })); - } else { - decoders.length = 0; - break; - } - } - } - const onError = this.onError.bind(this); - resolve14({ - status, - statusText, - headersList, - body: decoders.length ? pipeline2(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; - } - const bytes = chunk; - timingInfo.encodedBodySize += bytes.byteLength; - 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(error3) { - if (this.abort) { - fetchParams.controller.off("terminated", this.abort); - } - this.body?.destroy(error3); - fetchParams.controller.terminate(error3); - reject(error3); - }, - 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); - } - resolve14({ - status, - statusText: STATUS_CODES[status], - headersList, - socket - }); - return true; - } - } - )); + // 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"); + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: "header name" + }); + } + return this.#headersList.contains(name, false); } - } - module2.exports = { - fetch, - Fetch, - fetching, - finalizeAndReportTiming - }; - } -}); - -// node_modules/undici/lib/web/fileapi/symbols.js -var require_symbols3 = __commonJS({ - "node_modules/undici/lib/web/fileapi/symbols.js"(exports2, module2) { - "use strict"; - module2.exports = { - kState: /* @__PURE__ */ Symbol("FileReader state"), - kResult: /* @__PURE__ */ Symbol("FileReader result"), - kError: /* @__PURE__ */ Symbol("FileReader error"), - kLastProgressEventFired: /* @__PURE__ */ Symbol("FileReader last progress event fired timestamp"), - kEvents: /* @__PURE__ */ Symbol("FileReader events"), - kAborted: /* @__PURE__ */ Symbol("FileReader aborted") - }; - } -}); - -// node_modules/undici/lib/web/fileapi/progressevent.js -var require_progressevent = __commonJS({ - "node_modules/undici/lib/web/fileapi/progressevent.js"(exports2, module2) { - "use strict"; - var { webidl } = require_webidl(); - var kState = /* @__PURE__ */ Symbol("ProgressEvent state"); - var 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 - }; + // 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"); + value = headerValueNormalize(value); + 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" + }); + } + if (this.#guard === "immutable") { + throw new TypeError("immutable"); + } + this.#headersList.set(name, value, false); } - get lengthComputable() { - webidl.brandCheck(this, _ProgressEvent); - return this[kState].lengthComputable; + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie() { + webidl.brandCheck(this, _Headers); + const list = this.#headersList.cookies; + if (list) { + return [...list]; + } + return []; } - get loaded() { - webidl.brandCheck(this, _ProgressEvent); - return this[kState].loaded; + [util4.inspect.custom](depth, options) { + options.depth ??= depth; + return `Headers ${util4.formatWithOptions(options, this.#headersList.entries)}`; } - get total() { - webidl.brandCheck(this, _ProgressEvent); - return this[kState].total; + static getHeadersGuard(o) { + return o.#guard; } - }; - 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 + static setHeadersGuard(o, guard) { + o.#guard = guard; } - ]); - module2.exports = { - ProgressEvent - }; - } -}); - -// node_modules/undici/lib/web/fileapi/encoding.js -var require_encoding = __commonJS({ - "node_modules/undici/lib/web/fileapi/encoding.js"(exports2, module2) { - "use strict"; - function getEncoding(label) { - if (!label) { - return "failure"; + /** + * @param {Headers} o + */ + static getHeadersList(o) { + return o.#headersList; } - 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"; + /** + * @param {Headers} target + * @param {HeadersList} list + */ + static setHeadersList(target, list) { + target.#headersList = list; } - } - module2.exports = { - getEncoding }; - } -}); - -// node_modules/undici/lib/web/fileapi/util.js -var require_util4 = __commonJS({ - "node_modules/undici/lib/web/fileapi/util.js"(exports2, module2) { - "use strict"; - var { - kState, - kError, - kResult, - kAborted, - kLastProgressEventFired - } = require_symbols3(); - var { ProgressEvent } = require_progressevent(); - var { getEncoding } = require_encoding(); - var { serializeAMimeType, parseMIMEType } = require_data_url(); - var { types: types2 } = require("node:util"); - var { StringDecoder } = require("string_decoder"); - var { btoa: btoa2 } = require("node:buffer"); - var staticPropertyDescriptors = { - enumerable: true, - writable: false, - configurable: false - }; - function readOperation(fr, blob, type, encodingName) { - if (fr[kState] === "loading") { - throw new DOMException("Invalid state", "InvalidStateError"); - } - fr[kState] = "loading"; - fr[kResult] = null; - fr[kError] = null; - const stream2 = blob.stream(); - const reader = stream2.getReader(); - const bytes = []; - let chunkPromise = reader.read(); - let isFirstChunk = true; - (async () => { - while (!fr[kAborted]) { + var { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers; + Reflect.deleteProperty(Headers, "getHeadersGuard"); + Reflect.deleteProperty(Headers, "setHeadersGuard"); + Reflect.deleteProperty(Headers, "getHeadersList"); + Reflect.deleteProperty(Headers, "setHeadersList"); + iteratorMixin("Headers", Headers, headersListSortAndCombine, 0, 1); + Object.defineProperties(Headers.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + getSetCookie: kEnumerableProperty, + [Symbol.toStringTag]: { + value: "Headers", + configurable: true + }, + [util4.inspect.custom]: { + enumerable: false + } + }); + webidl.converters.HeadersInit = function(V, prefix, argument) { + if (webidl.util.Type(V) === webidl.util.Types.OBJECT) { + const iterator2 = Reflect.get(V, Symbol.iterator); + if (!util4.types.isProxy(V) && iterator2 === Headers.prototype.entries) { try { - const { done, value } = await chunkPromise; - if (isFirstChunk && !fr[kAborted]) { - queueMicrotask(() => { - fireAProgressEvent("loadstart", fr); - }); - } - isFirstChunk = false; - if (!done && types2.isUint8Array(value)) { - bytes.push(value); - if ((fr[kLastProgressEventFired] === void 0 || Date.now() - fr[kLastProgressEventFired] >= 50) && !fr[kAborted]) { - fr[kLastProgressEventFired] = Date.now(); - queueMicrotask(() => { - fireAProgressEvent("progress", fr); - }); - } - chunkPromise = reader.read(); - } else if (done) { - queueMicrotask(() => { - fr[kState] = "done"; - try { - const result = packageData(bytes, type, blob.type, encodingName); - if (fr[kAborted]) { - return; - } - fr[kResult] = result; - fireAProgressEvent("load", fr); - } catch (error3) { - fr[kError] = error3; - fireAProgressEvent("error", fr); - } - if (fr[kState] !== "loading") { - fireAProgressEvent("loadend", fr); - } - }); - break; - } - } catch (error3) { - if (fr[kAborted]) { - return; - } - queueMicrotask(() => { - fr[kState] = "done"; - fr[kError] = error3; - fireAProgressEvent("error", fr); - if (fr[kState] !== "loading") { - fireAProgressEvent("loadend", fr); - } - }); - break; - } - } - })(); - } - function fireAProgressEvent(e, reader) { - const event = new ProgressEvent(e, { - bubbles: false, - cancelable: false - }); - reader.dispatchEvent(event); - } - function packageData(bytes, type, mimeType, encodingName) { - switch (type) { - case "DataURL": { - 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 += btoa2(decoder.write(chunk)); - } - dataURL += btoa2(decoder.end()); - return dataURL; - } - case "Text": { - let encoding = "failure"; - if (encodingName) { - encoding = getEncoding(encodingName); - } - if (encoding === "failure" && mimeType) { - const type2 = parseMIMEType(mimeType); - if (type2 !== "failure") { - encoding = getEncoding(type2.parameters.get("charset")); - } - } - if (encoding === "failure") { - encoding = "UTF-8"; + return getHeadersList(V).entriesList; + } catch { } - return decode(bytes, encoding); } - case "ArrayBuffer": { - const sequence = combineByteSequences(bytes); - return sequence.buffer; - } - case "BinaryString": { - let binaryString = ""; - const decoder = new StringDecoder("latin1"); - for (const chunk of bytes) { - binaryString += decoder.write(chunk); - } - binaryString += decoder.end(); - return binaryString; + if (typeof iterator2 === "function") { + return webidl.converters["sequence>"](V, prefix, argument, iterator2.bind(V)); } + return webidl.converters["record"](V, prefix, argument); } - } - function decode(ioQueue, encoding) { - const bytes = combineByteSequences(ioQueue); - const BOMEncoding = BOMSniffing(bytes); - let slice = 0; - if (BOMEncoding !== null) { - encoding = BOMEncoding; - slice = BOMEncoding === "UTF-8" ? 3 : 2; - } - const sliced = bytes.slice(slice); - return new TextDecoder(encoding).decode(sliced); - } - function BOMSniffing(ioQueue) { - const [a, b, c] = ioQueue; - if (a === 239 && b === 187 && c === 191) { - return "UTF-8"; - } else if (a === 254 && b === 255) { - return "UTF-16BE"; - } else if (a === 255 && b === 254) { - return "UTF-16LE"; - } - return null; - } - 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)); - } + throw webidl.errors.conversionFailed({ + prefix: "Headers constructor", + argument: "Argument 1", + types: ["sequence>", "record"] + }); + }; module2.exports = { - staticPropertyDescriptors, - readOperation, - fireAProgressEvent + fill, + // for test. + compareHeaderName, + Headers, + HeadersList, + getHeadersGuard, + setHeadersGuard, + setHeadersList, + getHeadersList }; } }); -// node_modules/undici/lib/web/fileapi/filereader.js -var require_filereader = __commonJS({ - "node_modules/undici/lib/web/fileapi/filereader.js"(exports2, module2) { +// node_modules/undici/lib/web/fetch/response.js +var require_response = __commonJS({ + "node_modules/undici/lib/web/fetch/response.js"(exports2, module2) { "use strict"; + var { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = require_headers(); + var { extractBody, cloneBody, mixinBody, streamRegistry, bodyUnusable } = require_body(); + var util4 = require_util(); + var nodeUtil = require("node:util"); + var { kEnumerableProperty } = util4; var { - staticPropertyDescriptors, - readOperation, - fireAProgressEvent - } = require_util4(); + isValidReasonPhrase, + isCancelled, + isAborted, + isErrorLike, + environmentSettingsObject: relevantRealm + } = require_util2(); var { - kState, - kError, - kResult, - kEvents, - kAborted - } = require_symbols3(); + redirectStatusSet, + nullBodyStatus + } = require_constants3(); var { webidl } = require_webidl(); - var { kEnumerableProperty } = require_util(); - var FileReader = 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 - }; + var { URLSerializer } = require_data_url(); + var { kConstruct } = require_symbols(); + var assert = require("node:assert"); + var { isomorphicEncode, serializeJavascriptValueToJSONString } = require_infra(); + var textEncoder = new TextEncoder("utf-8"); + var Response2 = class _Response { + /** @type {Headers} */ + #headers; + #state; + // Creates network error Response. + static error() { + const responseObject = fromInnerResponse(makeNetworkError(), "immutable"); + return responseObject; } - /** - * @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 }); - readOperation(this, blob, "ArrayBuffer"); + // https://fetch.spec.whatwg.org/#dom-response-json + static json(data, init2 = void 0) { + webidl.argumentLengthCheck(arguments, 1, "Response.json"); + if (init2 !== null) { + init2 = webidl.converters.ResponseInit(init2); + } + const bytes = textEncoder.encode( + serializeJavascriptValueToJSONString(data) + ); + const body = extractBody(bytes); + const responseObject = fromInnerResponse(makeResponse({}), "response"); + initializeResponse(responseObject, init2, { body: body[0], type: "application/json" }); + return responseObject; } - /** - * @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 }); - readOperation(this, blob, "BinaryString"); + // Creates a redirect Response that redirects to url with status status. + static redirect(url2, status = 302) { + webidl.argumentLengthCheck(arguments, 1, "Response.redirect"); + url2 = webidl.converters.USVString(url2); + status = webidl.converters["unsigned short"](status); + let parsedURL; + try { + parsedURL = new URL(url2, relevantRealm.settingsObject.baseUrl); + } catch (err) { + throw new TypeError(`Failed to parse URL from ${url2}`, { cause: err }); + } + if (!redirectStatusSet.has(status)) { + throw new RangeError(`Invalid status code ${status}`); + } + const responseObject = fromInnerResponse(makeResponse({}), "immutable"); + responseObject.#state.status = status; + const value = isomorphicEncode(URLSerializer(parsedURL)); + responseObject.#state.headersList.append("location", value, true); + return responseObject; } - /** - * @see https://w3c.github.io/FileAPI/#readAsDataText - * @param {import('buffer').Blob} blob - * @param {string?} encoding - */ - readAsText(blob, encoding = void 0) { - webidl.brandCheck(this, _FileReader); - webidl.argumentLengthCheck(arguments, 1, "FileReader.readAsText"); - blob = webidl.converters.Blob(blob, { strict: false }); - if (encoding !== void 0) { - encoding = webidl.converters.DOMString(encoding, "FileReader.readAsText", "encoding"); + // https://fetch.spec.whatwg.org/#dom-response + constructor(body = null, init2 = void 0) { + webidl.util.markAsUncloneable(this); + if (body === kConstruct) { + return; + } + if (body !== null) { + body = webidl.converters.BodyInit(body, "Response", "body"); + } + init2 = webidl.converters.ResponseInit(init2); + this.#state = makeResponse({}); + this.#headers = new Headers(kConstruct); + setHeadersGuard(this.#headers, "response"); + setHeadersList(this.#headers, this.#state.headersList); + let bodyWithType = null; + if (body != null) { + const [extractedBody, type] = extractBody(body); + bodyWithType = { body: extractedBody, type }; + } + initializeResponse(this, init2, bodyWithType); + } + // Returns response’s type, e.g., "cors". + get type() { + webidl.brandCheck(this, _Response); + return this.#state.type; + } + // Returns response’s URL, if it has one; otherwise the empty string. + get url() { + webidl.brandCheck(this, _Response); + const urlList = this.#state.urlList; + const url2 = urlList[urlList.length - 1] ?? null; + if (url2 === null) { + return ""; } - readOperation(this, blob, "Text", encoding); + return URLSerializer(url2, true); } - /** - * @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 }); - readOperation(this, blob, "DataURL"); + // Returns whether response was obtained through a redirect. + get redirected() { + webidl.brandCheck(this, _Response); + return this.#state.urlList.length > 1; } - /** - * @see https://w3c.github.io/FileAPI/#dfn-abort - */ - abort() { - if (this[kState] === "empty" || this[kState] === "done") { - this[kResult] = null; - return; + // Returns response’s status. + get status() { + webidl.brandCheck(this, _Response); + return this.#state.status; + } + // Returns whether response’s status is an ok status. + get ok() { + webidl.brandCheck(this, _Response); + return this.#state.status >= 200 && this.#state.status <= 299; + } + // Returns response’s status message. + get statusText() { + webidl.brandCheck(this, _Response); + return this.#state.statusText; + } + // Returns response’s headers as Headers. + get headers() { + webidl.brandCheck(this, _Response); + return this.#headers; + } + get body() { + webidl.brandCheck(this, _Response); + return this.#state.body ? this.#state.body.stream : null; + } + get bodyUsed() { + webidl.brandCheck(this, _Response); + return !!this.#state.body && util4.isDisturbed(this.#state.body.stream); + } + // Returns a clone of response. + clone() { + webidl.brandCheck(this, _Response); + if (bodyUnusable(this.#state)) { + throw webidl.errors.exception({ + header: "Response.clone", + message: "Body has already been consumed." + }); } - if (this[kState] === "loading") { - this[kState] = "done"; - this[kResult] = null; + const clonedResponse = cloneResponse(this.#state); + if (this.#state.urlList.length !== 0 && this.#state.body?.stream) { + streamRegistry.register(this, new WeakRef(this.#state.body.stream)); } - this[kAborted] = true; - fireAProgressEvent("abort", this); - if (this[kState] !== "loading") { - fireAProgressEvent("loadend", this); + return fromInnerResponse(clonedResponse, getHeadersGuard(this.#headers)); + } + [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)}`; } /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate + * @param {Response} response */ - get readyState() { - webidl.brandCheck(this, _FileReader); - switch (this[kState]) { - case "empty": - return this.EMPTY; - case "loading": - return this.LOADING; - case "done": - return this.DONE; - } + static getResponseHeaders(response) { + return response.#headers; } /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-result + * @param {Response} response + * @param {Headers} newHeaders */ - get result() { - webidl.brandCheck(this, _FileReader); - return this[kResult]; + static setResponseHeaders(response, newHeaders) { + response.#headers = newHeaders; } /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-error + * @param {Response} response */ - get error() { - webidl.brandCheck(this, _FileReader); - return this[kError]; + static getResponseState(response) { + return response.#state; } - get onloadend() { - webidl.brandCheck(this, _FileReader); - return this[kEvents].loadend; + /** + * @param {Response} response + * @param {any} newState + */ + static setResponseState(response, newState) { + response.#state = newState; } - 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; - } + }; + var { getResponseHeaders, setResponseHeaders, getResponseState, setResponseState } = Response2; + Reflect.deleteProperty(Response2, "getResponseHeaders"); + Reflect.deleteProperty(Response2, "setResponseHeaders"); + Reflect.deleteProperty(Response2, "getResponseState"); + Reflect.deleteProperty(Response2, "setResponseState"); + mixinBody(Response2, getResponseState); + Object.defineProperties(Response2.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 } - get onerror() { - webidl.brandCheck(this, _FileReader); - return this[kEvents].error; + }); + Object.defineProperties(Response2, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty + }); + function cloneResponse(response) { + if (response.internalResponse) { + return filterResponse( + cloneResponse(response.internalResponse), + response.type + ); } - 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; + const newResponse = makeResponse({ ...response, body: null }); + if (response.body != null) { + newResponse.body = cloneBody(response.body); + } + return newResponse; + } + function makeResponse(init2) { + return { + aborted: false, + rangeRequested: false, + timingAllowPassed: false, + requestIncludesCredentials: false, + type: "default", + status: 200, + timingInfo: null, + cacheState: "", + statusText: "", + ...init2, + headersList: init2?.headersList ? new HeadersList(init2?.headersList) : new HeadersList(), + urlList: init2?.urlList ? [...init2.urlList] : [] + }; + } + function makeNetworkError(reason) { + const isError2 = isErrorLike(reason); + return makeResponse({ + type: "error", + status: 0, + error: isError2 ? reason : new Error(reason ? String(reason) : reason), + aborted: reason && reason.name === "AbortError" + }); + } + 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; } + }); + } + function filterResponse(response, type) { + if (type === "basic") { + return makeFilteredResponse(response, { + type: "basic", + headersList: response.headersList + }); + } else if (type === "cors") { + return makeFilteredResponse(response, { + type: "cors", + headersList: response.headersList + }); + } else if (type === "opaque") { + return makeFilteredResponse(response, { + type: "opaque", + urlList: [], + status: 0, + statusText: "", + body: null + }); + } else if (type === "opaqueredirect") { + return makeFilteredResponse(response, { + type: "opaqueredirect", + status: 0, + statusText: "", + headersList: [], + body: null + }); + } else { + assert(false); } - get onloadstart() { - webidl.brandCheck(this, _FileReader); - return this[kEvents].loadstart; + } + function makeAppropriateNetworkError(fetchParams, err = null) { + assert(isCancelled(fetchParams)); + 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 })); + } + function initializeResponse(response, init2, body) { + if (init2.status !== null && (init2.status < 200 || init2.status > 599)) { + throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.'); } - 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; + if ("statusText" in init2 && init2.statusText != null) { + if (!isValidReasonPhrase(String(init2.statusText))) { + throw new TypeError("Invalid statusText"); } } - get onprogress() { - webidl.brandCheck(this, _FileReader); - return this[kEvents].progress; + if ("status" in init2 && init2.status != null) { + getResponseState(response).status = init2.status; } - 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; - } + if ("statusText" in init2 && init2.statusText != null) { + getResponseState(response).statusText = init2.statusText; } - get onload() { - webidl.brandCheck(this, _FileReader); - return this[kEvents].load; + if ("headers" in init2 && init2.headers != null) { + fill(getResponseHeaders(response), init2.headers); } - set onload(fn) { - webidl.brandCheck(this, _FileReader); - if (this[kEvents].load) { - this.removeEventListener("load", this[kEvents].load); + if (body) { + if (nullBodyStatus.includes(response.status)) { + throw webidl.errors.exception({ + header: "Response constructor", + message: `Invalid response status code ${response.status}` + }); } - if (typeof fn === "function") { - this[kEvents].load = fn; - this.addEventListener("load", fn); - } else { - this[kEvents].load = null; + getResponseState(response).body = body.body; + if (body.type != null && !getResponseState(response).headersList.contains("content-type", true)) { + getResponseState(response).headersList.append("content-type", body.type, true); } } - get onabort() { - webidl.brandCheck(this, _FileReader); - return this[kEvents].abort; + } + function fromInnerResponse(innerResponse, guard) { + const response = new Response2(kConstruct); + setResponseState(response, innerResponse); + const headers = new Headers(kConstruct); + setResponseHeaders(response, headers); + setHeadersList(headers, innerResponse.headersList); + setHeadersGuard(headers, guard); + if (innerResponse.urlList.length !== 0 && innerResponse.body?.stream) { + streamRegistry.register(response, new WeakRef(innerResponse.body.stream)); } - 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; - } - } - }; - FileReader.EMPTY = FileReader.prototype.EMPTY = 0; - FileReader.LOADING = FileReader.prototype.LOADING = 1; - 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 + return response; + } + webidl.converters.XMLHttpRequestBodyInit = function(V, prefix, name) { + if (typeof V === "string") { + return webidl.converters.USVString(V, prefix, name); } - }); - Object.defineProperties(FileReader, { - EMPTY: staticPropertyDescriptors, - LOADING: staticPropertyDescriptors, - DONE: staticPropertyDescriptors - }); - module2.exports = { - FileReader + if (webidl.is.Blob(V)) { + return V; + } + if (webidl.is.BufferSource(V)) { + return V; + } + if (webidl.is.FormData(V)) { + return V; + } + if (webidl.is.URLSearchParams(V)) { + return V; + } + return webidl.converters.DOMString(V, prefix, name); }; - } -}); - -// node_modules/undici/lib/web/cache/symbols.js -var require_symbols4 = __commonJS({ - "node_modules/undici/lib/web/cache/symbols.js"(exports2, module2) { - "use strict"; - module2.exports = { - kConstruct: require_symbols().kConstruct + webidl.converters.BodyInit = function(V, prefix, argument) { + if (webidl.is.ReadableStream(V)) { + return V; + } + if (V?.[Symbol.asyncIterator]) { + return V; + } + return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument); }; - } -}); - -// node_modules/undici/lib/web/cache/util.js -var require_util5 = __commonJS({ - "node_modules/undici/lib/web/cache/util.js"(exports2, module2) { - "use strict"; - var assert = require("node:assert"); - var { URLSerializer } = require_data_url(); - var { isValidHeaderName } = require_util2(); - function urlEquals(A, B, excludeFragment = false) { - const serializedA = URLSerializer(A, excludeFragment); - const serializedB = URLSerializer(B, excludeFragment); - return serializedA === serializedB; - } - function getFieldValues(header) { - assert(header !== null); - const values = []; - for (let value of header.split(",")) { - value = value.trim(); - if (isValidHeaderName(value)) { - values.push(value); - } + 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 } - return values; - } + ]); + webidl.is.Response = webidl.util.MakeTypeAssertion(Response2); module2.exports = { - urlEquals, - getFieldValues + isNetworkError, + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response: Response2, + cloneResponse, + fromInnerResponse, + getResponseState }; } }); -// node_modules/undici/lib/web/cache/cache.js -var require_cache = __commonJS({ - "node_modules/undici/lib/web/cache/cache.js"(exports2, module2) { +// node_modules/undici/lib/web/fetch/request.js +var require_request2 = __commonJS({ + "node_modules/undici/lib/web/fetch/request.js"(exports2, module2) { "use strict"; - var { kConstruct } = require_symbols4(); - var { urlEquals, getFieldValues } = require_util5(); - var { kEnumerableProperty, isDisturbed } = require_util(); + var { extractBody, mixinBody, cloneBody, bodyUnusable } = require_body(); + var { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require_headers(); + var util4 = require_util(); + var nodeUtil = require("node:util"); + var { + isValidHTTPToken, + sameOrigin, + environmentSettingsObject + } = require_util2(); + var { + forbiddenMethodsSet, + corsSafeListedMethodsSet, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex + } = require_constants3(); + var { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util4; var { webidl } = require_webidl(); - var { Response, cloneResponse, fromInnerResponse } = require_response(); - var { Request, fromInnerRequest } = require_request2(); - var { kState } = require_symbols2(); - var { fetching } = require_fetch(); - var { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require_util2(); + var { URLSerializer } = require_data_url(); + var { kConstruct } = require_symbols(); var assert = require("node:assert"); - var Cache = class _Cache { - /** - * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list - * @type {requestResponseList} - */ - #relevantRequestResponseList; - constructor() { - if (arguments[0] !== kConstruct) { - webidl.illegalConstructor(); + var { getMaxListeners, setMaxListeners, defaultMaxListeners } = require("node:events"); + var kAbortController = /* @__PURE__ */ Symbol("abortController"); + var requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener("abort", abort); + }); + var dependentControllerMap = /* @__PURE__ */ new WeakMap(); + var abortSignalHasEventHandlerLeakWarning; + try { + abortSignalHasEventHandlerLeakWarning = getMaxListeners(new AbortController().signal) > 0; + } catch { + abortSignalHasEventHandlerLeakWarning = false; + } + function buildAbort(acRef) { + return abort; + function abort() { + const ac = acRef.deref(); + if (ac !== void 0) { + requestFinalizer.unregister(abort); + this.removeEventListener("abort", abort); + ac.abort(this.reason); + const controllerList = dependentControllerMap.get(ac.signal); + if (controllerList !== void 0) { + if (controllerList.size !== 0) { + for (const ref of controllerList) { + const ctrl = ref.deref(); + if (ctrl !== void 0) { + ctrl.abort(this.reason); + } + } + controllerList.clear(); + } + dependentControllerMap.delete(ac.signal); + } } - webidl.util.markAsUncloneable(this); - this.#relevantRequestResponseList = arguments[1]; } - async match(request3, options = {}) { - webidl.brandCheck(this, _Cache); - const prefix = "Cache.match"; - webidl.argumentLengthCheck(arguments, 1, prefix); - request3 = webidl.converters.RequestInfo(request3, prefix, "request"); - options = webidl.converters.CacheQueryOptions(options, prefix, "options"); - const p = this.#internalMatchAll(request3, options, 1); - if (p.length === 0) { + } + var patchMethodWarning = false; + var Request = class _Request { + /** @type {AbortSignal} */ + #signal; + /** @type {import('../../dispatcher/dispatcher')} */ + #dispatcher; + /** @type {Headers} */ + #headers; + #state; + // https://fetch.spec.whatwg.org/#dom-request + constructor(input, init2 = void 0) { + webidl.util.markAsUncloneable(this); + if (input === kConstruct) { return; } - return p[0]; - } - async matchAll(request3 = void 0, options = {}) { - webidl.brandCheck(this, _Cache); - const prefix = "Cache.matchAll"; - if (request3 !== void 0) request3 = webidl.converters.RequestInfo(request3, prefix, "request"); - options = webidl.converters.CacheQueryOptions(options, prefix, "options"); - return this.#internalMatchAll(request3, options); - } - async add(request3) { - webidl.brandCheck(this, _Cache); - const prefix = "Cache.add"; - webidl.argumentLengthCheck(arguments, 1, prefix); - request3 = webidl.converters.RequestInfo(request3, prefix, "request"); - const requests = [request3]; - const responseArrayPromise = this.addAll(requests); - return await responseArrayPromise; - } - async addAll(requests) { - webidl.brandCheck(this, _Cache); - const prefix = "Cache.addAll"; + const prefix = "Request constructor"; webidl.argumentLengthCheck(arguments, 1, prefix); - const responsePromises = []; - const requestList = []; - for (let request3 of requests) { - if (request3 === void 0) { - throw webidl.errors.conversionFailed({ - prefix, - argument: "Argument 1", - types: ["undefined is not allowed"] - }); - } - request3 = webidl.converters.RequestInfo(request3); - if (typeof request3 === "string") { - continue; + input = webidl.converters.RequestInfo(input); + init2 = webidl.converters.RequestInit(init2); + let request3 = null; + let fallbackMode = null; + const baseUrl = environmentSettingsObject.settingsObject.baseUrl; + let signal = null; + if (typeof input === "string") { + this.#dispatcher = init2.dispatcher; + let parsedURL; + try { + parsedURL = new URL(input, baseUrl); + } catch (err) { + throw new TypeError("Failed to parse URL from " + input, { cause: err }); } - const r = request3[kState]; - if (!urlIsHttpHttpsScheme(r.url) || r.method !== "GET") { - throw webidl.errors.exception({ - header: prefix, - message: "Expected http/s scheme when method is not GET." - }); + if (parsedURL.username || parsedURL.password) { + throw new TypeError( + "Request cannot be constructed from a URL that includes credentials: " + input + ); } + request3 = makeRequest({ urlList: [parsedURL] }); + fallbackMode = "cors"; + } else { + assert(webidl.is.Request(input)); + request3 = input.#state; + signal = input.#signal; + this.#dispatcher = init2.dispatcher || input.#dispatcher; } - const fetchControllers = []; - for (const request3 of requests) { - const r = new Request(request3)[kState]; - if (!urlIsHttpHttpsScheme(r.url)) { - throw webidl.errors.exception({ - header: prefix, - message: "Expected http/s scheme." - }); - } - r.initiator = "fetch"; - r.destination = "subresource"; - requestList.push(r); - const responsePromise = createDeferredPromise(); - fetchControllers.push(fetching({ - request: r, - processResponse(response) { - 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")) { - const fieldValues = getFieldValues(response.headersList.get("vary")); - for (const fieldValue of fieldValues) { - 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) { - if (response.aborted) { - responsePromise.reject(new DOMException("aborted", "AbortError")); - return; - } - responsePromise.resolve(response); - } - })); - responsePromises.push(responsePromise.promise); + const origin = environmentSettingsObject.settingsObject.origin; + let window2 = "client"; + if (request3.window?.constructor?.name === "EnvironmentSettingsObject" && sameOrigin(request3.window, origin)) { + window2 = request3.window; } - const p = Promise.all(responsePromises); - const responses = await p; - const operations = []; - let index2 = 0; - for (const response of responses) { - const operation = { - type: "put", - // 7.3.2 - request: requestList[index2], - // 7.3.3 - response - // 7.3.4 - }; - operations.push(operation); - index2++; + if (init2.window != null) { + throw new TypeError(`'window' option '${window2}' must be null`); } - const cacheJobPromise = createDeferredPromise(); - let errorData = null; - try { - this.#batchCacheOperations(operations); - } catch (e) { - errorData = e; + if ("window" in init2) { + window2 = "no-window"; } - queueMicrotask(() => { - if (errorData === null) { - cacheJobPromise.resolve(void 0); + request3 = 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: request3.method, + // header list A copy of request’s header list. + // undici implementation note: headersList is cloned in makeRequest + headersList: request3.headersList, + // unsafe-request flag Set. + unsafeRequest: request3.unsafeRequest, + // client This’s relevant settings object. + client: environmentSettingsObject.settingsObject, + // window window. + window: window2, + // priority request’s priority. + priority: request3.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: request3.origin, + // referrer request’s referrer. + referrer: request3.referrer, + // referrer policy request’s referrer policy. + referrerPolicy: request3.referrerPolicy, + // mode request’s mode. + mode: request3.mode, + // credentials mode request’s credentials mode. + credentials: request3.credentials, + // cache mode request’s cache mode. + cache: request3.cache, + // redirect mode request’s redirect mode. + redirect: request3.redirect, + // integrity metadata request’s integrity metadata. + integrity: request3.integrity, + // keepalive request’s keepalive. + keepalive: request3.keepalive, + // reload-navigation flag request’s reload-navigation flag. + reloadNavigation: request3.reloadNavigation, + // history-navigation flag request’s history-navigation flag. + historyNavigation: request3.historyNavigation, + // URL list A clone of request’s URL list. + urlList: [...request3.urlList] + }); + const initHasKey = Object.keys(init2).length !== 0; + if (initHasKey) { + if (request3.mode === "navigate") { + request3.mode = "same-origin"; + } + request3.reloadNavigation = false; + request3.historyNavigation = false; + request3.origin = "client"; + request3.referrer = "client"; + request3.referrerPolicy = ""; + request3.url = request3.urlList[request3.urlList.length - 1]; + request3.urlList = [request3.url]; + } + if (init2.referrer !== void 0) { + const referrer = init2.referrer; + if (referrer === "") { + request3.referrer = "no-referrer"; } else { - cacheJobPromise.reject(errorData); + let parsedReferrer; + try { + parsedReferrer = new URL(referrer, baseUrl); + } catch (err) { + throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }); + } + if (parsedReferrer.protocol === "about:" && parsedReferrer.hostname === "client" || origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) { + request3.referrer = "client"; + } else { + request3.referrer = parsedReferrer; + } } - }); - return cacheJobPromise.promise; - } - async put(request3, response) { - webidl.brandCheck(this, _Cache); - const prefix = "Cache.put"; - webidl.argumentLengthCheck(arguments, 2, prefix); - request3 = webidl.converters.RequestInfo(request3, prefix, "request"); - response = webidl.converters.Response(response, prefix, "response"); - let innerRequest = null; - if (request3 instanceof Request) { - innerRequest = request3[kState]; + } + if (init2.referrerPolicy !== void 0) { + request3.referrerPolicy = init2.referrerPolicy; + } + let mode; + if (init2.mode !== void 0) { + mode = init2.mode; } else { - innerRequest = new Request(request3)[kState]; + mode = fallbackMode; } - if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== "GET") { + if (mode === "navigate") { throw webidl.errors.exception({ - header: prefix, - message: "Expected an http/s scheme when method is not GET" + header: "Request constructor", + message: "invalid request mode navigate." }); } - const innerResponse = response[kState]; - if (innerResponse.status === 206) { - throw webidl.errors.exception({ - header: prefix, - message: "Got 206 status" - }); + if (mode != null) { + request3.mode = mode; } - if (innerResponse.headersList.contains("vary")) { - const fieldValues = getFieldValues(innerResponse.headersList.get("vary")); - for (const fieldValue of fieldValues) { - if (fieldValue === "*") { - throw webidl.errors.exception({ - header: prefix, - message: "Got * vary field value" - }); - } - } + if (init2.credentials !== void 0) { + request3.credentials = init2.credentials; } - if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { - throw webidl.errors.exception({ - header: prefix, - message: "Response body is locked or disturbed" - }); + if (init2.cache !== void 0) { + request3.cache = init2.cache; } - const clonedResponse = cloneResponse(innerResponse); - const bodyReadPromise = createDeferredPromise(); - if (innerResponse.body != null) { - const stream2 = innerResponse.body.stream; - const reader = stream2.getReader(); - readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject); - } else { - bodyReadPromise.resolve(void 0); + if (request3.cache === "only-if-cached" && request3.mode !== "same-origin") { + throw new TypeError( + "'only-if-cached' can be set only with 'same-origin' mode" + ); } - const operations = []; - const operation = { - type: "put", - // 14. - request: innerRequest, - // 15. - response: clonedResponse - // 16. - }; - operations.push(operation); - const bytes = await bodyReadPromise.promise; - if (clonedResponse.body != null) { - clonedResponse.body.source = bytes; + if (init2.redirect !== void 0) { + request3.redirect = init2.redirect; } - const cacheJobPromise = createDeferredPromise(); - let errorData = null; - try { - this.#batchCacheOperations(operations); - } catch (e) { - errorData = e; + if (init2.integrity != null) { + request3.integrity = String(init2.integrity); } - queueMicrotask(() => { - if (errorData === null) { - cacheJobPromise.resolve(); + if (init2.keepalive !== void 0) { + request3.keepalive = Boolean(init2.keepalive); + } + if (init2.method !== void 0) { + let method = init2.method; + const mayBeNormalized = normalizedMethodRecords[method]; + if (mayBeNormalized !== void 0) { + request3.method = mayBeNormalized; } else { - cacheJobPromise.reject(errorData); + 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.`); + } + method = normalizedMethodRecordsBase[upperCase] ?? method; + request3.method = method; } - }); - return cacheJobPromise.promise; - } - async delete(request3, options = {}) { - webidl.brandCheck(this, _Cache); - const prefix = "Cache.delete"; - webidl.argumentLengthCheck(arguments, 1, prefix); - request3 = webidl.converters.RequestInfo(request3, prefix, "request"); - options = webidl.converters.CacheQueryOptions(options, prefix, "options"); - let r = null; - if (request3 instanceof Request) { - r = request3[kState]; - if (r.method !== "GET" && !options.ignoreMethod) { - return false; + if (!patchMethodWarning && request3.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; } - } else { - assert(typeof request3 === "string"); - r = new Request(request3)[kState]; } - const operations = []; - 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; + if (init2.signal !== void 0) { + signal = init2.signal; } - queueMicrotask(() => { - if (errorData === null) { - cacheJobPromise.resolve(!!requestResponses?.length); + this.#state = request3; + const ac = new AbortController(); + this.#signal = ac.signal; + if (signal != null) { + if (signal.aborted) { + ac.abort(signal.reason); } 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(request3 = void 0, options = {}) { - webidl.brandCheck(this, _Cache); - const prefix = "Cache.keys"; - if (request3 !== void 0) request3 = webidl.converters.RequestInfo(request3, prefix, "request"); - options = webidl.converters.CacheQueryOptions(options, prefix, "options"); - let r = null; - if (request3 !== void 0) { - if (request3 instanceof Request) { - r = request3[kState]; - if (r.method !== "GET" && !options.ignoreMethod) { - return []; + this[kAbortController] = ac; + const acRef = new WeakRef(ac); + const abort = buildAbort(acRef); + if (abortSignalHasEventHandlerLeakWarning && getMaxListeners(signal) === defaultMaxListeners) { + setMaxListeners(1500, signal); } - } else if (typeof request3 === "string") { - r = new Request(request3)[kState]; - } - } - const promise = createDeferredPromise(); - const requests = []; - if (request3 === void 0) { - for (const requestResponse of this.#relevantRequestResponseList) { - requests.push(requestResponse[0]); - } - } else { - const requestResponses = this.#queryCache(r, options); - for (const requestResponse of requestResponses) { - requests.push(requestResponse[0]); + util4.addAbortListener(signal, abort); + requestFinalizer.register(ac, { signal, abort }, abort); } } - queueMicrotask(() => { - const requestList = []; - for (const request4 of requests) { - const requestObject = fromInnerRequest( - request4, - new AbortController().signal, - "immutable" + this.#headers = new Headers(kConstruct); + setHeadersList(this.#headers, request3.headersList); + setHeadersGuard(this.#headers, "request"); + if (mode === "no-cors") { + if (!corsSafeListedMethodsSet.has(request3.method)) { + throw new TypeError( + `'${request3.method} is unsupported in no-cors mode.` ); - requestList.push(requestObject); - } - 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) { - const cache = this.#relevantRequestResponseList; - const backupCache = [...cache]; - const addedItems = []; - const resultList = []; - try { - for (const operation of operations) { - if (operation.type !== "delete" && operation.type !== "put") { - throw webidl.errors.exception({ - header: "Cache.#batchCacheOperations", - message: 'operation type does not match "delete" or "put"' - }); - } - if (operation.type === "delete" && operation.response != null) { - throw webidl.errors.exception({ - header: "Cache.#batchCacheOperations", - message: "delete operation should not have an associated response" - }); - } - if (this.#queryCache(operation.request, operation.options, addedItems).length) { - throw new DOMException("???", "InvalidStateError"); - } - let requestResponses; - if (operation.type === "delete") { - requestResponses = this.#queryCache(operation.request, operation.options); - if (requestResponses.length === 0) { - return []; - } - for (const requestResponse of requestResponses) { - const idx = cache.indexOf(requestResponse); - assert(idx !== -1); - cache.splice(idx, 1); - } - } else if (operation.type === "put") { - if (operation.response == null) { - throw webidl.errors.exception({ - header: "Cache.#batchCacheOperations", - message: "put operation should have an associated response" - }); - } - const r = operation.request; - if (!urlIsHttpHttpsScheme(r.url)) { - throw webidl.errors.exception({ - header: "Cache.#batchCacheOperations", - message: "expected http or https scheme" - }); - } - if (r.method !== "GET") { - throw webidl.errors.exception({ - header: "Cache.#batchCacheOperations", - message: "not get method" - }); - } - if (operation.options != null) { - throw webidl.errors.exception({ - header: "Cache.#batchCacheOperations", - message: "options must not be defined" - }); - } - requestResponses = this.#queryCache(operation.request); - for (const requestResponse of requestResponses) { - const idx = cache.indexOf(requestResponse); - assert(idx !== -1); - cache.splice(idx, 1); - } - cache.push([operation.request, operation.response]); - addedItems.push([operation.request, operation.response]); - } - resultList.push([operation.request, operation.response]); } - return resultList; - } catch (e) { - this.#relevantRequestResponseList.length = 0; - this.#relevantRequestResponseList = backupCache; - throw e; + setHeadersGuard(this.#headers, "request-no-cors"); } - } - /** - * @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) { - 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); + if (initHasKey) { + const headersList = getHeadersList(this.#headers); + const headers = init2.headers !== void 0 ? init2.headers : new HeadersList(headersList); + headersList.clear(); + if (headers instanceof HeadersList) { + for (const { name, value } of headers.rawValues()) { + headersList.append(name, value, false); + } + headersList.cookies = headers.cookies; + } else { + fillHeaders(this.#headers, headers); } } - 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, request3, response = null, options) { - const queryURL = new URL(requestQuery.url); - const cachedURL = new URL(request3.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 = request3.headersList.get(fieldValue); - const queryValue = requestQuery.headersList.get(fieldValue); - if (requestValue !== queryValue) { - return false; - } + const inputBody = webidl.is.Request(input) ? input.#state.body : null; + if ((init2.body != null || inputBody != null) && (request3.method === "GET" || request3.method === "HEAD")) { + throw new TypeError("Request with GET/HEAD method cannot have body."); } - return true; - } - #internalMatchAll(request3, options, maxResponses = Infinity) { - let r = null; - if (request3 !== void 0) { - if (request3 instanceof Request) { - r = request3[kState]; - if (r.method !== "GET" && !options.ignoreMethod) { - return []; - } - } else if (typeof request3 === "string") { - r = new Request(request3)[kState]; + let initBody = null; + if (init2.body != null) { + const [extractedBody, contentType] = extractBody( + init2.body, + request3.keepalive + ); + initBody = extractedBody; + if (contentType && !getHeadersList(this.#headers).contains("content-type", true)) { + this.#headers.append("content-type", contentType, true); } } - const responses = []; - if (request3 === void 0) { - for (const requestResponse of this.#relevantRequestResponseList) { - responses.push(requestResponse[1]); + const inputOrInitBody = initBody ?? inputBody; + if (inputOrInitBody != null && inputOrInitBody.source == null) { + if (initBody != null && init2.duplex == null) { + throw new TypeError("RequestInit: duplex option is required when sending a body."); } - } else { - const requestResponses = this.#queryCache(r, options); - for (const requestResponse of requestResponses) { - responses.push(requestResponse[1]); + if (request3.mode !== "same-origin" && request3.mode !== "cors") { + throw new TypeError( + 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' + ); } + request3.useCORSPreflightFlag = true; } - const responseList = []; - for (const response of responses) { - const responseObject = fromInnerResponse(response, "immutable"); - responseList.push(responseObject.clone()); - if (responseList.length >= maxResponses) { - break; + let finalBody = inputOrInitBody; + if (initBody == null && inputBody != null) { + if (bodyUnusable(input.#state)) { + throw new TypeError( + "Cannot construct a Request with a Request object that has already been used." + ); } + const identityTransform = new TransformStream(); + inputBody.stream.pipeThrough(identityTransform); + finalBody = { + source: inputBody.source, + length: inputBody.length, + stream: identityTransform.readable + }; } - return Object.freeze(responseList); + this.#state.body = finalBody; } - }; - Object.defineProperties(Cache.prototype, { - [Symbol.toStringTag]: { - value: "Cache", - configurable: true - }, - match: kEnumerableProperty, - matchAll: kEnumerableProperty, - add: kEnumerableProperty, - addAll: kEnumerableProperty, - put: kEnumerableProperty, - delete: kEnumerableProperty, - keys: kEnumerableProperty - }); - var 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 + // Returns request’s HTTP method, which is "GET" by default. + get method() { + webidl.brandCheck(this, _Request); + return this.#state.method; } - ]; - webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters); - webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ - ...cacheQueryOptionConverters, - { - key: "cacheName", - converter: webidl.converters.DOMString + // Returns the URL of request as a string. + get url() { + webidl.brandCheck(this, _Request); + return URLSerializer(this.#state.url); } - ]); - webidl.converters.Response = webidl.interfaceConverter(Response); - webidl.converters["sequence"] = webidl.sequenceConverter( - webidl.converters.RequestInfo - ); - module2.exports = { - Cache - }; - } -}); - -// node_modules/undici/lib/web/cache/cachestorage.js -var require_cachestorage = __commonJS({ - "node_modules/undici/lib/web/cache/cachestorage.js"(exports2, module2) { - "use strict"; - var { kConstruct } = require_symbols4(); - var { Cache } = require_cache(); - var { webidl } = require_webidl(); - var { kEnumerableProperty } = require_util(); - var CacheStorage = class _CacheStorage { - /** - * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map - * @type {Map} + * @param {Request} request + * @param {AbortSignal} newSignal */ - async has(cacheName) { - webidl.brandCheck(this, _CacheStorage); - const prefix = "CacheStorage.has"; - webidl.argumentLengthCheck(arguments, 1, prefix); - cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName"); - return this.#caches.has(cacheName); + static setRequestSignal(request3, newSignal) { + request3.#signal = newSignal; + return request3; } /** - * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open - * @param {string} cacheName - * @returns {Promise} + * @param {Request} request */ - async open(cacheName) { - webidl.brandCheck(this, _CacheStorage); - const prefix = "CacheStorage.open"; - webidl.argumentLengthCheck(arguments, 1, prefix); - cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName"); - if (this.#caches.has(cacheName)) { - const cache2 = this.#caches.get(cacheName); - return new Cache(kConstruct, cache2); - } - const cache = []; - this.#caches.set(cacheName, cache); - return new Cache(kConstruct, cache); + static getRequestDispatcher(request3) { + return request3.#dispatcher; } /** - * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete - * @param {string} cacheName - * @returns {Promise} + * @param {Request} request + * @param {import('../../dispatcher/dispatcher')} newDispatcher */ - 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); + static setRequestDispatcher(request3, newDispatcher) { + request3.#dispatcher = newDispatcher; } /** - * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys - * @returns {Promise} + * @param {Request} request + * @param {Headers} newHeaders */ - async keys() { - webidl.brandCheck(this, _CacheStorage); - const keys = this.#caches.keys(); - return [...keys]; + static setRequestHeaders(request3, newHeaders) { + request3.#headers = newHeaders; + } + /** + * @param {Request} request + */ + static getRequestState(request3) { + return request3.#state; + } + /** + * @param {Request} request + * @param {any} newState + */ + static setRequestState(request3, newState) { + request3.#state = newState; } }; - Object.defineProperties(CacheStorage.prototype, { + var { setRequestSignal, getRequestDispatcher, setRequestDispatcher, setRequestHeaders, getRequestState, setRequestState } = Request; + Reflect.deleteProperty(Request, "setRequestSignal"); + Reflect.deleteProperty(Request, "getRequestDispatcher"); + Reflect.deleteProperty(Request, "setRequestDispatcher"); + Reflect.deleteProperty(Request, "setRequestHeaders"); + Reflect.deleteProperty(Request, "getRequestState"); + Reflect.deleteProperty(Request, "setRequestState"); + mixinBody(Request, getRequestState); + function makeRequest(init2) { + return { + method: init2.method ?? "GET", + localURLsOnly: init2.localURLsOnly ?? false, + unsafeRequest: init2.unsafeRequest ?? false, + body: init2.body ?? null, + client: init2.client ?? null, + reservedClient: init2.reservedClient ?? null, + replacesClientId: init2.replacesClientId ?? "", + window: init2.window ?? "client", + keepalive: init2.keepalive ?? false, + serviceWorkers: init2.serviceWorkers ?? "all", + initiator: init2.initiator ?? "", + destination: init2.destination ?? "", + priority: init2.priority ?? null, + origin: init2.origin ?? "client", + policyContainer: init2.policyContainer ?? "client", + referrer: init2.referrer ?? "client", + referrerPolicy: init2.referrerPolicy ?? "", + mode: init2.mode ?? "no-cors", + useCORSPreflightFlag: init2.useCORSPreflightFlag ?? false, + credentials: init2.credentials ?? "same-origin", + useCredentials: init2.useCredentials ?? false, + cache: init2.cache ?? "default", + redirect: init2.redirect ?? "follow", + integrity: init2.integrity ?? "", + cryptoGraphicsNonceMetadata: init2.cryptoGraphicsNonceMetadata ?? "", + parserMetadata: init2.parserMetadata ?? "", + reloadNavigation: init2.reloadNavigation ?? false, + historyNavigation: init2.historyNavigation ?? false, + userActivation: init2.userActivation ?? false, + taintedOrigin: init2.taintedOrigin ?? false, + redirectCount: init2.redirectCount ?? 0, + responseTainting: init2.responseTainting ?? "basic", + preventNoCacheCacheControlHeaderModification: init2.preventNoCacheCacheControlHeaderModification ?? false, + done: init2.done ?? false, + timingAllowFailed: init2.timingAllowFailed ?? false, + useURLCredentials: init2.useURLCredentials ?? void 0, + traversableForUserPrompts: init2.traversableForUserPrompts ?? "client", + urlList: init2.urlList, + url: init2.urlList[0], + headersList: init2.headersList ? new HeadersList(init2.headersList) : new HeadersList() + }; + } + function cloneRequest(request3) { + const newRequest = makeRequest({ ...request3, body: null }); + if (request3.body != null) { + newRequest.body = cloneBody(request3.body); + } + return newRequest; + } + function fromInnerRequest(innerRequest, dispatcher, signal, guard) { + const request3 = new Request(kConstruct); + setRequestState(request3, innerRequest); + setRequestDispatcher(request3, dispatcher); + setRequestSignal(request3, signal); + const headers = new Headers(kConstruct); + setRequestHeaders(request3, headers); + setHeadersList(headers, innerRequest.headersList); + setHeadersGuard(headers, guard); + return request3; + } + 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: "CacheStorage", + value: "Request", configurable: true - }, - match: kEnumerableProperty, - has: kEnumerableProperty, - open: kEnumerableProperty, - delete: kEnumerableProperty, - keys: kEnumerableProperty + } }); + webidl.is.Request = webidl.util.MakeTypeAssertion(Request); + webidl.converters.RequestInfo = function(V) { + if (typeof V === "string") { + return webidl.converters.USVString(V); + } + if (webidl.is.Request(V)) { + return V; + } + return webidl.converters.USVString(V); + }; + 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" + ) + ) + }, + { + key: "window", + converter: webidl.converters.any + }, + { + key: "duplex", + converter: webidl.converters.DOMString, + allowedValues: requestDuplex + }, + { + key: "dispatcher", + // undici specific option + converter: webidl.converters.any + }, + { + key: "priority", + converter: webidl.converters.DOMString, + allowedValues: ["high", "low", "auto"], + defaultValue: () => "auto" + } + ]); module2.exports = { - CacheStorage + Request, + makeRequest, + fromInnerRequest, + cloneRequest, + getRequestDispatcher, + getRequestState }; } }); -// node_modules/undici/lib/web/cookies/constants.js -var require_constants4 = __commonJS({ - "node_modules/undici/lib/web/cookies/constants.js"(exports2, module2) { +// node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js +var require_subresource_integrity = __commonJS({ + "node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js"(exports2, module2) { "use strict"; - var maxAttributeValueSize = 1024; - var maxNameValuePairSize = 4096; - module2.exports = { - maxAttributeValueSize, - maxNameValuePairSize - }; - } -}); - -// node_modules/undici/lib/web/cookies/util.js -var require_util6 = __commonJS({ - "node_modules/undici/lib/web/cookies/util.js"(exports2, module2) { - "use strict"; - function isCTLExcludingHtab(value) { - for (let i = 0; i < value.length; ++i) { - const code = value.charCodeAt(i); - if (code >= 0 && code <= 8 || code >= 10 && code <= 31 || code === 127) { - return true; - } + var assert = require("node:assert"); + var { runtimeFeatures } = require_runtime_features(); + var { asciiLowercase } = require_infra(); + var validSRIHashAlgorithmTokenSet = /* @__PURE__ */ new Map([["sha256", 0], ["sha384", 1], ["sha512", 2]]); + var crypto3; + if (runtimeFeatures.has("crypto")) { + crypto3 = require("node:crypto"); + const cryptoHashes = crypto3.getHashes(); + if (cryptoHashes.length === 0) { + validSRIHashAlgorithmTokenSet.clear(); } - return false; - } - function validateCookieName(name) { - for (let i = 0; i < name.length; ++i) { - const code = name.charCodeAt(i); - if (code < 33 || // exclude CTLs (0-31), SP and HT - code > 126 || // exclude non-ascii and DEL - code === 34 || // " - code === 40 || // ( - code === 41 || // ) - code === 60 || // < - code === 62 || // > - code === 64 || // @ - code === 44 || // , - code === 59 || // ; - code === 58 || // : - code === 92 || // \ - code === 47 || // / - code === 91 || // [ - code === 93 || // ] - code === 63 || // ? - code === 61 || // = - code === 123 || // { - code === 125) { - throw new Error("Invalid cookie name"); + for (const algorithm of validSRIHashAlgorithmTokenSet.keys()) { + if (cryptoHashes.includes(algorithm) === false) { + validSRIHashAlgorithmTokenSet.delete(algorithm); } } + } else { + validSRIHashAlgorithmTokenSet.clear(); } - function validateCookieValue(value) { - let len = value.length; - let i = 0; - if (value[0] === '"') { - if (len === 1 || value[len - 1] !== '"') { - throw new Error("Invalid cookie value"); + var getSRIHashAlgorithmIndex = ( + /** @type {GetSRIHashAlgorithmIndex} */ + Map.prototype.get.bind( + validSRIHashAlgorithmTokenSet + ) + ); + var isValidSRIHashAlgorithm = (algorithm) => validSRIHashAlgorithmTokenSet.has(asciiLowercase(algorithm)); + var bytesMatch = runtimeFeatures.has("crypto") === false || validSRIHashAlgorithmTokenSet.size === 0 ? () => true : (bytes, metadataList) => { + const parsedMetadata = parseMetadata(metadataList); + if (parsedMetadata.length === 0) { + return true; + } + const metadata = getStrongestMetadata(parsedMetadata); + for (const item of metadata) { + const algorithm = item.alg; + const expectedValue = item.val; + const actualValue = applyAlgorithmToBytes(algorithm, bytes); + if (caseSensitiveMatch(actualValue, expectedValue)) { + return true; } - --len; - ++i; } - while (i < len) { - const code = value.charCodeAt(i++); - if (code < 33 || // exclude CTLs (0-31) - code > 126 || // non-ascii and DEL (127) - code === 34 || // " - code === 44 || // , - code === 59 || // ; - code === 92) { - throw new Error("Invalid cookie value"); + return false; + }; + function getStrongestMetadata(metadataList) { + const result = []; + let strongest = null; + for (const item of metadataList) { + assert(isValidSRIHashAlgorithm(item.alg), "Invalid SRI hash algorithm token"); + if (result.length === 0) { + result.push(item); + strongest = item; + continue; + } + const currentAlgorithm = ( + /** @type {Metadata} */ + strongest.alg + ); + const currentAlgorithmIndex = getSRIHashAlgorithmIndex(currentAlgorithm); + const newAlgorithm = item.alg; + const newAlgorithmIndex = getSRIHashAlgorithmIndex(newAlgorithm); + if (newAlgorithmIndex < currentAlgorithmIndex) { + continue; + } else if (newAlgorithmIndex > currentAlgorithmIndex) { + strongest = item; + result[0] = item; + result.length = 1; + } else { + result.push(item); } } + return result; } - function validateCookiePath(path30) { - for (let i = 0; i < path30.length; ++i) { - const code = path30.charCodeAt(i); - if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii - code === 59) { - throw new Error("Invalid cookie path"); + function parseMetadata(metadata) { + const result = []; + for (const item of metadata.split(" ")) { + const expressionAndOptions = item.split("?", 1); + const algorithmExpression = expressionAndOptions[0]; + let base64Value = ""; + const algorithmAndValue = [algorithmExpression.slice(0, 6), algorithmExpression.slice(7)]; + const algorithm = algorithmAndValue[0]; + if (!isValidSRIHashAlgorithm(algorithm)) { + continue; } + if (algorithmAndValue[1]) { + base64Value = algorithmAndValue[1]; + } + const metadata2 = { + // Possible spec bug? + alg: asciiLowercase(algorithm), + val: base64Value + }; + result.push(metadata2); } + return result; } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } - function validateCookieDomain(domain) { - if (domain === " ") { - return; + var applyAlgorithmToBytes = (algorithm, bytes) => { + return crypto3.hash(algorithm, bytes, "base64"); + }; + function caseSensitiveMatch(actualValue, expectedValue) { + let actualValueLength = actualValue.length; + if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === "=") { + actualValueLength -= 1; } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); + if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === "=") { + actualValueLength -= 1; } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; + let expectedValueLength = expectedValue.length; + if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === "=") { + expectedValueLength -= 1; + } + if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === "=") { + expectedValueLength -= 1; + } + if (actualValueLength !== expectedValueLength) { + return false; + } + for (let i = 0; i < actualValueLength; ++i) { + if (actualValue[i] === expectedValue[i] || actualValue[i] === "+" && expectedValue[i] === "-" || actualValue[i] === "/" && expectedValue[i] === "_") { continue; } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); + return false; + } + return true; + } + module2.exports = { + applyAlgorithmToBytes, + bytesMatch, + caseSensitiveMatch, + isValidSRIHashAlgorithm, + getStrongestMetadata, + parseMetadata + }; + } +}); + +// node_modules/undici/lib/web/fetch/index.js +var require_fetch = __commonJS({ + "node_modules/undici/lib/web/fetch/index.js"(exports2, module2) { + "use strict"; + var { + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse, + fromInnerResponse, + getResponseState + } = require_response(); + var { HeadersList } = require_headers(); + var { Request, cloneRequest, getRequestDispatcher, getRequestState } = require_request2(); + var zlib3 = require("node:zlib"); + var { + makePolicyContainer, + clonePolicyContainer, + requestBadPort, + TAOCheck, + appendRequestOriginHeader, + responseLocationURL, + requestCurrentURL, + setRequestReferrerPolicyOnRedirect, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + createOpaqueTimingInfo, + appendFetchMetadata, + corsCheck, + crossOriginResourcePolicyCheck, + determineRequestsReferrer, + coarsenedSharedCurrentTime, + sameOrigin, + isCancelled, + isAborted, + isErrorLike, + fullyReadBody, + readableStreamClose, + urlIsLocal, + urlIsHttpHttpsScheme, + urlHasHttpsScheme, + clampAndCoarsenConnectionTimingInfo, + simpleRangeHeaderValue, + buildContentRange, + createInflate, + extractMimeType, + hasAuthenticationEntry, + includesCredentials, + isTraversableNavigable + } = require_util2(); + var assert = require("node:assert"); + var { safelyExtractBody, extractBody } = require_body(); + var { + redirectStatusSet, + nullBodyStatus, + safeMethodsSet, + requestBodyHeader, + subresourceSet + } = require_constants3(); + var EE = require("node:events"); + var { Readable: Readable4, pipeline: pipeline2, finished, isErrored, isReadable } = require("node:stream"); + var { addAbortListener, bufferToLowerCasedHeaderName } = require_util(); + var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url(); + var { getGlobalDispatcher } = require_global2(); + var { webidl } = require_webidl(); + var { STATUS_CODES } = require("node:http"); + var { bytesMatch } = require_subresource_integrity(); + var { createDeferredPromise } = require_promise(); + var { isomorphicEncode } = require_infra(); + var { runtimeFeatures } = require_runtime_features(); + var hasZstd = runtimeFeatures.has("zstd"); + var GET_OR_HEAD = ["GET", "HEAD"]; + var defaultUserAgent = typeof __UNDICI_IS_NODE__ !== "undefined" || typeof esbuildDetection !== "undefined" ? "node" : "undici"; + var resolveObjectURL; + var Fetch = class extends EE { + constructor(dispatcher) { + super(); + this.dispatcher = dispatcher; + this.connection = null; + this.dump = false; + this.state = "ongoing"; + } + terminate(reason) { + if (this.state !== "ongoing") { + return; } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); + this.state = "terminated"; + this.connection?.destroy(reason); + this.emit("terminated", reason); + } + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort(error3) { + if (this.state !== "ongoing") { + return; } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); + this.state = "aborted"; + if (!error3) { + error3 = new DOMException("The operation was aborted.", "AbortError"); } + this.serializedAbortReason = error3; + this.connection?.destroy(error3); + this.emit("terminated", error3); } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { - throw new Error("Invalid cookie domain"); - } + }; + function handleFetchDone(response) { + finalizeAndReportTiming(response, "fetch"); } - var IMFDays = [ - "Sun", - "Mon", - "Tue", - "Wed", - "Thu", - "Fri", - "Sat" - ]; - var IMFMonths = [ - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec" - ]; - var IMFPaddedNumbers = Array(61).fill(0).map((_2, i) => i.toString().padStart(2, "0")); - function toIMFDate(date) { - if (typeof date === "number") { - date = new Date(date); + function fetch(input, init2 = void 0) { + webidl.argumentLengthCheck(arguments, 1, "globalThis.fetch"); + let p = createDeferredPromise(); + let requestObject; + try { + requestObject = new Request(input, init2); + } catch (e) { + p.reject(e); + return p.promise; } - return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT`; - } - function validateCookieMaxAge(maxAge) { - if (maxAge < 0) { - throw new Error("Invalid cookie max-age"); + const request3 = getRequestState(requestObject); + if (requestObject.signal.aborted) { + abortFetch(p, request3, null, requestObject.signal.reason, null); + return p.promise; + } + const globalObject = request3.client.globalObject; + if (globalObject?.constructor?.name === "ServiceWorkerGlobalScope") { + request3.serviceWorkers = "none"; } + let responseObject = null; + let locallyAborted = false; + let controller = null; + addAbortListener( + requestObject.signal, + () => { + locallyAborted = true; + assert(controller != null); + controller.abort(requestObject.signal.reason); + const realResponse = responseObject?.deref(); + abortFetch(p, request3, realResponse, requestObject.signal.reason, controller.controller); + } + ); + const processResponse = (response) => { + if (locallyAborted) { + return; + } + if (response.aborted) { + abortFetch(p, request3, responseObject, controller.serializedAbortReason, controller.controller); + return; + } + if (response.type === "error") { + p.reject(new TypeError("fetch failed", { cause: response.error })); + return; + } + responseObject = new WeakRef(fromInnerResponse(response, "immutable")); + p.resolve(responseObject.deref()); + p = null; + }; + controller = fetching({ + request: request3, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: getRequestDispatcher(requestObject), + // undici + // Keep requestObject alive to prevent its AbortController from being GC'd + // See https://github.com/nodejs/undici/issues/4627 + requestObject + }); + return p.promise; } - function stringify(cookie) { - if (cookie.name.length === 0) { - return null; + function finalizeAndReportTiming(response, initiatorType = "other") { + if (response.type === "error" && response.aborted) { + return; } - validateCookieName(cookie.name); - validateCookieValue(cookie.value); - const out = [`${cookie.name}=${cookie.value}`]; - if (cookie.name.startsWith("__Secure-")) { - cookie.secure = true; + if (!response.urlList?.length) { + return; } - if (cookie.name.startsWith("__Host-")) { - cookie.secure = true; - cookie.domain = null; - cookie.path = "/"; + const originalURL = response.urlList[0]; + let timingInfo = response.timingInfo; + let cacheState = response.cacheState; + if (!urlIsHttpHttpsScheme(originalURL)) { + return; } - if (cookie.secure) { - out.push("Secure"); + if (timingInfo === null) { + return; } - if (cookie.httpOnly) { - out.push("HttpOnly"); + if (!response.timingAllowPassed) { + timingInfo = createOpaqueTimingInfo({ + startTime: timingInfo.startTime + }); + cacheState = ""; } - if (typeof cookie.maxAge === "number") { - validateCookieMaxAge(cookie.maxAge); - out.push(`Max-Age=${cookie.maxAge}`); + timingInfo.endTime = coarsenedSharedCurrentTime(); + response.timingInfo = timingInfo; + markResourceTiming( + timingInfo, + originalURL.href, + initiatorType, + globalThis, + cacheState, + "", + // bodyType + response.status + ); + } + var markResourceTiming = performance.markResourceTiming; + function abortFetch(p, request3, responseObject, error3, controller) { + if (p) { + p.reject(error3); } - if (cookie.domain) { - validateCookieDomain(cookie.domain); - out.push(`Domain=${cookie.domain}`); + if (request3.body?.stream != null && isReadable(request3.body.stream)) { + request3.body.stream.cancel(error3).catch((err) => { + if (err.code === "ERR_INVALID_STATE") { + return; + } + throw err; + }); } - if (cookie.path) { - validateCookiePath(cookie.path); - out.push(`Path=${cookie.path}`); + if (responseObject == null) { + return; } - if (cookie.expires && cookie.expires.toString() !== "Invalid Date") { - out.push(`Expires=${toIMFDate(cookie.expires)}`); + const response = getResponseState(responseObject); + if (response.body?.stream != null && isReadable(response.body.stream)) { + controller.error(error3); } - if (cookie.sameSite) { - out.push(`SameSite=${cookie.sameSite}`); + } + function fetching({ + request: request3, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseEndOfBody, + processResponseConsumeBody, + useParallelQueue = false, + dispatcher = getGlobalDispatcher(), + // undici + requestObject = null + // Keep alive to prevent AbortController GC, see #4627 + }) { + assert(dispatcher); + let taskDestination = null; + let crossOriginIsolatedCapability = false; + if (request3.client != null) { + taskDestination = request3.client.globalObject; + crossOriginIsolatedCapability = request3.client.crossOriginIsolatedCapability; } - for (const part of cookie.unparsed) { - if (!part.includes("=")) { - throw new Error("Invalid unparsed"); + const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability); + const timingInfo = createOpaqueTimingInfo({ + startTime: currentTime + }); + const fetchParams = { + controller: new Fetch(dispatcher), + request: request3, + timingInfo, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseConsumeBody, + processResponseEndOfBody, + taskDestination, + crossOriginIsolatedCapability, + // Keep requestObject alive to prevent its AbortController from being GC'd + requestObject + }; + assert(!request3.body || request3.body.stream); + if (request3.window === "client") { + request3.window = request3.client?.globalObject?.constructor?.name === "Window" ? request3.client : "no-window"; + } + if (request3.origin === "client") { + request3.origin = request3.client.origin; + } + if (request3.policyContainer === "client") { + if (request3.client != null) { + request3.policyContainer = clonePolicyContainer( + request3.client.policyContainer + ); + } else { + request3.policyContainer = makePolicyContainer(); } - const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); } - return out.join("; "); - } - module2.exports = { - isCTLExcludingHtab, - validateCookieName, - validateCookiePath, - validateCookieValue, - toIMFDate, - stringify - }; - } -}); - -// node_modules/undici/lib/web/cookies/parse.js -var require_parse = __commonJS({ - "node_modules/undici/lib/web/cookies/parse.js"(exports2, module2) { - "use strict"; - var { maxNameValuePairSize, maxAttributeValueSize } = require_constants4(); - var { isCTLExcludingHtab } = require_util6(); - var { collectASequenceOfCodePointsFast } = require_data_url(); - var assert = require("node:assert"); - function parseSetCookie(header) { - if (isCTLExcludingHtab(header)) { - return null; + if (!request3.headersList.contains("accept", true)) { + const value = "*/*"; + request3.headersList.append("accept", value, true); } - let nameValuePair = ""; - let unparsedAttributes = ""; - let name = ""; - let value = ""; - if (header.includes(";")) { - const position = { position: 0 }; - nameValuePair = collectASequenceOfCodePointsFast(";", header, position); - unparsedAttributes = header.slice(position.position); - } else { - nameValuePair = header; + if (!request3.headersList.contains("accept-language", true)) { + request3.headersList.append("accept-language", "*", true); } - if (!nameValuePair.includes("=")) { - value = nameValuePair; - } else { - const position = { position: 0 }; - name = collectASequenceOfCodePointsFast( - "=", - nameValuePair, - position - ); - value = nameValuePair.slice(position.position + 1); + if (request3.priority === null) { } - name = name.trim(); - value = value.trim(); - if (name.length + value.length > maxNameValuePairSize) { - return null; + if (subresourceSet.has(request3.destination)) { } - return { - name, - value, - ...parseUnparsedAttributes(unparsedAttributes) - }; + mainFetch(fetchParams, false); + return fetchParams.controller; } - function parseUnparsedAttributes(unparsedAttributes, cookieAttributeList = {}) { - if (unparsedAttributes.length === 0) { - return cookieAttributeList; - } - assert(unparsedAttributes[0] === ";"); - unparsedAttributes = unparsedAttributes.slice(1); - let cookieAv = ""; - if (unparsedAttributes.includes(";")) { - cookieAv = collectASequenceOfCodePointsFast( - ";", - unparsedAttributes, - { position: 0 } - ); - unparsedAttributes = unparsedAttributes.slice(cookieAv.length); - } else { - cookieAv = unparsedAttributes; - unparsedAttributes = ""; - } - let attributeName = ""; - let attributeValue = ""; - if (cookieAv.includes("=")) { - const position = { position: 0 }; - attributeName = collectASequenceOfCodePointsFast( - "=", - cookieAv, - position - ); - attributeValue = cookieAv.slice(position.position + 1); - } else { - attributeName = cookieAv; - } - attributeName = attributeName.trim(); - attributeValue = attributeValue.trim(); - if (attributeValue.length > maxAttributeValueSize) { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList); - } - const attributeNameLowercase = attributeName.toLowerCase(); - if (attributeNameLowercase === "expires") { - const expiryTime = new Date(attributeValue); - cookieAttributeList.expires = expiryTime; - } else if (attributeNameLowercase === "max-age") { - const charCode = attributeValue.charCodeAt(0); - if ((charCode < 48 || charCode > 57) && attributeValue[0] !== "-") { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList); - } - if (!/^\d+$/.test(attributeValue)) { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList); - } - const deltaSeconds = Number(attributeValue); - cookieAttributeList.maxAge = deltaSeconds; - } else if (attributeNameLowercase === "domain") { - let cookieDomain = attributeValue; - if (cookieDomain[0] === ".") { - cookieDomain = cookieDomain.slice(1); - } - cookieDomain = cookieDomain.toLowerCase(); - cookieAttributeList.domain = cookieDomain; - } else if (attributeNameLowercase === "path") { - let cookiePath = ""; - if (attributeValue.length === 0 || attributeValue[0] !== "/") { - cookiePath = "/"; + async function mainFetch(fetchParams, recursive) { + try { + const request3 = fetchParams.request; + let response = null; + if (request3.localURLsOnly && !urlIsLocal(requestCurrentURL(request3))) { + response = makeNetworkError("local URLs only"); + } + tryUpgradeRequestToAPotentiallyTrustworthyURL(request3); + if (requestBadPort(request3) === "blocked") { + response = makeNetworkError("bad port"); + } + if (request3.referrerPolicy === "") { + request3.referrerPolicy = request3.policyContainer.referrerPolicy; + } + if (request3.referrer !== "no-referrer") { + request3.referrer = determineRequestsReferrer(request3); + } + if (response === null) { + const currentURL = requestCurrentURL(request3); + if ( + // - request’s current URL’s origin is same origin with request’s origin, + // and request’s response tainting is "basic" + sameOrigin(currentURL, request3.url) && request3.responseTainting === "basic" || // request’s current URL’s scheme is "data" + currentURL.protocol === "data:" || // - request’s mode is "navigate" or "websocket" + (request3.mode === "navigate" || request3.mode === "websocket") + ) { + request3.responseTainting = "basic"; + response = await schemeFetch(fetchParams); + } else if (request3.mode === "same-origin") { + response = makeNetworkError('request mode cannot be "same-origin"'); + } else if (request3.mode === "no-cors") { + if (request3.redirect !== "follow") { + response = makeNetworkError( + 'redirect mode cannot be "follow" for "no-cors" request' + ); + } else { + request3.responseTainting = "opaque"; + response = await schemeFetch(fetchParams); + } + } else if (!urlIsHttpHttpsScheme(requestCurrentURL(request3))) { + response = makeNetworkError("URL scheme must be a HTTP(S) scheme"); + } else { + request3.responseTainting = "cors"; + response = await httpFetch(fetchParams); + } + } + if (recursive) { + return response; + } + if (response.status !== 0 && !response.internalResponse) { + if (request3.responseTainting === "cors") { + } + if (request3.responseTainting === "basic") { + response = filterResponse(response, "basic"); + } else if (request3.responseTainting === "cors") { + response = filterResponse(response, "cors"); + } else if (request3.responseTainting === "opaque") { + response = filterResponse(response, "opaque"); + } else { + assert(false); + } + } + let internalResponse = response.status === 0 ? response : response.internalResponse; + if (internalResponse.urlList.length === 0) { + internalResponse.urlList.push(...request3.urlList); + } + if (!request3.timingAllowFailed) { + response.timingAllowPassed = true; + } + if (response.type === "opaque" && internalResponse.status === 206 && internalResponse.rangeRequested && !request3.headers.contains("range", true)) { + response = internalResponse = makeNetworkError(); + } + if (response.status !== 0 && (request3.method === "HEAD" || request3.method === "CONNECT" || nullBodyStatus.includes(internalResponse.status))) { + internalResponse.body = null; + fetchParams.controller.dump = true; + } + if (request3.integrity) { + const processBodyError = (reason) => fetchFinale(fetchParams, makeNetworkError(reason)); + if (request3.responseTainting === "opaque" || response.body == null) { + processBodyError(response.error); + return; + } + const processBody = (bytes) => { + if (!bytesMatch(bytes, request3.integrity)) { + processBodyError("integrity mismatch"); + return; + } + response.body = safelyExtractBody(bytes)[0]; + fetchFinale(fetchParams, response); + }; + fullyReadBody(response.body, processBody, processBodyError); } else { - cookiePath = attributeValue; - } - cookieAttributeList.path = cookiePath; - } else if (attributeNameLowercase === "secure") { - cookieAttributeList.secure = true; - } else if (attributeNameLowercase === "httponly") { - cookieAttributeList.httpOnly = true; - } else if (attributeNameLowercase === "samesite") { - const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + fetchFinale(fetchParams, response); } - } else { - cookieAttributeList.unparsed ??= []; - cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); + } catch (err) { + fetchParams.controller.terminate(err); } - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList); } - module2.exports = { - parseSetCookie, - parseUnparsedAttributes - }; - } -}); - -// node_modules/undici/lib/web/cookies/index.js -var require_cookies = __commonJS({ - "node_modules/undici/lib/web/cookies/index.js"(exports2, module2) { - "use strict"; - var { parseSetCookie } = require_parse(); - var { stringify } = require_util6(); - var { webidl } = require_webidl(); - var { Headers } = require_headers(); - 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; + function schemeFetch(fetchParams) { + if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { + return Promise.resolve(makeAppropriateNetworkError(fetchParams)); } - for (const piece of cookie.split(";")) { - const [name, ...value] = piece.split("="); - out[name.trim()] = value.join("="); + const { request: request3 } = fetchParams; + const { protocol: scheme } = requestCurrentURL(request3); + switch (scheme) { + case "about:": { + return Promise.resolve(makeNetworkError("about scheme is not supported")); + } + case "blob:": { + if (!resolveObjectURL) { + resolveObjectURL = require("node:buffer").resolveObjectURL; + } + const blobURLEntry = requestCurrentURL(request3); + if (blobURLEntry.search.length !== 0) { + return Promise.resolve(makeNetworkError("NetworkError when attempting to fetch resource.")); + } + const blob = resolveObjectURL(blobURLEntry.toString()); + if (request3.method !== "GET" || !webidl.is.Blob(blob)) { + return Promise.resolve(makeNetworkError("invalid method")); + } + const response = makeResponse(); + const fullLength = blob.size; + const serializedFullLength = isomorphicEncode(`${fullLength}`); + const type = blob.type; + if (!request3.headersList.contains("range", true)) { + const bodyWithType = extractBody(blob); + response.statusText = "OK"; + response.body = bodyWithType[0]; + response.headersList.set("content-length", serializedFullLength, true); + response.headersList.set("content-type", type, true); + } else { + response.rangeRequested = true; + const rangeHeader = request3.headersList.get("range", true); + const rangeValue = simpleRangeHeaderValue(rangeHeader, true); + if (rangeValue === "failure") { + return Promise.resolve(makeNetworkError("failed to fetch the data URL")); + } + let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue; + if (rangeStart === null) { + rangeStart = fullLength - rangeEnd; + rangeEnd = rangeStart + rangeEnd - 1; + } else { + if (rangeStart >= fullLength) { + return Promise.resolve(makeNetworkError("Range start is greater than the blob's size.")); + } + if (rangeEnd === null || rangeEnd >= fullLength) { + rangeEnd = fullLength - 1; + } + } + const slicedBlob = blob.slice(rangeStart, rangeEnd + 1, type); + const slicedBodyWithType = extractBody(slicedBlob); + response.body = slicedBodyWithType[0]; + const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`); + const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength); + response.status = 206; + response.statusText = "Partial Content"; + response.headersList.set("content-length", serializedSlicedLength, true); + response.headersList.set("content-type", type, true); + response.headersList.set("content-range", contentRange, true); + } + return Promise.resolve(response); + } + case "data:": { + const currentURL = requestCurrentURL(request3); + const dataURLStruct = dataURLProcessor(currentURL); + if (dataURLStruct === "failure") { + return Promise.resolve(makeNetworkError("failed to fetch the data URL")); + } + const mimeType = serializeAMimeType(dataURLStruct.mimeType); + return Promise.resolve(makeResponse({ + statusText: "OK", + headersList: [ + ["content-type", { name: "Content-Type", value: mimeType }] + ], + body: safelyExtractBody(dataURLStruct.body)[0] + })); + } + case "file:": { + return Promise.resolve(makeNetworkError("not implemented... yet...")); + } + case "http:": + case "https:": { + return httpFetch(fetchParams).catch((err) => makeNetworkError(err)); + } + default: { + return Promise.resolve(makeNetworkError("unknown scheme")); + } } - return out; - } - 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); - setCookie(headers, { - name, - value: "", - expires: /* @__PURE__ */ new Date(0), - ...attributes - }); } - function getSetCookies(headers) { - webidl.argumentLengthCheck(arguments, 1, "getSetCookies"); - webidl.brandCheck(headers, Headers, { strict: false }); - const cookies = headers.getSetCookie(); - if (!cookies) { - return []; + function finalizeResponse(fetchParams, response) { + fetchParams.request.done = true; + if (fetchParams.processResponseDone != null) { + queueMicrotask(() => fetchParams.processResponseDone(response)); } - return cookies.map((pair) => parseSetCookie(pair)); } - 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); + function fetchFinale(fetchParams, response) { + let timingInfo = fetchParams.timingInfo; + const processResponseEndOfBody = () => { + const unsafeEndTime = Date.now(); + if (fetchParams.request.destination === "document") { + fetchParams.controller.fullTimingInfo = timingInfo; + } + fetchParams.controller.reportTimingSteps = () => { + if (!urlIsHttpHttpsScheme(fetchParams.request.url)) { + return; + } + timingInfo.endTime = unsafeEndTime; + let cacheState = response.cacheState; + const bodyInfo = response.bodyInfo; + if (!response.timingAllowPassed) { + timingInfo = createOpaqueTimingInfo(timingInfo); + cacheState = ""; + } + let responseStatus = 0; + if (fetchParams.request.mode !== "navigate" || !response.hasCrossOriginRedirects) { + responseStatus = response.status; + const mimeType = extractMimeType(response.headersList); + if (mimeType !== "failure") { + bodyInfo.contentType = minimizeSupportedMimeType(mimeType); + } + } + if (fetchParams.request.initiatorType != null) { + markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus); + } + }; + const processResponseEndOfBodyTask = () => { + fetchParams.request.done = true; + if (fetchParams.processResponseEndOfBody != null) { + queueMicrotask(() => fetchParams.processResponseEndOfBody(response)); + } + if (fetchParams.request.initiatorType != null) { + fetchParams.controller.reportTimingSteps(); + } + }; + queueMicrotask(() => processResponseEndOfBodyTask()); + }; + if (fetchParams.processResponse != null) { + queueMicrotask(() => { + fetchParams.processResponse(response); + fetchParams.processResponse = null; + }); + } + const internalResponse = response.type === "error" ? response : response.internalResponse ?? response; + if (internalResponse.body == null) { + processResponseEndOfBody(); + } else { + finished(internalResponse.body.stream, () => { + processResponseEndOfBody(); + }); } } - 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 + async function httpFetch(fetchParams) { + const request3 = fetchParams.request; + let response = null; + let actualResponse = null; + const timingInfo = fetchParams.timingInfo; + if (request3.serviceWorkers === "all") { } - ]); - 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) + if (response === null) { + if (request3.redirect === "follow") { + request3.serviceWorkers = "none"; + } + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams); + if (request3.responseTainting === "cors" && corsCheck(request3, response) === "failure") { + return makeNetworkError("cors failure"); + } + if (TAOCheck(request3, response) === "failure") { + request3.timingAllowFailed = true; + } } - ]); - module2.exports = { - getCookies, - deleteCookie, - getSetCookies, - setCookie - }; - } -}); - -// node_modules/undici/lib/web/websocket/events.js -var require_events = __commonJS({ - "node_modules/undici/lib/web/websocket/events.js"(exports2, module2) { - "use strict"; - var { webidl } = require_webidl(); - var { kEnumerableProperty } = require_util(); - var { kConstruct } = require_symbols(); - var { MessagePort } = require("node:worker_threads"); - var MessageEvent = class _MessageEvent extends Event { - #eventInit; - constructor(type, eventInitDict = {}) { - if (type === kConstruct) { - super(arguments[1], arguments[2]); - webidl.util.markAsUncloneable(this); - return; + if ((request3.responseTainting === "opaque" || response.type === "opaque") && crossOriginResourcePolicyCheck( + request3.origin, + request3.client, + request3.destination, + actualResponse + ) === "blocked") { + return makeNetworkError("blocked"); + } + if (redirectStatusSet.has(actualResponse.status)) { + if (request3.redirect !== "manual") { + fetchParams.controller.connection.destroy(void 0, false); + } + if (request3.redirect === "error") { + response = makeNetworkError("unexpected redirect"); + } else if (request3.redirect === "manual") { + response = actualResponse; + } else if (request3.redirect === "follow") { + response = await httpRedirectFetch(fetchParams, response); + } else { + assert(false); } - 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; + response.timingInfo = timingInfo; + return response; + } + function httpRedirectFetch(fetchParams, response) { + const request3 = fetchParams.request; + const actualResponse = response.internalResponse ? response.internalResponse : response; + let locationURL; + try { + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request3).hash + ); + if (locationURL == null) { + return response; + } + } catch (err) { + return Promise.resolve(makeNetworkError(err)); } - get origin() { - webidl.brandCheck(this, _MessageEvent); - return this.#eventInit.origin; + if (!urlIsHttpHttpsScheme(locationURL)) { + return Promise.resolve(makeNetworkError("URL scheme must be a HTTP(S) scheme")); } - get lastEventId() { - webidl.brandCheck(this, _MessageEvent); - return this.#eventInit.lastEventId; + if (request3.redirectCount === 20) { + return Promise.resolve(makeNetworkError("redirect count exceeded")); } - get source() { - webidl.brandCheck(this, _MessageEvent); - return this.#eventInit.source; + request3.redirectCount += 1; + if (request3.mode === "cors" && (locationURL.username || locationURL.password) && !sameOrigin(request3, locationURL)) { + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')); } - get ports() { - webidl.brandCheck(this, _MessageEvent); - if (!Object.isFrozen(this.#eventInit.ports)) { - Object.freeze(this.#eventInit.ports); + if (request3.responseTainting === "cors" && (locationURL.username || locationURL.password)) { + return Promise.resolve(makeNetworkError( + 'URL cannot contain credentials for request mode "cors"' + )); + } + if (actualResponse.status !== 303 && request3.body != null && request3.body.source == null) { + return Promise.resolve(makeNetworkError()); + } + if ([301, 302].includes(actualResponse.status) && request3.method === "POST" || actualResponse.status === 303 && !GET_OR_HEAD.includes(request3.method)) { + request3.method = "GET"; + request3.body = null; + for (const headerName of requestBodyHeader) { + request3.headersList.delete(headerName); } - 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 - }); + if (!sameOrigin(requestCurrentURL(request3), locationURL)) { + request3.headersList.delete("authorization", true); + request3.headersList.delete("proxy-authorization", true); + request3.headersList.delete("cookie", true); + request3.headersList.delete("host", true); } - static createFastMessageEvent(type, init2) { - const messageEvent = new _MessageEvent(kConstruct, type, init2); - messageEvent.#eventInit = init2; - messageEvent.#eventInit.data ??= null; - messageEvent.#eventInit.origin ??= ""; - messageEvent.#eventInit.lastEventId ??= ""; - messageEvent.#eventInit.source ??= null; - messageEvent.#eventInit.ports ??= []; - return messageEvent; + if (request3.body != null) { + assert(request3.body.source != null); + request3.body = safelyExtractBody(request3.body.source)[0]; } - }; - var { createFastMessageEvent } = MessageEvent; - delete MessageEvent.createFastMessageEvent; - var CloseEvent = 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); + const timingInfo = fetchParams.timingInfo; + timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability); + if (timingInfo.redirectStartTime === 0) { + timingInfo.redirectStartTime = timingInfo.startTime; } - get wasClean() { - webidl.brandCheck(this, _CloseEvent); - return this.#eventInit.wasClean; + request3.urlList.push(locationURL); + setRequestReferrerPolicyOnRedirect(request3, actualResponse); + return mainFetch(fetchParams, true); + } + async function httpNetworkOrCacheFetch(fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false) { + const request3 = fetchParams.request; + let httpFetchParams = null; + let httpRequest = null; + let response = null; + const httpCache = null; + const revalidatingFlag = false; + if (request3.window === "no-window" && request3.redirect === "error") { + httpFetchParams = fetchParams; + httpRequest = request3; + } else { + httpRequest = cloneRequest(request3); + httpFetchParams = { ...fetchParams }; + httpFetchParams.request = httpRequest; } - get code() { - webidl.brandCheck(this, _CloseEvent); - return this.#eventInit.code; + const includeCredentials = request3.credentials === "include" || request3.credentials === "same-origin" && request3.responseTainting === "basic"; + const contentLength = httpRequest.body ? httpRequest.body.length : null; + let contentLengthHeaderValue = null; + if (httpRequest.body == null && ["POST", "PUT"].includes(httpRequest.method)) { + contentLengthHeaderValue = "0"; } - get reason() { - webidl.brandCheck(this, _CloseEvent); - return this.#eventInit.reason; + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`); } - }; - var ErrorEvent = 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; + if (contentLengthHeaderValue != null && !httpRequest.headersList.contains("content-length", true)) { + httpRequest.headersList.append("content-length", contentLengthHeaderValue, true); } - get message() { - webidl.brandCheck(this, _ErrorEvent); - return this.#eventInit.message; + if (contentLength != null && httpRequest.keepalive) { } - get filename() { - webidl.brandCheck(this, _ErrorEvent); - return this.#eventInit.filename; + if (webidl.is.URL(httpRequest.referrer)) { + httpRequest.headersList.append("referer", isomorphicEncode(httpRequest.referrer.href), true); } - get lineno() { - webidl.brandCheck(this, _ErrorEvent); - return this.#eventInit.lineno; + appendRequestOriginHeader(httpRequest); + appendFetchMetadata(httpRequest); + if (!httpRequest.headersList.contains("user-agent", true)) { + httpRequest.headersList.append("user-agent", defaultUserAgent, true); } - get colno() { - webidl.brandCheck(this, _ErrorEvent); - return this.#eventInit.colno; + 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"; } - get error() { - webidl.brandCheck(this, _ErrorEvent); - return this.#eventInit.error; + if (httpRequest.cache === "no-cache" && !httpRequest.preventNoCacheCacheControlHeaderModification && !httpRequest.headersList.contains("cache-control", true)) { + httpRequest.headersList.append("cache-control", "max-age=0", true); } - }; - 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 - ); - var 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 - } - ]); - module2.exports = { - MessageEvent, - CloseEvent, - ErrorEvent, - createFastMessageEvent - }; - } -}); - -// node_modules/undici/lib/web/websocket/constants.js -var require_constants5 = __commonJS({ - "node_modules/undici/lib/web/websocket/constants.js"(exports2, module2) { - "use strict"; - var uid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - var staticPropertyDescriptors = { - enumerable: true, - writable: false, - configurable: false - }; - var states = { - CONNECTING: 0, - OPEN: 1, - CLOSING: 2, - CLOSED: 3 - }; - var sentCloseFrameState = { - NOT_SENT: 0, - PROCESSING: 1, - SENT: 2 - }; - var opcodes = { - CONTINUATION: 0, - TEXT: 1, - BINARY: 2, - CLOSE: 8, - PING: 9, - PONG: 10 - }; - var maxUnsigned16Bit = 2 ** 16 - 1; - var parserStates = { - INFO: 0, - PAYLOADLENGTH_16: 2, - PAYLOADLENGTH_64: 3, - READ_DATA: 4 - }; - var emptyBuffer = Buffer.allocUnsafe(0); - var sendHints = { - string: 1, - typedArray: 2, - arrayBuffer: 3, - blob: 4 - }; - module2.exports = { - uid, - sentCloseFrameState, - staticPropertyDescriptors, - states, - opcodes, - maxUnsigned16Bit, - parserStates, - emptyBuffer, - sendHints - }; - } -}); - -// node_modules/undici/lib/web/websocket/symbols.js -var require_symbols5 = __commonJS({ - "node_modules/undici/lib/web/websocket/symbols.js"(exports2, module2) { - "use strict"; - module2.exports = { - kWebSocketURL: /* @__PURE__ */ Symbol("url"), - kReadyState: /* @__PURE__ */ Symbol("ready state"), - kController: /* @__PURE__ */ Symbol("controller"), - kResponse: /* @__PURE__ */ Symbol("response"), - kBinaryType: /* @__PURE__ */ Symbol("binary type"), - kSentClose: /* @__PURE__ */ Symbol("sent close"), - kReceivedClose: /* @__PURE__ */ Symbol("received close"), - kByteParser: /* @__PURE__ */ Symbol("byte parser") - }; - } -}); - -// node_modules/undici/lib/web/websocket/util.js -var require_util7 = __commonJS({ - "node_modules/undici/lib/web/websocket/util.js"(exports2, module2) { - "use strict"; - var { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = require_symbols5(); - var { states, opcodes } = require_constants5(); - var { ErrorEvent, createFastMessageEvent } = require_events(); - var { isUtf8 } = require("node:buffer"); - var { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = require_data_url(); - function isConnecting(ws) { - return ws[kReadyState] === states.CONNECTING; - } - function isEstablished(ws) { - return ws[kReadyState] === states.OPEN; - } - function isClosing(ws) { - return ws[kReadyState] === states.CLOSING; - } - function isClosed(ws) { - return ws[kReadyState] === states.CLOSED; - } - function fireEvent(e, target, eventFactory = (type, init2) => new Event(type, init2), eventInitDict = {}) { - const event = eventFactory(e, eventInitDict); - target.dispatchEvent(event); - } - function websocketMessageReceived(ws, type, data) { - if (ws[kReadyState] !== states.OPEN) { - return; - } - let dataForEvent; - if (type === opcodes.TEXT) { - try { - dataForEvent = utf8Decode(data); - } catch { - failWebsocketConnection(ws, "Received invalid UTF-8 in text frame."); - return; + if (httpRequest.cache === "no-store" || httpRequest.cache === "reload") { + if (!httpRequest.headersList.contains("pragma", true)) { + httpRequest.headersList.append("pragma", "no-cache", true); } - } else if (type === opcodes.BINARY) { - if (ws[kBinaryType] === "blob") { - dataForEvent = new Blob([data]); - } else { - dataForEvent = toArrayBuffer(data); + if (!httpRequest.headersList.contains("cache-control", true)) { + httpRequest.headersList.append("cache-control", "no-cache", true); } } - 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); - } - function isValidSubprotocol(protocol) { - if (protocol.length === 0) { - return false; + if (httpRequest.headersList.contains("range", true)) { + httpRequest.headersList.append("accept-encoding", "identity", true); } - for (let i = 0; i < protocol.length; ++i) { - const code = protocol.charCodeAt(i); - if (code < 33 || // CTL, contains SP (0x20) and HT (0x09) - code > 126 || code === 34 || // " - code === 40 || // ( - code === 41 || // ) - code === 44 || // , - code === 47 || // / - code === 58 || // : - code === 59 || // ; - code === 60 || // < - code === 61 || // = - code === 62 || // > - code === 63 || // ? - code === 64 || // @ - code === 91 || // [ - code === 92 || // \ - code === 93 || // ] - code === 123 || // { - code === 125) { - return false; + 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); } } - return true; - } - function isValidStatusCode(code) { - if (code >= 1e3 && code < 1015) { - return code !== 1004 && // reserved - code !== 1005 && // "MUST NOT be set as a status code" - code !== 1006; + httpRequest.headersList.delete("host", true); + if (includeCredentials) { + if (!httpRequest.headersList.contains("authorization", true)) { + let authorizationValue = null; + if (hasAuthenticationEntry(httpRequest) && (httpRequest.useURLCredentials === void 0 || !includesCredentials(requestCurrentURL(httpRequest)))) { + } else if (includesCredentials(requestCurrentURL(httpRequest)) && isAuthenticationFetch) { + const { username, password } = requestCurrentURL(httpRequest); + authorizationValue = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`; + } + if (authorizationValue !== null) { + httpRequest.headersList.append("Authorization", authorizationValue, false); + } + } } - return code >= 3e3 && code <= 4999; - } - function failWebsocketConnection(ws, reason) { - const { [kController]: controller, [kResponse]: response } = ws; - controller.abort(); - if (response?.socket && !response.socket.destroyed) { - response.socket.destroy(); + if (httpCache == null) { + httpRequest.cache = "no-store"; } - if (reason) { - fireEvent("error", ws, (type, init2) => new ErrorEvent(type, init2), { - error: new Error(reason), - message: reason - }); + if (httpRequest.cache !== "no-store" && httpRequest.cache !== "reload") { } - } - 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); - } - function parseExtensions(extensions) { - const position = { position: 0 }; - const extensionList = /* @__PURE__ */ 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) + if (response == null) { + if (httpRequest.cache === "only-if-cached") { + return makeNetworkError("only if cached"); + } + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch ); - position.position++; - } - return extensionList; - } - function isValidClientWindowBits(value) { - if (value.length === 0) { - return false; - } - for (let i = 0; i < value.length; i++) { - const byte = value.charCodeAt(i); - if (byte < 48 || byte > 57) { - return false; + if (!safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399) { + } + if (revalidatingFlag && forwardResponse.status === 304) { + } + if (response == null) { + response = forwardResponse; } } - const num = Number.parseInt(value, 10); - return num >= 8 && num <= 15; - } - var hasIntl = typeof process.versions.icu === "string"; - var fatalDecoder = hasIntl ? new TextDecoder("utf-8", { fatal: true }) : void 0; - var utf8Decode = hasIntl ? fatalDecoder.decode.bind(fatalDecoder) : function(buffer) { - if (isUtf8(buffer)) { - return buffer.toString("utf-8"); + response.urlList = [...httpRequest.urlList]; + if (httpRequest.headersList.contains("range", true)) { + response.rangeRequested = true; } - throw new TypeError("Invalid utf-8 received."); - }; - module2.exports = { - isConnecting, - isEstablished, - isClosing, - isClosed, - fireEvent, - isValidSubprotocol, - isValidStatusCode, - failWebsocketConnection, - websocketMessageReceived, - utf8Decode, - isControlFrame, - isContinuationFrame, - isTextBinaryFrame, - isValidOpcode, - parseExtensions, - isValidClientWindowBits - }; - } -}); - -// node_modules/undici/lib/web/websocket/frame.js -var require_frame = __commonJS({ - "node_modules/undici/lib/web/websocket/frame.js"(exports2, module2) { - "use strict"; - var { maxUnsigned16Bit } = require_constants5(); - var BUFFER_SIZE = 16386; - var crypto3; - var buffer = null; - var bufIdx = BUFFER_SIZE; - try { - crypto3 = require("node:crypto"); - } catch { - crypto3 = { - // not full compatibility, but minimum. - randomFillSync: function randomFillSync(buffer2, _offset, _size) { - for (let i = 0; i < buffer2.length; ++i) { - buffer2[i] = Math.random() * 255 | 0; + response.requestIncludesCredentials = includeCredentials; + if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && (request3.useURLCredentials !== void 0 || isTraversableNavigable(request3.traversableForUserPrompts))) { + if (request3.body != null) { + if (request3.body.source == null) { + return response; } - return buffer2; + request3.body = safelyExtractBody(request3.body.source)[0]; } - }; - } - function generateMask() { - if (bufIdx === BUFFER_SIZE) { - bufIdx = 0; - crypto3.randomFillSync(buffer ??= Buffer.allocUnsafe(BUFFER_SIZE), 0, BUFFER_SIZE); - } - return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]]; - } - var WebsocketFrameSend = class { - /** - * @param {Buffer|undefined} data - */ - constructor(data) { - this.frameData = data; + if (request3.useURLCredentials === void 0 || isAuthenticationFetch) { + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams); + } + return response; + } + fetchParams.controller.connection.destroy(); + response = await httpNetworkOrCacheFetch(fetchParams, true); } - createFrame(opcode) { - const frameData = this.frameData; - const maskKey = generateMask(); - const bodyLength = frameData?.byteLength ?? 0; - let payloadLength = bodyLength; - let offset = 6; - if (bodyLength > maxUnsigned16Bit) { - offset += 8; - payloadLength = 127; - } else if (bodyLength > 125) { - offset += 2; - payloadLength = 126; + if (response.status === 407) { + if (request3.window === "no-window") { + return makeNetworkError(); } - const buffer2 = Buffer.allocUnsafe(bodyLength + offset); - buffer2[0] = buffer2[1] = 0; - buffer2[0] |= 128; - buffer2[0] = (buffer2[0] & 240) + opcode; - buffer2[offset - 4] = maskKey[0]; - buffer2[offset - 3] = maskKey[1]; - buffer2[offset - 2] = maskKey[2]; - buffer2[offset - 1] = maskKey[3]; - buffer2[1] = payloadLength; - if (payloadLength === 126) { - buffer2.writeUInt16BE(bodyLength, 2); - } else if (payloadLength === 127) { - buffer2[2] = buffer2[3] = 0; - buffer2.writeUIntBE(bodyLength, 4, 6); + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams); } - buffer2[1] |= 128; - for (let i = 0; i < bodyLength; ++i) { - buffer2[offset + i] = frameData[i] ^ maskKey[i & 3]; + return makeNetworkError("proxy authentication required"); + } + 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 + (request3.body == null || request3.body.source != null) + ) { + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams); } - return buffer2; + fetchParams.controller.connection.destroy(); + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ); } - }; - module2.exports = { - WebsocketFrameSend - }; - } -}); - -// node_modules/undici/lib/web/websocket/connection.js -var require_connection = __commonJS({ - "node_modules/undici/lib/web/websocket/connection.js"(exports2, module2) { - "use strict"; - var { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require_constants5(); - var { - kReadyState, - kSentClose, - kByteParser, - kReceivedClose, - kResponse - } = require_symbols5(); - var { fireEvent, failWebsocketConnection, isClosing, isClosed, isEstablished, parseExtensions } = require_util7(); - var { channels } = require_diagnostics(); - var { CloseEvent } = require_events(); - var { makeRequest } = require_request2(); - var { fetching } = require_fetch(); - var { Headers, getHeadersList } = require_headers(); - var { getDecodeSplit } = require_util2(); - var { WebsocketFrameSend } = require_frame(); - var crypto3; - try { - crypto3 = require("node:crypto"); - } catch { + if (isAuthenticationFetch) { + } + return response; } - function establishWebSocketConnection(url2, protocols, client, ws, onEstablish, options) { - const requestURL = url2; - requestURL.protocol = url2.protocol === "ws:" ? "http:" : "https:"; - const request3 = makeRequest({ - urlList: [requestURL], - client, - serviceWorkers: "none", - referrer: "no-referrer", - mode: "websocket", - credentials: "include", - cache: "no-store", - redirect: "error" - }); - if (options.headers) { - const headersList = getHeadersList(new Headers(options.headers)); - request3.headersList = headersList; + 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")); + } + } + } + }; + const request3 = fetchParams.request; + let response = null; + const timingInfo = fetchParams.timingInfo; + const httpCache = null; + if (httpCache == null) { + request3.cache = "no-store"; } - const keyValue = crypto3.randomBytes(16).toString("base64"); - request3.headersList.append("sec-websocket-key", keyValue); - request3.headersList.append("sec-websocket-version", "13"); - for (const protocol of protocols) { - request3.headersList.append("sec-websocket-protocol", protocol); + const newConnection = forceNewConnection ? "yes" : "no"; + if (request3.mode === "websocket") { + } else { } - const permessageDeflate = "permessage-deflate; client_max_window_bits"; - request3.headersList.append("sec-websocket-extensions", permessageDeflate); - const controller = fetching({ - request: request3, - useParallelQueue: true, - dispatcher: options.dispatcher, - processResponse(response) { - if (response.type === "error" || response.status !== 101) { - failWebsocketConnection(ws, "Received network error or non-101 status code."); + let requestBody = null; + if (request3.body == null && fetchParams.processRequestEndOfBody) { + queueMicrotask(() => fetchParams.processRequestEndOfBody()); + } else if (request3.body != null) { + const processBodyChunk = async function* (bytes) { + if (isCancelled(fetchParams)) { return; } - if (protocols.length !== 0 && !response.headersList.get("Sec-WebSocket-Protocol")) { - failWebsocketConnection(ws, "Server did not respond with sent protocols."); + yield bytes; + fetchParams.processRequestBodyChunkLength?.(bytes.byteLength); + }; + const processEndOfBody = () => { + if (isCancelled(fetchParams)) { return; } - if (response.headersList.get("Upgrade")?.toLowerCase() !== "websocket") { - failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".'); - return; + if (fetchParams.processRequestEndOfBody) { + fetchParams.processRequestEndOfBody(); } - if (response.headersList.get("Connection")?.toLowerCase() !== "upgrade") { - failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".'); + }; + const processBodyError = (e) => { + if (isCancelled(fetchParams)) { return; } - const secWSAccept = response.headersList.get("Sec-WebSocket-Accept"); - const digest = crypto3.createHash("sha1").update(keyValue + uid).digest("base64"); - if (secWSAccept !== digest) { - failWebsocketConnection(ws, "Incorrect hash received in Sec-WebSocket-Accept header."); - return; + if (e.name === "AbortError") { + fetchParams.controller.abort(); + } else { + fetchParams.controller.terminate(e); } - 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; + }; + requestBody = (async function* () { + try { + for await (const bytes of request3.body.stream) { + yield* processBodyChunk(bytes); } + processEndOfBody(); + } catch (err) { + processBodyError(err); } - const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); - if (secProtocol !== null) { - const requestProtocols = getDecodeSplit("sec-websocket-protocol", request3.headersList); - if (!requestProtocols.includes(secProtocol)) { - failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); - return; + })(); + } + try { + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }); + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }); + } else { + const iterator2 = body[Symbol.asyncIterator](); + fetchParams.controller.next = () => iterator2.next(); + response = makeResponse({ status, statusText, headersList }); + } + } catch (err) { + if (err.name === "AbortError") { + fetchParams.controller.connection.destroy(); + return makeAppropriateNetworkError(fetchParams, err); + } + return makeNetworkError(err); + } + const pullAlgorithm = () => { + return fetchParams.controller.resume(); + }; + const cancelAlgorithm = (reason) => { + if (!isCancelled(fetchParams)) { + fetchParams.controller.abort(reason); + } + }; + const stream2 = new ReadableStream( + { + start(controller) { + fetchParams.controller.controller = controller; + }, + pull: pullAlgorithm, + cancel: cancelAlgorithm, + type: "bytes" + } + ); + response.body = { stream: stream2, source: null, length: null }; + if (!fetchParams.controller.resume) { + fetchParams.controller.on("terminated", onAborted); + } + fetchParams.controller.resume = async () => { + while (true) { + let bytes; + let isFailure; + try { + const { done, value } = await fetchParams.controller.next(); + if (isAborted(fetchParams)) { + break; + } + bytes = done ? void 0 : value; + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + bytes = void 0; + } else { + bytes = err; + isFailure = true; } } - 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 - }); + if (bytes === void 0) { + readableStreamClose(fetchParams.controller.controller); + finalizeResponse(fetchParams, response); + return; + } + timingInfo.decodedBodySize += bytes?.byteLength ?? 0; + if (isFailure) { + fetchParams.controller.terminate(bytes); + return; + } + const buffer = new Uint8Array(bytes); + if (buffer.byteLength) { + fetchParams.controller.controller.enqueue(buffer); + } + if (isErrored(stream2)) { + fetchParams.controller.terminate(); + return; + } + if (fetchParams.controller.controller.desiredSize <= 0) { + return; } - onEstablish(response, extensions); } - }); - return controller; - } - function closeWebSocketConnection(ws, code, reason, reasonByteLength) { - if (isClosing(ws) || isClosed(ws)) { - } else if (!isEstablished(ws)) { - failWebsocketConnection(ws, "Connection was closed before it was established."); - ws[kReadyState] = states.CLOSING; - } else if (ws[kSentClose] === sentCloseFrameState.NOT_SENT) { - ws[kSentClose] = sentCloseFrameState.PROCESSING; - const frame = new WebsocketFrameSend(); - if (code !== void 0 && reason === void 0) { - frame.frameData = Buffer.allocUnsafe(2); - frame.frameData.writeUInt16BE(code, 0); - } else if (code !== void 0 && reason !== void 0) { - frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength); - frame.frameData.writeUInt16BE(code, 0); - frame.frameData.write(reason, 2, "utf-8"); + }; + function onAborted(reason) { + if (isAborted(fetchParams)) { + response.aborted = true; + if (isReadable(stream2)) { + fetchParams.controller.controller.error( + fetchParams.controller.serializedAbortReason + ); + } } else { - frame.frameData = emptyBuffer; + if (isReadable(stream2)) { + fetchParams.controller.controller.error(new TypeError("terminated", { + cause: isErrorLike(reason) ? reason : void 0 + })); + } } - const socket = ws[kResponse].socket; - socket.write(frame.createFrame(opcodes.CLOSE)); - ws[kSentClose] = sentCloseFrameState.SENT; - ws[kReadyState] = states.CLOSING; - } else { - ws[kReadyState] = states.CLOSING; - } - } - function onSocketData(chunk) { - if (!this.ws[kByteParser].write(chunk)) { - this.pause(); - } - } - function onSocketClose() { - const { ws } = this; - const { [kResponse]: response } = ws; - response.socket.off("data", onSocketData); - response.socket.off("close", onSocketClose); - response.socket.off("error", onSocketError); - 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]) { - code = 1006; - } - ws[kReadyState] = states.CLOSED; - fireEvent("close", ws, (type, init2) => new CloseEvent(type, init2), { - wasClean, - code, - reason - }); - if (channels.close.hasSubscribers) { - channels.close.publish({ - websocket: ws, - code, - reason - }); + fetchParams.controller.connection.destroy(); } - } - function onSocketError(error3) { - const { ws } = this; - ws[kReadyState] = states.CLOSING; - if (channels.socketError.hasSubscribers) { - channels.socketError.publish(error3); + return response; + function dispatch({ body }) { + const url2 = requestCurrentURL(request3); + const agent = fetchParams.controller.dispatcher; + const path30 = url2.pathname + url2.search; + const hasTrailingQuestionMark = url2.search.length === 0 && url2.href[url2.href.length - url2.hash.length - 1] === "?"; + return new Promise((resolve15, reject) => agent.dispatch( + { + path: hasTrailingQuestionMark ? `${path30}?` : path30, + origin: url2.origin, + method: request3.method, + body: agent.isMockActive ? request3.body && (request3.body.source || request3.body.stream) : body, + headers: request3.headersList.entries, + maxRedirections: 0, + upgrade: request3.mode === "websocket" ? "websocket" : void 0 + }, + { + body: null, + abort: null, + onConnect(abort) { + const { connection } = fetchParams.controller; + timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(void 0, 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; + } + timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability); + }, + onResponseStarted() { + timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability); + }, + onHeaders(status, rawHeaders, resume, statusText) { + if (status < 200) { + return false; + } + const headersList = new HeadersList(); + for (let i = 0; i < rawHeaders.length; i += 2) { + const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]); + const value = rawHeaders[i + 1]; + if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) { + for (const val of value) { + headersList.append(nameStr, val.toString("latin1"), true); + } + } else { + headersList.append(nameStr, value.toString("latin1"), true); + } + } + const location = headersList.get("location", true); + const willFollow = location && request3.redirect === "follow" && redirectStatusSet.has(status); + const decoders = []; + if (request3.method !== "HEAD" && request3.method !== "CONNECT" && !nullBodyStatus.includes(status) && !willFollow) { + const contentEncoding = headersList.get("content-encoding", true); + const codings = contentEncoding ? contentEncoding.toLowerCase().split(",") : []; + const maxContentEncodings = 5; + if (codings.length > maxContentEncodings) { + this.abort(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(); + if (coding === "x-gzip" || coding === "gzip") { + decoders.push(zlib3.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: zlib3.constants.Z_SYNC_FLUSH, + finishFlush: zlib3.constants.Z_SYNC_FLUSH + })); + } else if (coding === "deflate") { + decoders.push(createInflate({ + flush: zlib3.constants.Z_SYNC_FLUSH, + finishFlush: zlib3.constants.Z_SYNC_FLUSH + })); + } else if (coding === "br") { + decoders.push(zlib3.createBrotliDecompress({ + flush: zlib3.constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib3.constants.BROTLI_OPERATION_FLUSH + })); + } else if (coding === "zstd" && hasZstd) { + decoders.push(zlib3.createZstdDecompress({ + flush: zlib3.constants.ZSTD_e_continue, + finishFlush: zlib3.constants.ZSTD_e_end + })); + } else { + decoders.length = 0; + break; + } + } + } + this.body = new Readable4({ read: resume }); + const onError = this.onError.bind(this); + resolve15({ + status, + statusText, + headersList, + body: decoders.length ? pipeline2(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; + } + const bytes = chunk; + timingInfo.encodedBodySize += bytes.byteLength; + return this.body.push(bytes); + }, + onComplete() { + if (this.abort) { + fetchParams.controller.off("terminated", this.abort); + } + fetchParams.controller.ended = true; + this.body.push(null); + }, + onError(error3) { + if (this.abort) { + fetchParams.controller.off("terminated", this.abort); + } + this.body?.destroy(error3); + fetchParams.controller.terminate(error3); + reject(error3); + }, + onRequestUpgrade(_controller, status, headers, socket) { + if (socket.session != null && status !== 200 || socket.session == null && status !== 101) { + return false; + } + const headersList = new HeadersList(); + for (const [name, value] of Object.entries(headers)) { + if (value == null) { + continue; + } + const headerName = name.toLowerCase(); + if (Array.isArray(value)) { + for (const entry of value) { + headersList.append(headerName, String(entry), true); + } + } else { + headersList.append(headerName, String(value), true); + } + } + resolve15({ + status, + statusText: STATUS_CODES[status], + headersList, + socket + }); + return true; + }, + onUpgrade(status, rawHeaders, socket) { + if (socket.session != null && status !== 200 || socket.session == null && status !== 101) { + return false; + } + const headersList = new HeadersList(); + for (let i = 0; i < rawHeaders.length; i += 2) { + const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]); + const value = rawHeaders[i + 1]; + if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) { + for (const val of value) { + headersList.append(nameStr, val.toString("latin1"), true); + } + } else { + headersList.append(nameStr, value.toString("latin1"), true); + } + } + resolve15({ + status, + statusText: STATUS_CODES[status], + headersList, + socket + }); + return true; + } + } + )); } - this.destroy(); } module2.exports = { - establishWebSocketConnection, - closeWebSocketConnection + fetch, + Fetch, + fetching, + finalizeAndReportTiming }; } }); -// node_modules/undici/lib/web/websocket/permessage-deflate.js -var require_permessage_deflate = __commonJS({ - "node_modules/undici/lib/web/websocket/permessage-deflate.js"(exports2, module2) { +// node_modules/undici/lib/web/cache/util.js +var require_util3 = __commonJS({ + "node_modules/undici/lib/web/cache/util.js"(exports2, module2) { "use strict"; - var { createInflateRaw, Z_DEFAULT_WINDOWBITS } = require("node:zlib"); - var { isValidClientWindowBits } = require_util7(); - var { MessageSizeExceededError } = require_errors(); - var tail = Buffer.from([0, 0, 255, 255]); - var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); - var kLength = /* @__PURE__ */ Symbol("kLength"); - var PerMessageDeflate = class { - /** @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) { - if (!this.#inflate) { - let windowBits = Z_DEFAULT_WINDOWBITS; - if (this.#options.serverMaxWindowBits) { - 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); + var assert = require("node:assert"); + var { URLSerializer } = require_data_url(); + var { isValidHeaderName } = require_util2(); + function urlEquals(A, B, excludeFragment = false) { + const serializedA = URLSerializer(A, excludeFragment); + const serializedB = URLSerializer(B, excludeFragment); + return serializedA === serializedB; + } + function getFieldValues(header) { + assert(header !== null); + const values = []; + for (let value of header.split(",")) { + value = value.trim(); + if (isValidHeaderName(value)) { + values.push(value); } - 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); - }); } + return values; + } + module2.exports = { + urlEquals, + getFieldValues }; - module2.exports = { PerMessageDeflate }; } }); -// node_modules/undici/lib/web/websocket/receiver.js -var require_receiver = __commonJS({ - "node_modules/undici/lib/web/websocket/receiver.js"(exports2, module2) { +// node_modules/undici/lib/web/cache/cache.js +var require_cache3 = __commonJS({ + "node_modules/undici/lib/web/cache/cache.js"(exports2, module2) { "use strict"; - var { Writable } = require("node:stream"); var assert = require("node:assert"); - var { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = require_constants5(); - var { kReadyState, kSentClose, kResponse, kReceivedClose } = require_symbols5(); - var { channels } = require_diagnostics(); - var { - isValidStatusCode, - isValidOpcode, - failWebsocketConnection, - websocketMessageReceived, - utf8Decode, - isControlFrame, - isTextBinaryFrame, - isContinuationFrame - } = require_util7(); - var { WebsocketFrameSend } = require_frame(); - var { closeWebSocketConnection } = require_connection(); - var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } - var ByteParser = class extends Writable { - #buffers = []; - #fragmentsBytes = 0; - #byteOffset = 0; - #loop = false; - #state = parserStates.INFO; - #info = {}; - #fragments = []; - /** @type {Map} */ - #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + var { kConstruct } = require_symbols(); + var { urlEquals, getFieldValues } = require_util3(); + var { kEnumerableProperty, isDisturbed } = require_util(); + var { webidl } = require_webidl(); + var { cloneResponse, fromInnerResponse, getResponseState } = require_response(); + var { Request, fromInnerRequest, getRequestState } = require_request2(); + var { fetching } = require_fetch(); + var { urlIsHttpHttpsScheme, readAllBytes } = require_util2(); + var { createDeferredPromise } = require_promise(); + var Cache = class _Cache { /** - * @param {import('./websocket').WebSocket} ws - * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} */ - constructor(ws, extensions, options = {}) { - super(); - this.ws = ws; - this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; - if (this.#extensions.has("permessage-deflate")) { - this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); + #relevantRequestResponseList; + constructor() { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor(); } + webidl.util.markAsUncloneable(this); + this.#relevantRequestResponseList = arguments[1]; } - /** - * @param {Buffer} chunk - * @param {() => void} callback - */ - _write(chunk, _2, 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.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; + async match(request3, options = {}) { + webidl.brandCheck(this, _Cache); + const prefix = "Cache.match"; + webidl.argumentLengthCheck(arguments, 1, prefix); + request3 = webidl.converters.RequestInfo(request3); + options = webidl.converters.CacheQueryOptions(options, prefix, "options"); + const p = this.#internalMatchAll(request3, options, 1); + if (p.length === 0) { + return; } - return true; + return p[0]; } - /** - * 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 (this.#byteOffset < 2) { - return callback(); - } - const buffer = this.consume(2); - const fin = (buffer[0] & 128) !== 0; - const opcode = buffer[0] & 15; - const masked = (buffer[1] & 128) === 128; - const fragmented = !fin && opcode !== opcodes.CONTINUATION; - const payloadLength = buffer[1] & 127; - const rsv1 = buffer[0] & 64; - const rsv2 = buffer[0] & 32; - const rsv3 = buffer[0] & 16; - if (!isValidOpcode(opcode)) { - failWebsocketConnection(this.ws, "Invalid opcode received"); - return callback(); - } - if (masked) { - failWebsocketConnection(this.ws, "Frame cannot be masked"); - return callback(); - } - 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)) { - failWebsocketConnection(this.ws, "Invalid frame type was fragmented."); - return; - } - if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) { - failWebsocketConnection(this.ws, "Expected continuation frame"); - return; - } - if (this.#info.fragmented && fragmented) { - failWebsocketConnection(this.ws, "Fragmented frame exceeded 125 bytes."); - return; - } - 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); - 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) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - 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, - (error3, data) => { - if (error3) { - const code = error3 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error3.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; + async matchAll(request3 = void 0, options = {}) { + webidl.brandCheck(this, _Cache); + const prefix = "Cache.matchAll"; + if (request3 !== void 0) request3 = webidl.converters.RequestInfo(request3); + options = webidl.converters.CacheQueryOptions(options, prefix, "options"); + return this.#internalMatchAll(request3, options); + } + async add(request3) { + webidl.brandCheck(this, _Cache); + const prefix = "Cache.add"; + webidl.argumentLengthCheck(arguments, 1, prefix); + request3 = webidl.converters.RequestInfo(request3); + const requests = [request3]; + const responseArrayPromise = this.addAll(requests); + return await responseArrayPromise; + } + async addAll(requests) { + webidl.brandCheck(this, _Cache); + const prefix = "Cache.addAll"; + webidl.argumentLengthCheck(arguments, 1, prefix); + const responsePromises = []; + const requestList = []; + for (let request3 of requests) { + if (request3 === void 0) { + throw webidl.errors.conversionFailed({ + prefix, + argument: "Argument 1", + types: ["undefined is not allowed"] + }); + } + request3 = webidl.converters.RequestInfo(request3); + if (typeof request3 === "string") { + continue; + } + const r = getRequestState(request3); + if (!urlIsHttpHttpsScheme(r.url) || r.method !== "GET") { + throw webidl.errors.exception({ + header: prefix, + message: "Expected http/s scheme when method is not GET." + }); + } + } + const fetchControllers = []; + for (const request3 of requests) { + const r = getRequestState(new Request(request3)); + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: prefix, + message: "Expected http/s scheme." + }); + } + r.initiator = "fetch"; + r.destination = "subresource"; + requestList.push(r); + const responsePromise = createDeferredPromise(); + fetchControllers.push(fetching({ + request: r, + processResponse(response) { + 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")) { + const fieldValues = getFieldValues(response.headersList.get("vary")); + for (const fieldValue of fieldValues) { + if (fieldValue === "*") { + responsePromise.reject(webidl.errors.exception({ + header: "Cache.addAll", + message: "invalid vary field value" + })); + for (const controller of fetchControllers) { + controller.abort(); } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; - this.#state = parserStates.INFO; - this.run(callback); + return; } - ); - this.#loop = false; - break; + } + } + }, + processResponseEndOfBody(response) { + if (response.aborted) { + responsePromise.reject(new DOMException("aborted", "AbortError")); + return; } + responsePromise.resolve(response); } - } + })); + responsePromises.push(responsePromise.promise); } - } - /** - * 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; + const p = Promise.all(responsePromises); + const responses = await p; + const operations = []; + let index2 = 0; + for (const response of responses) { + const operation = { + type: "put", + // 7.3.2 + request: requestList[index2], + // 7.3.3 + response + // 7.3.4 + }; + operations.push(operation); + index2++; } - if (this.#buffers[0].length === n) { - this.#byteOffset -= this.#buffers[0].length; - return this.#buffers.shift(); + const cacheJobPromise = createDeferredPromise(); + let errorData = null; + try { + this.#batchCacheOperations(operations); + } catch (e) { + errorData = e; } - 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; + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(void 0); } else { - buffer.set(this.#buffers.shift(), offset); - offset += next.length; + cacheJobPromise.reject(errorData); } - } - this.#byteOffset -= n; - return buffer; + }); + return cacheJobPromise.promise; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; + async put(request3, response) { + webidl.brandCheck(this, _Cache); + const prefix = "Cache.put"; + webidl.argumentLengthCheck(arguments, 2, prefix); + request3 = webidl.converters.RequestInfo(request3); + response = webidl.converters.Response(response, prefix, "response"); + let innerRequest = null; + if (webidl.is.Request(request3)) { + innerRequest = getRequestState(request3); + } else { + innerRequest = getRequestState(new Request(request3)); } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); + if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== "GET") { + throw webidl.errors.exception({ + header: prefix, + message: "Expected an http/s scheme when method is not GET" + }); } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } - parseCloseBody(data) { - assert(data.length !== 1); - let code; - if (data.length >= 2) { - code = data.readUInt16BE(0); + const innerResponse = getResponseState(response); + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: prefix, + message: "Got 206 status" + }); } - if (code !== void 0 && !isValidStatusCode(code)) { - return { code: 1002, reason: "Invalid status code", error: true }; + if (innerResponse.headersList.contains("vary")) { + const fieldValues = getFieldValues(innerResponse.headersList.get("vary")); + for (const fieldValue of fieldValues) { + if (fieldValue === "*") { + throw webidl.errors.exception({ + header: prefix, + message: "Got * vary field value" + }); + } + } } - let reason = data.subarray(2); - if (reason[0] === 239 && reason[1] === 187 && reason[2] === 191) { - reason = reason.subarray(3); + if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { + throw webidl.errors.exception({ + header: prefix, + message: "Response body is locked or disturbed" + }); + } + const clonedResponse = cloneResponse(innerResponse); + const bodyReadPromise = createDeferredPromise(); + if (innerResponse.body != null) { + const stream2 = innerResponse.body.stream; + const reader = stream2.getReader(); + readAllBytes(reader, bodyReadPromise.resolve, bodyReadPromise.reject); + } else { + bodyReadPromise.resolve(void 0); + } + const operations = []; + const operation = { + type: "put", + // 14. + request: innerRequest, + // 15. + response: clonedResponse + // 16. + }; + operations.push(operation); + const bytes = await bodyReadPromise.promise; + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes; } + const cacheJobPromise = createDeferredPromise(); + let errorData = null; try { - reason = utf8Decode(reason); - } catch { - return { code: 1007, reason: "Invalid UTF-8", error: true }; + this.#batchCacheOperations(operations); + } catch (e) { + errorData = e; } - 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; + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(); + } else { + cacheJobPromise.reject(errorData); } - 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 cacheJobPromise.promise; + } + async delete(request3, options = {}) { + webidl.brandCheck(this, _Cache); + const prefix = "Cache.delete"; + webidl.argumentLengthCheck(arguments, 1, prefix); + request3 = webidl.converters.RequestInfo(request3); + options = webidl.converters.CacheQueryOptions(options, prefix, "options"); + let r = null; + if (webidl.is.Request(request3)) { + r = getRequestState(request3); + if (r.method !== "GET" && !options.ignoreMethod) { return false; } - if (this.ws[kSentClose] !== sentCloseFrameState.SENT) { - let body2 = emptyBuffer; - if (this.#info.closeInfo.code) { - body2 = Buffer.allocUnsafe(2); - body2.writeUInt16BE(this.#info.closeInfo.code, 0); - } - const closeFrame = new WebsocketFrameSend(body2); - this.ws[kResponse].socket.write( - closeFrame.createFrame(opcodes.CLOSE), - (err) => { - if (!err) { - this.ws[kSentClose] = sentCloseFrameState.SENT; - } - } - ); - } - this.ws[kReadyState] = states.CLOSING; - this.ws[kReceivedClose] = true; - return false; - } else if (opcode === opcodes.PING) { - 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) { - if (channels.pong.hasSubscribers) { - channels.pong.publish({ - payload: body - }); - } + } else { + assert(typeof request3 === "string"); + r = getRequestState(new Request(request3)); } - return true; - } - get closingInfo() { - return this.#info.closeInfo; + const operations = []; + 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; } - }; - module2.exports = { - ByteParser - }; - } -}); - -// node_modules/undici/lib/web/websocket/sender.js -var require_sender = __commonJS({ - "node_modules/undici/lib/web/websocket/sender.js"(exports2, module2) { - "use strict"; - var { WebsocketFrameSend } = require_frame(); - var { opcodes, sendHints } = require_constants5(); - var FixedQueue = require_fixed_queue(); - var FastBuffer = Buffer[Symbol.species]; - var SendQueue = class { - /** - * @type {FixedQueue} - */ - #queue = new FixedQueue(); /** - * @type {boolean} + * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys + * @param {any} request + * @param {import('../../../types/cache').CacheQueryOptions} options + * @returns {Promise} */ - #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) { - this.#socket.write(frame, cb); - } else { - const node2 = { - promise: null, - callback: cb, - frame - }; - this.#queue.push(node2); + async keys(request3 = void 0, options = {}) { + webidl.brandCheck(this, _Cache); + const prefix = "Cache.keys"; + if (request3 !== void 0) request3 = webidl.converters.RequestInfo(request3); + options = webidl.converters.CacheQueryOptions(options, prefix, "options"); + let r = null; + if (request3 !== void 0) { + if (webidl.is.Request(request3)) { + r = getRequestState(request3); + if (r.method !== "GET" && !options.ignoreMethod) { + return []; + } + } else if (typeof request3 === "string") { + r = getRequestState(new Request(request3)); } - return; - } - 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 queue2 = this.#queue; - while (!queue2.isEmpty()) { - const node = queue2.shift(); - if (node.promise !== null) { - await node.promise; + const promise = createDeferredPromise(); + const requests = []; + if (request3 === void 0) { + for (const requestResponse of this.#relevantRequestResponseList) { + requests.push(requestResponse[0]); + } + } else { + const requestResponses = this.#queryCache(r, options); + for (const requestResponse of requestResponses) { + requests.push(requestResponse[0]); } - this.#socket.write(node.frame, node.callback); - 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); + queueMicrotask(() => { + const requestList = []; + for (const request4 of requests) { + const requestObject = fromInnerRequest( + request4, + void 0, + new AbortController().signal, + "immutable" + ); + requestList.push(requestObject); + } + promise.resolve(Object.freeze(requestList)); + }); + return promise.promise; } - } - module2.exports = { SendQueue }; - } -}); - -// node_modules/undici/lib/web/websocket/websocket.js -var require_websocket = __commonJS({ - "node_modules/undici/lib/web/websocket/websocket.js"(exports2, module2) { - "use strict"; - var { webidl } = require_webidl(); - var { URLSerializer } = require_data_url(); - var { environmentSettingsObject } = require_util2(); - var { staticPropertyDescriptors, states, sentCloseFrameState, sendHints } = require_constants5(); - var { - kWebSocketURL, - kReadyState, - kController, - kBinaryType, - kResponse, - kSentClose, - kByteParser - } = require_symbols5(); - var { - isConnecting, - isEstablished, - isClosing, - isValidSubprotocol, - fireEvent - } = require_util7(); - var { establishWebSocketConnection, closeWebSocketConnection } = require_connection(); - var { ByteParser } = require_receiver(); - var { kEnumerableProperty, isBlobLike } = require_util(); - var { getGlobalDispatcher } = require_global2(); - var { types: types2 } = require("node:util"); - var { ErrorEvent, CloseEvent } = require_events(); - var { SendQueue } = require_sender(); - var WebSocket = 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 + * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm + * @param {CacheBatchOperation[]} operations + * @returns {requestResponseList} */ - constructor(url2, 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"); - url2 = webidl.converters.USVString(url2, prefix, "url"); - protocols = options.protocols; - const baseURL = environmentSettingsObject.settingsObject.baseUrl; - let urlRecord; + #batchCacheOperations(operations) { + const cache = this.#relevantRequestResponseList; + const backupCache = [...cache]; + const addedItems = []; + const resultList = []; try { - urlRecord = new URL(url2, baseURL); + for (const operation of operations) { + if (operation.type !== "delete" && operation.type !== "put") { + throw webidl.errors.exception({ + header: "Cache.#batchCacheOperations", + message: 'operation type does not match "delete" or "put"' + }); + } + if (operation.type === "delete" && operation.response != null) { + throw webidl.errors.exception({ + header: "Cache.#batchCacheOperations", + message: "delete operation should not have an associated response" + }); + } + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException("???", "InvalidStateError"); + } + let requestResponses; + if (operation.type === "delete") { + requestResponses = this.#queryCache(operation.request, operation.options); + if (requestResponses.length === 0) { + return []; + } + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse); + assert(idx !== -1); + cache.splice(idx, 1); + } + } else if (operation.type === "put") { + if (operation.response == null) { + throw webidl.errors.exception({ + header: "Cache.#batchCacheOperations", + message: "put operation should have an associated response" + }); + } + const r = operation.request; + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: "Cache.#batchCacheOperations", + message: "expected http or https scheme" + }); + } + if (r.method !== "GET") { + throw webidl.errors.exception({ + header: "Cache.#batchCacheOperations", + message: "not get method" + }); + } + if (operation.options != null) { + throw webidl.errors.exception({ + header: "Cache.#batchCacheOperations", + message: "options must not be defined" + }); + } + requestResponses = this.#queryCache(operation.request); + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse); + assert(idx !== -1); + cache.splice(idx, 1); + } + cache.push([operation.request, operation.response]); + addedItems.push([operation.request, operation.response]); + } + resultList.push([operation.request, operation.response]); + } + return resultList; } catch (e) { - throw new DOMException(e, "SyntaxError"); - } - if (urlRecord.protocol === "http:") { - urlRecord.protocol = "ws:"; - } else if (urlRecord.protocol === "https:") { - urlRecord.protocol = "wss:"; - } - if (urlRecord.protocol !== "ws:" && urlRecord.protocol !== "wss:") { - throw new DOMException( - `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, - "SyntaxError" - ); - } - if (urlRecord.hash || urlRecord.href.endsWith("#")) { - throw new DOMException("Got fragment", "SyntaxError"); - } - if (typeof protocols === "string") { - protocols = [protocols]; - } - 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"); + this.#relevantRequestResponseList.length = 0; + this.#relevantRequestResponseList = backupCache; + throw e; } - this[kWebSocketURL] = new URL(urlRecord.href); - const client = environmentSettingsObject.settingsObject; - this[kController] = establishWebSocketConnection( - urlRecord, - protocols, - client, - this, - (response, extensions) => this.#onConnectionEstablished(response, extensions), - options - ); - this[kReadyState] = _WebSocket.CONNECTING; - this[kSentClose] = sentCloseFrameState.NOT_SENT; - this[kBinaryType] = "blob"; } /** - * @see https://websockets.spec.whatwg.org/#dom-websocket-close - * @param {number|undefined} code - * @param {string|undefined} reason + * @see https://w3c.github.io/ServiceWorker/#query-cache + * @param {any} requestQuery + * @param {import('../../../types/cache').CacheQueryOptions} options + * @param {requestResponseList} targetStorage + * @returns {requestResponseList} */ - close(code = void 0, reason = void 0) { - webidl.brandCheck(this, _WebSocket); - const prefix = "WebSocket.close"; - if (code !== void 0) { - code = webidl.converters["unsigned short"](code, prefix, "code", { clamp: true }); - } - if (reason !== void 0) { - reason = webidl.converters.USVString(reason, prefix, "reason"); - } - if (code !== void 0) { - if (code !== 1e3 && (code < 3e3 || code > 4999)) { - throw new DOMException("invalid code", "InvalidAccessError"); - } - } - let reasonByteLength = 0; - if (reason !== void 0) { - reasonByteLength = Buffer.byteLength(reason); - if (reasonByteLength > 123) { - throw new DOMException( - `Reason must be less than 123 bytes; received ${reasonByteLength}`, - "SyntaxError" - ); + #queryCache(requestQuery, options, targetStorage) { + 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); } } - closeWebSocketConnection(this, code, reason, reasonByteLength); + return resultList; } /** - * @see https://websockets.spec.whatwg.org/#dom-websocket-send - * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data + * @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} */ - send(data) { - webidl.brandCheck(this, _WebSocket); - const prefix = "WebSocket.send"; - webidl.argumentLengthCheck(arguments, 1, prefix); - data = webidl.converters.WebSocketSendData(data, prefix, "data"); - if (isConnecting(this)) { - throw new DOMException("Sent before connected.", "InvalidStateError"); - } - if (!isEstablished(this) || isClosing(this)) { - return; - } - if (typeof data === "string") { - const length = Buffer.byteLength(data); - this.#bufferedAmount += length; - this.#sendQueue.add(data, () => { - this.#bufferedAmount -= length; - }, sendHints.string); - } else if (types2.isArrayBuffer(data)) { - this.#bufferedAmount += data.byteLength; - this.#sendQueue.add(data, () => { - this.#bufferedAmount -= data.byteLength; - }, sendHints.arrayBuffer); - } else if (ArrayBuffer.isView(data)) { - this.#bufferedAmount += data.byteLength; - this.#sendQueue.add(data, () => { - this.#bufferedAmount -= data.byteLength; - }, sendHints.typedArray); - } else if (isBlobLike(data)) { - this.#bufferedAmount += data.size; - this.#sendQueue.add(data, () => { - this.#bufferedAmount -= data.size; - }, sendHints.blob); - } - } - get readyState() { - webidl.brandCheck(this, _WebSocket); - return this[kReadyState]; - } - get bufferedAmount() { - webidl.brandCheck(this, _WebSocket); - return this.#bufferedAmount; - } - get url() { - webidl.brandCheck(this, _WebSocket); - 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); + #requestMatchesCachedItem(requestQuery, request3, response = null, options) { + const queryURL = new URL(requestQuery.url); + const cachedURL = new URL(request3.url); + if (options?.ignoreSearch) { + cachedURL.search = ""; + queryURL.search = ""; } - if (typeof fn === "function") { - this.#events.error = fn; - this.addEventListener("error", fn); - } else { - this.#events.error = null; + if (!urlEquals(queryURL, cachedURL, true)) { + return false; } - } - 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 (response == null || options?.ignoreVary || !response.headersList.contains("vary")) { + return true; } - if (typeof fn === "function") { - this.#events.close = fn; - this.addEventListener("close", fn); - } else { - this.#events.close = null; + const fieldValues = getFieldValues(response.headersList.get("vary")); + for (const fieldValue of fieldValues) { + if (fieldValue === "*") { + return false; + } + const requestValue = request3.headersList.get(fieldValue); + const queryValue = requestQuery.headersList.get(fieldValue); + if (requestValue !== queryValue) { + return false; + } } + return true; } - 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; + #internalMatchAll(request3, options, maxResponses = Infinity) { + let r = null; + if (request3 !== void 0) { + if (webidl.is.Request(request3)) { + r = getRequestState(request3); + if (r.method !== "GET" && !options.ignoreMethod) { + return []; + } + } else if (typeof request3 === "string") { + r = getRequestState(new Request(request3)); + } } - } - get binaryType() { - webidl.brandCheck(this, _WebSocket); - return this[kBinaryType]; - } - set binaryType(type) { - webidl.brandCheck(this, _WebSocket); - if (type !== "blob" && type !== "arraybuffer") { - this[kBinaryType] = "blob"; + const responses = []; + if (request3 === void 0) { + for (const requestResponse of this.#relevantRequestResponseList) { + responses.push(requestResponse[1]); + } } else { - this[kBinaryType] = type; - } - } - /** - * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol - */ - #onConnectionEstablished(response, parsedExtensions) { - this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); - parser.on("drain", onParserDrain); - parser.on("error", onParserError.bind(this)); - response.socket.ws = this; - this[kByteParser] = parser; - this.#sendQueue = new SendQueue(response.socket); - this[kReadyState] = states.OPEN; - const extensions = response.headersList.get("sec-websocket-extensions"); - if (extensions !== null) { - this.#extensions = extensions; + const requestResponses = this.#queryCache(r, options); + for (const requestResponse of requestResponses) { + responses.push(requestResponse[1]); + } } - const protocol = response.headersList.get("sec-websocket-protocol"); - if (protocol !== null) { - this.#protocol = protocol; + const responseList = []; + for (const response of responses) { + const responseObject = fromInnerResponse(cloneResponse(response), "immutable"); + responseList.push(responseObject); + if (responseList.length >= maxResponses) { + break; + } } - fireEvent("open", this); + return Object.freeze(responseList); } }; - WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING; - WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN; - WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING; - 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, + Object.defineProperties(Cache.prototype, { [Symbol.toStringTag]: { - value: "WebSocket", - writable: false, - enumerable: false, + value: "Cache", configurable: true - } - }); - Object.defineProperties(WebSocket, { - CONNECTING: staticPropertyDescriptors, - OPEN: staticPropertyDescriptors, - CLOSING: staticPropertyDescriptors, - CLOSED: staticPropertyDescriptors + }, + match: kEnumerableProperty, + matchAll: kEnumerableProperty, + add: kEnumerableProperty, + addAll: kEnumerableProperty, + put: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty }); - 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); - }; - webidl.converters.WebSocketInit = webidl.dictionaryConverter([ + var cacheQueryOptionConverters = [ { - key: "protocols", - converter: webidl.converters["DOMString or sequence"], - defaultValue: () => new Array(0) + key: "ignoreSearch", + converter: webidl.converters.boolean, + defaultValue: () => false }, { - key: "dispatcher", - converter: webidl.converters.any, - defaultValue: () => getGlobalDispatcher() + key: "ignoreMethod", + converter: webidl.converters.boolean, + defaultValue: () => false }, { - 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) || types2.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; + key: "ignoreVary", + converter: webidl.converters.boolean, + defaultValue: () => false } - fireEvent("error", this, () => new ErrorEvent("error", { error: err, message })); - closeWebSocketConnection(this, code); - } - module2.exports = { - WebSocket - }; - } -}); - -// node_modules/undici/lib/web/eventsource/util.js -var require_util8 = __commonJS({ - "node_modules/undici/lib/web/eventsource/util.js"(exports2, module2) { - "use strict"; - function isValidLastEventId(value) { - return value.indexOf("\0") === -1; - } - function isASCIINumber(value) { - if (value.length === 0) return false; - for (let i = 0; i < value.length; i++) { - if (value.charCodeAt(i) < 48 || value.charCodeAt(i) > 57) return false; + ]; + webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters); + webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ + ...cacheQueryOptionConverters, + { + key: "cacheName", + converter: webidl.converters.DOMString } - return true; - } - function delay2(ms) { - return new Promise((resolve14) => { - setTimeout(resolve14, ms).unref(); - }); - } + ]); + webidl.converters.Response = webidl.interfaceConverter( + webidl.is.Response, + "Response" + ); + webidl.converters["sequence"] = webidl.sequenceConverter( + webidl.converters.RequestInfo + ); module2.exports = { - isValidLastEventId, - isASCIINumber, - delay: delay2 + Cache }; } }); -// node_modules/undici/lib/web/eventsource/eventsource-stream.js -var require_eventsource_stream = __commonJS({ - "node_modules/undici/lib/web/eventsource/eventsource-stream.js"(exports2, module2) { +// node_modules/undici/lib/web/cache/cachestorage.js +var require_cachestorage = __commonJS({ + "node_modules/undici/lib/web/cache/cachestorage.js"(exports2, module2) { "use strict"; - var { Transform: Transform5 } = require("node:stream"); - var { isASCIINumber, isValidLastEventId } = require_util8(); - var BOM = [239, 187, 191]; - var LF = 10; - var CR = 13; - var COLON = 58; - var SPACE = 32; - var EventSourceStream = class extends Transform5 { - /** - * @type {eventSourceSettings} - */ - state = null; - /** - * Leading byte-order-mark check. - * @type {boolean} - */ - checkBOM = true; + var { Cache } = require_cache3(); + var { webidl } = require_webidl(); + var { kEnumerableProperty } = require_util(); + var { kConstruct } = require_symbols(); + var CacheStorage = class _CacheStorage { /** - * @type {boolean} + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map + * @type {Map} */ - eventEndCheck = false; + async has(cacheName) { + webidl.brandCheck(this, _CacheStorage); + const prefix = "CacheStorage.has"; + webidl.argumentLengthCheck(arguments, 1, prefix); + cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName"); + return this.#caches.has(cacheName); + } /** - * @type {Buffer} + * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open + * @param {string} cacheName + * @returns {Promise} */ - buffer = null; - pos = 0; - event = { - data: void 0, - event: void 0, - id: void 0, - retry: void 0 - }; + async open(cacheName) { + webidl.brandCheck(this, _CacheStorage); + const prefix = "CacheStorage.open"; + webidl.argumentLengthCheck(arguments, 1, prefix); + cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName"); + if (this.#caches.has(cacheName)) { + const cache2 = this.#caches.get(cacheName); + return new Cache(kConstruct, cache2); + } + const cache = []; + this.#caches.set(cacheName, cache); + return new Cache(kConstruct, cache); + } /** - * @param {object} options - * @param {eventSourceSettings} options.eventSourceSettings - * @param {Function} [options.push] + * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete + * @param {string} cacheName + * @returns {Promise} */ - constructor(options = {}) { - options.readableObjectMode = true; - super(options); - this.state = options.eventSourceSettings || {}; - if (options.push) { - this.push = options.push; - } + 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); } /** - * @param {Buffer} chunk - * @param {string} _encoding - * @param {Function} callback - * @returns {void} + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {Promise} */ - _transform(chunk, _encoding, callback) { - if (chunk.length === 0) { - callback(); - return; - } - if (this.buffer) { - this.buffer = Buffer.concat([this.buffer, chunk]); - } else { - this.buffer = chunk; + async keys() { + webidl.brandCheck(this, _CacheStorage); + const keys = this.#caches.keys(); + return [...keys]; + } + }; + Object.defineProperties(CacheStorage.prototype, { + [Symbol.toStringTag]: { + value: "CacheStorage", + configurable: true + }, + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty + }); + module2.exports = { + CacheStorage + }; + } +}); + +// node_modules/undici/lib/web/cookies/constants.js +var require_constants4 = __commonJS({ + "node_modules/undici/lib/web/cookies/constants.js"(exports2, module2) { + "use strict"; + var maxAttributeValueSize = 1024; + var maxNameValuePairSize = 4096; + module2.exports = { + maxAttributeValueSize, + maxNameValuePairSize + }; + } +}); + +// node_modules/undici/lib/web/cookies/util.js +var require_util4 = __commonJS({ + "node_modules/undici/lib/web/cookies/util.js"(exports2, module2) { + "use strict"; + function isCTLExcludingHtab(value) { + for (let i = 0; i < value.length; ++i) { + const code = value.charCodeAt(i); + if (code >= 0 && code <= 8 || code >= 10 && code <= 31 || code === 127) { + return true; } - if (this.checkBOM) { - switch (this.buffer.length) { - case 1: - if (this.buffer[0] === BOM[0]) { - callback(); - return; - } - this.checkBOM = false; - callback(); - return; - case 2: - if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { - callback(); - return; - } - this.checkBOM = false; - break; - case 3: - if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { - this.buffer = Buffer.alloc(0); - this.checkBOM = false; - callback(); - return; - } - this.checkBOM = false; - break; - default: - if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { - this.buffer = this.buffer.subarray(3); - } - this.checkBOM = false; - break; - } + } + return false; + } + function validateCookieName(name) { + for (let i = 0; i < name.length; ++i) { + const code = name.charCodeAt(i); + if (code < 33 || // exclude CTLs (0-31), SP and HT + code > 126 || // exclude non-ascii and DEL + code === 34 || // " + code === 40 || // ( + code === 41 || // ) + code === 60 || // < + code === 62 || // > + code === 64 || // @ + code === 44 || // , + code === 59 || // ; + code === 58 || // : + code === 92 || // \ + code === 47 || // / + code === 91 || // [ + code === 93 || // ] + code === 63 || // ? + code === 61 || // = + code === 123 || // { + code === 125) { + throw new Error("Invalid cookie name"); } - while (this.pos < this.buffer.length) { - if (this.eventEndCheck) { - if (this.crlfCheck) { - if (this.buffer[this.pos] === LF) { - this.buffer = this.buffer.subarray(this.pos + 1); - this.pos = 0; - this.crlfCheck = false; - continue; - } - this.crlfCheck = false; - } - if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { - if (this.buffer[this.pos] === CR) { - this.crlfCheck = true; - } - this.buffer = this.buffer.subarray(this.pos + 1); - this.pos = 0; - if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { - this.processEvent(this.event); - } - this.clearEvent(); - continue; - } - this.eventEndCheck = false; - continue; - } - if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { - if (this.buffer[this.pos] === CR) { - this.crlfCheck = true; - } - this.parseLine(this.buffer.subarray(0, this.pos), this.event); - this.buffer = this.buffer.subarray(this.pos + 1); - this.pos = 0; - this.eventEndCheck = true; - continue; - } - this.pos++; + } + } + function validateCookieValue(value) { + let len = value.length; + let i = 0; + if (value[0] === '"') { + if (len === 1 || value[len - 1] !== '"') { + throw new Error("Invalid cookie value"); } - callback(); + --len; + ++i; } - /** - * @param {Buffer} line - * @param {EventStreamEvent} event - */ - parseLine(line, event) { - if (line.length === 0) { - return; + while (i < len) { + const code = value.charCodeAt(i++); + if (code < 33 || // exclude CTLs (0-31) + code > 126 || // non-ascii and DEL (127) + code === 34 || // " + code === 44 || // , + code === 59 || // ; + code === 92) { + throw new Error("Invalid cookie value"); } - const colonPosition = line.indexOf(COLON); - if (colonPosition === 0) { - return; + } + } + function validateCookiePath(path30) { + for (let i = 0; i < path30.length; ++i) { + const code = path30.charCodeAt(i); + if (code < 32 || // exclude CTLs (0-31) + code > 126 || // exclude DEL and non-ascii + code === 59) { + throw new Error("Invalid cookie path"); } - let field = ""; - let value = ""; - if (colonPosition !== -1) { - field = line.subarray(0, colonPosition).toString("utf8"); - let valueStart = colonPosition + 1; - if (line[valueStart] === SPACE) { - ++valueStart; + } + } + function isLetterOrDigit(code) { + return code >= 48 && code <= 57 || // 0-9 + code >= 65 && code <= 90 || // A-Z + code >= 97 && code <= 122; + } + function validateCookieDomain(domain) { + if (domain === " ") { + return; + } + if (domain.length > 255) { + throw new Error("Invalid cookie domain"); + } + let labelLength = 0; + for (let i = 0; i < domain.length; ++i) { + const code = domain.charCodeAt(i); + if (code === 46) { + if (labelLength === 0) { + throw new Error("Invalid cookie domain"); } - value = line.subarray(valueStart).toString("utf8"); - } else { - field = line.toString("utf8"); - value = ""; + if (domain.charCodeAt(i - 1) === 45) { + throw new Error("Invalid cookie domain"); + } + labelLength = 0; + continue; } - switch (field) { - case "data": - if (event[field] === void 0) { - event[field] = value; - } else { - event[field] += ` -${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; + if (labelLength === 0 && !isLetterOrDigit(code)) { + throw new Error("Invalid cookie domain"); } - } - /** - * @param {EventSourceStreamEvent} event - */ - processEvent(event) { - if (event.retry && isASCIINumber(event.retry)) { - this.state.reconnectionTime = parseInt(event.retry, 10); + if (!isLetterOrDigit(code) && code !== 45) { + throw new Error("Invalid cookie domain"); } - if (event.id && isValidLastEventId(event.id)) { - this.state.lastEventId = event.id; + if (++labelLength > 63) { + throw new Error("Invalid cookie domain"); } - if (event.data !== void 0) { - this.push({ - type: event.event || "message", - options: { - data: event.data, - lastEventId: this.state.lastEventId, - origin: this.state.origin - } - }); + } + if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + throw new Error("Invalid cookie domain"); + } + } + var IMFDays = [ + "Sun", + "Mon", + "Tue", + "Wed", + "Thu", + "Fri", + "Sat" + ]; + var IMFMonths = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + ]; + var IMFPaddedNumbers = Array(61).fill(0).map((_2, i) => i.toString().padStart(2, "0")); + 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`; + } + function validateCookieMaxAge(maxAge) { + if (maxAge < 0) { + throw new Error("Invalid cookie max-age"); + } + } + function stringify(cookie) { + if (cookie.name.length === 0) { + return null; + } + validateCookieName(cookie.name); + validateCookieValue(cookie.value); + const out = [`${cookie.name}=${cookie.value}`]; + 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 != null) { + const expiresMs = cookie.expires instanceof Date ? cookie.expires.getTime() : cookie.expires; + const maxTimeValue = 864e13; + if (typeof expiresMs === "number" && Number.isFinite(expiresMs) && Math.abs(expiresMs) <= maxTimeValue) { + out.push(`Expires=${toIMFDate(cookie.expires)}`); } } - clearEvent() { - this.event = { - data: void 0, - event: void 0, - id: void 0, - retry: void 0 - }; + 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("="); + const trimmedKey = key.trim(); + const joinedValue = value.join("="); + validateCookieName(trimmedKey); + validateCookieValue(joinedValue); + out.push(`${trimmedKey}=${joinedValue}`); + } + return out.join("; "); + } module2.exports = { - EventSourceStream + isCTLExcludingHtab, + validateCookieName, + validateCookiePath, + validateCookieValue, + toIMFDate, + stringify }; } }); -// node_modules/undici/lib/web/eventsource/eventsource.js -var require_eventsource = __commonJS({ - "node_modules/undici/lib/web/eventsource/eventsource.js"(exports2, module2) { +// node_modules/undici/lib/web/cookies/parse.js +var require_parse = __commonJS({ + "node_modules/undici/lib/web/cookies/parse.js"(exports2, module2) { "use strict"; - var { pipeline: pipeline2 } = require("node:stream"); - var { fetching } = require_fetch(); - var { makeRequest } = require_request2(); - var { webidl } = require_webidl(); - var { EventSourceStream } = require_eventsource_stream(); - var { parseMIMEType } = require_data_url(); - var { createFastMessageEvent } = require_events(); - var { isNetworkError } = require_response(); - var { delay: delay2 } = require_util8(); - var { kEnumerableProperty } = require_util(); - var { environmentSettingsObject } = require_util2(); - var experimentalWarned = false; - var defaultReconnectionTime = 3e3; - var CONNECTING = 0; - var OPEN = 1; - var CLOSED = 2; - var ANONYMOUS = "anonymous"; - var USE_CREDENTIALS = "use-credentials"; - var EventSource = class _EventSource extends EventTarget { - #events = { - open: null, - error: null, - message: null + var { collectASequenceOfCodePointsFast } = require_infra(); + var { maxNameValuePairSize, maxAttributeValueSize } = require_constants4(); + var { isCTLExcludingHtab } = require_util4(); + var assert = require("node:assert"); + function parseSetCookie(header) { + if (isCTLExcludingHtab(header)) { + return null; + } + let nameValuePair = ""; + let unparsedAttributes = ""; + let name = ""; + let value = ""; + if (header.includes(";")) { + const position = { position: 0 }; + nameValuePair = collectASequenceOfCodePointsFast(";", header, position); + unparsedAttributes = header.slice(position.position); + } else { + nameValuePair = header; + } + if (!nameValuePair.includes("=")) { + value = nameValuePair; + } else { + const position = { position: 0 }; + name = collectASequenceOfCodePointsFast( + "=", + nameValuePair, + position + ); + value = nameValuePair.slice(position.position + 1); + } + name = name.trim(); + value = value.trim(); + if (name.length + value.length > maxNameValuePairSize) { + return null; + } + return { + name, + value, + ...parseUnparsedAttributes(unparsedAttributes) }; - #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(url2, eventSourceInitDict = {}) { - 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" - }); + } + function parseUnparsedAttributes(unparsedAttributes, cookieAttributeList = {}) { + while (true) { + if (unparsedAttributes.length === 0) { + return cookieAttributeList; + } + assert(unparsedAttributes[0] === ";"); + unparsedAttributes = unparsedAttributes.slice(1); + let cookieAv = ""; + if (unparsedAttributes.includes(";")) { + cookieAv = collectASequenceOfCodePointsFast( + ";", + unparsedAttributes, + { position: 0 } + ); + unparsedAttributes = unparsedAttributes.slice(cookieAv.length); + } else { + cookieAv = unparsedAttributes; + unparsedAttributes = ""; + } + let attributeName = ""; + let attributeValue = ""; + if (cookieAv.includes("=")) { + const position = { position: 0 }; + attributeName = collectASequenceOfCodePointsFast( + "=", + cookieAv, + position + ); + attributeValue = cookieAv.slice(position.position + 1); + } else { + attributeName = cookieAv; } - url2 = webidl.converters.USVString(url2, prefix, "url"); - eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, "eventSourceInitDict"); - this.#dispatcher = eventSourceInitDict.dispatcher; - this.#state = { - lastEventId: "", - reconnectionTime: defaultReconnectionTime - }; - const settings = environmentSettingsObject; - let urlRecord; - try { - urlRecord = new URL(url2, settings.settingsObject.baseUrl); - this.#state.origin = urlRecord.origin; - } catch (e) { - throw new DOMException(e, "SyntaxError"); + attributeName = attributeName.trim(); + attributeValue = attributeValue.trim(); + if (attributeValue.length > maxAttributeValueSize) { + continue; } - this.#url = urlRecord.href; - let corsAttributeState = ANONYMOUS; - if (eventSourceInitDict.withCredentials) { - corsAttributeState = USE_CREDENTIALS; - this.#withCredentials = true; + const attributeNameLowercase = attributeName.toLowerCase(); + if (attributeNameLowercase === "expires") { + const expiryTime = new Date(attributeValue); + cookieAttributeList.expires = expiryTime; + } else if (attributeNameLowercase === "max-age") { + const charCode = attributeValue.charCodeAt(0); + if ((charCode < 48 || charCode > 57) && attributeValue[0] !== "-") { + continue; + } + if (!/^\d+$/.test(attributeValue)) { + continue; + } + const deltaSeconds = Number(attributeValue); + cookieAttributeList.maxAge = deltaSeconds; + } else if (attributeNameLowercase === "domain") { + let cookieDomain = attributeValue; + if (cookieDomain[0] === ".") { + cookieDomain = cookieDomain.slice(1); + } + cookieDomain = cookieDomain.toLowerCase(); + cookieAttributeList.domain = cookieDomain; + } else if (attributeNameLowercase === "path") { + let cookiePath = ""; + if (attributeValue.length === 0 || attributeValue[0] !== "/") { + cookiePath = "/"; + } else { + cookiePath = attributeValue; + } + cookieAttributeList.path = cookiePath; + } else if (attributeNameLowercase === "secure") { + cookieAttributeList.secure = true; + } else if (attributeNameLowercase === "httponly") { + cookieAttributeList.httpOnly = true; + } else if (attributeNameLowercase === "samesite") { + const attributeValueLowercase = attributeValue.toLowerCase(); + if (attributeValueLowercase === "none") { + cookieAttributeList.sameSite = "None"; + } else if (attributeValueLowercase === "strict") { + cookieAttributeList.sameSite = "Strict"; + } else if (attributeValueLowercase === "lax") { + cookieAttributeList.sameSite = "Lax"; + } + } else { + cookieAttributeList.unparsed ??= []; + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); } - 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" - }; - initRequest.client = environmentSettingsObject.settingsObject; - initRequest.headersList = [["accept", { name: "accept", value: "text/event-stream" }]]; - initRequest.cache = "no-store"; - initRequest.initiator = "other"; - initRequest.urlList = [new URL(this.#url)]; - 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; + } + module2.exports = { + parseSetCookie, + parseUnparsedAttributes + }; + } +}); + +// node_modules/undici/lib/web/cookies/index.js +var require_cookies = __commonJS({ + "node_modules/undici/lib/web/cookies/index.js"(exports2, module2) { + "use strict"; + var { parseSetCookie } = require_parse(); + var { stringify } = require_util4(); + var { webidl } = require_webidl(); + var { Headers } = require_headers(); + var brandChecks = webidl.brandCheckMultiple([Headers, globalThis.Headers].filter(Boolean)); + function getCookies(headers) { + webidl.argumentLengthCheck(arguments, 1, "getCookies"); + brandChecks(headers); + const cookie = headers.get("cookie"); + const out = { __proto__: null }; + if (!cookie) { + return out; } - /** - * Returns the URL providing the event stream. - * @readonly - * @returns {string} - */ - get url() { - return this.#url; + for (const piece of cookie.split(";")) { + const [name, ...value] = piece.split("="); + out[name.trim()] = value.join("="); } - /** - * 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; + return out; + } + function deleteCookie(headers, name, attributes) { + brandChecks(headers); + const prefix = "deleteCookie"; + webidl.argumentLengthCheck(arguments, 2, prefix); + name = webidl.converters.DOMString(name, prefix, "name"); + attributes = webidl.converters.DeleteCookieAttributes(attributes); + setCookie(headers, { + name, + value: "", + expires: /* @__PURE__ */ new Date(0), + ...attributes + }); + } + function getSetCookies(headers) { + webidl.argumentLengthCheck(arguments, 1, "getSetCookies"); + brandChecks(headers); + const cookies = headers.getSetCookie(); + if (!cookies) { + return []; } - #connect() { - if (this.#readyState === CLOSED) return; - this.#readyState = CONNECTING; - const fetchParams = { - request: this.#request, - dispatcher: this.#dispatcher - }; - const processEventSourceEndOfBody = (response) => { - if (isNetworkError(response)) { - this.dispatchEvent(new Event("error")); - this.close(); - } - this.#reconnect(); - }; - fetchParams.processResponseEndOfBody = processEventSourceEndOfBody; - fetchParams.processResponse = (response) => { - if (isNetworkError(response)) { - if (response.aborted) { - this.close(); - this.dispatchEvent(new Event("error")); - return; - } else { - this.#reconnect(); - return; - } - } - 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; + return cookies.map((pair) => parseSetCookie(pair)); + } + function parseCookie(cookie) { + cookie = webidl.converters.DOMString(cookie); + return parseSetCookie(cookie); + } + function setCookie(headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, "setCookie"); + brandChecks(headers); + cookie = webidl.converters.Cookie(cookie); + const str = stringify(cookie); + if (str) { + headers.append("set-cookie", str, true); + } + } + 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); } - this.#readyState = OPEN; - this.dispatchEvent(new Event("open")); - 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 - )); - } - }); - pipeline2( - response.body.stream, - eventSourceStream, - (error3) => { - if (error3?.aborted === false) { - this.close(); - this.dispatchEvent(new Event("error")); - } - } - ); - }; - this.#controller = fetching(fetchParams); + 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: () => [] } - /** - * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model - * @returns {Promise} - */ - async #reconnect() { - if (this.#readyState === CLOSED) return; - this.#readyState = CONNECTING; - this.dispatchEvent(new Event("error")); - await delay2(this.#state.reconnectionTime); - if (this.#readyState !== CONNECTING) return; - if (this.#state.lastEventId.length) { - this.#request.headersList.set("last-event-id", this.#state.lastEventId, true); + ]); + module2.exports = { + getCookies, + deleteCookie, + getSetCookies, + setCookie, + parseCookie + }; + } +}); + +// node_modules/undici/lib/web/websocket/events.js +var require_events = __commonJS({ + "node_modules/undici/lib/web/websocket/events.js"(exports2, module2) { + "use strict"; + var { webidl } = require_webidl(); + var { kEnumerableProperty } = require_util(); + var { kConstruct } = require_symbols(); + var MessageEvent = class _MessageEvent extends Event { + #eventInit; + constructor(type, eventInitDict = {}) { + if (type === kConstruct) { + super(arguments[1], arguments[2]); + webidl.util.markAsUncloneable(this); + return; } - this.#connect(); + 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); } - /** - * 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 data() { + webidl.brandCheck(this, _MessageEvent); + return this.#eventInit.data; } - get onopen() { - return this.#events.open; + get origin() { + webidl.brandCheck(this, _MessageEvent); + return this.#eventInit.origin; } - 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 lastEventId() { + webidl.brandCheck(this, _MessageEvent); + return this.#eventInit.lastEventId; } - get onmessage() { - return this.#events.message; + get source() { + webidl.brandCheck(this, _MessageEvent); + return this.#eventInit.source; } - 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 ports() { + webidl.brandCheck(this, _MessageEvent); + if (!Object.isFrozen(this.#eventInit.ports)) { + Object.freeze(this.#eventInit.ports); } + return this.#eventInit.ports; } - get onerror() { - return this.#events.error; + 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 + }); } - 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; - } + static createFastMessageEvent(type, init2) { + const messageEvent = new _MessageEvent(kConstruct, type, init2); + messageEvent.#eventInit = init2; + messageEvent.#eventInit.data ??= null; + messageEvent.#eventInit.origin ??= ""; + messageEvent.#eventInit.lastEventId ??= ""; + messageEvent.#eventInit.source ??= null; + messageEvent.#eventInit.ports ??= []; + return messageEvent; } }; - var 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 + var { createFastMessageEvent } = MessageEvent; + delete MessageEvent.createFastMessageEvent; + var CloseEvent = 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; } }; - 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 + var ErrorEvent = 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 }); - webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([ + 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( + webidl.is.MessagePort, + "MessagePort" + ); + webidl.converters["sequence"] = webidl.sequenceConverter( + webidl.converters.MessagePort + ); + var eventInit = [ { - key: "withCredentials", + key: "bubbles", converter: webidl.converters.boolean, defaultValue: () => false }, { - key: "dispatcher", - // undici only + 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: () => [] + } + ]); + 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 } ]); module2.exports = { - EventSource, - defaultReconnectionTime + MessageEvent, + CloseEvent, + ErrorEvent, + createFastMessageEvent }; } }); -// node_modules/undici/index.js -var require_undici = __commonJS({ - "node_modules/undici/index.js"(exports2, module2) { +// node_modules/undici/lib/web/websocket/constants.js +var require_constants5 = __commonJS({ + "node_modules/undici/lib/web/websocket/constants.js"(exports2, module2) { "use strict"; - var Client = require_client(); - var Dispatcher = require_dispatcher(); - var Pool = require_pool(); - var BalancedPool = require_balanced_pool(); - var Agent = require_agent(); - var ProxyAgent2 = require_proxy_agent(); - var EnvHttpProxyAgent = require_env_http_proxy_agent(); - var RetryAgent = require_retry_agent(); - var errors = require_errors(); - var util3 = require_util(); - var { InvalidArgumentError } = errors; - var api = require_api(); - var buildConnector = require_connect(); - var MockClient = require_mock_client(); - var MockAgent = require_mock_agent(); - var MockPool = require_mock_pool(); - var mockErrors = require_mock_errors(); - var RetryHandler = require_retry_handler(); - var { getGlobalDispatcher, setGlobalDispatcher } = require_global2(); - var DecoratorHandler = require_decorator_handler(); - var RedirectHandler = require_redirect_handler(); - var createRedirectInterceptor = require_redirect_interceptor(); - Object.assign(Dispatcher.prototype, api); - module2.exports.Dispatcher = Dispatcher; - module2.exports.Client = Client; - module2.exports.Pool = Pool; - module2.exports.BalancedPool = BalancedPool; - module2.exports.Agent = Agent; - module2.exports.ProxyAgent = ProxyAgent2; - module2.exports.EnvHttpProxyAgent = EnvHttpProxyAgent; - module2.exports.RetryAgent = RetryAgent; - module2.exports.RetryHandler = RetryHandler; - module2.exports.DecoratorHandler = DecoratorHandler; - module2.exports.RedirectHandler = RedirectHandler; - module2.exports.createRedirectInterceptor = createRedirectInterceptor; - module2.exports.interceptors = { - redirect: require_redirect(), - retry: require_retry(), - dump: require_dump(), - dns: require_dns() + var uid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + var staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false }; - module2.exports.buildConnector = buildConnector; - module2.exports.errors = errors; - module2.exports.util = { - parseHeaders: util3.parseHeaders, - headerNameToString: util3.headerNameToString + var states = { + CONNECTING: 0, + OPEN: 1, + CLOSING: 2, + CLOSED: 3 }; - function makeDispatcher(fn) { - return (url2, opts, handler2) => { - if (typeof opts === "function") { - handler2 = opts; - opts = null; - } - if (!url2 || typeof url2 !== "string" && typeof url2 !== "object" && !(url2 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 path30 = opts.path; - if (!opts.path.startsWith("/")) { - path30 = `/${path30}`; - } - url2 = new URL(util3.parseOrigin(url2).origin + path30); - } else { - if (!opts) { - opts = typeof url2 === "object" ? url2 : {}; - } - url2 = util3.parseURL(url2); - } - const { agent, dispatcher = getGlobalDispatcher() } = opts; - if (agent) { - throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?"); - } - return fn.call(dispatcher, { - ...opts, - origin: url2.origin, - path: url2.search ? `${url2.pathname}${url2.search}` : url2.pathname, - method: opts.method || (opts.body ? "PUT" : "GET") - }, handler2); - }; - } - module2.exports.setGlobalDispatcher = setGlobalDispatcher; - module2.exports.getGlobalDispatcher = getGlobalDispatcher; - var fetchImpl = require_fetch().fetch; - module2.exports.fetch = async function fetch(init2, options = void 0) { - try { - return await fetchImpl(init2, options); - } catch (err) { - if (err && typeof err === "object") { - Error.captureStackTrace(err); - } - throw err; - } + var sentCloseFrameState = { + SENT: 1, + RECEIVED: 2 + }; + var opcodes = { + CONTINUATION: 0, + TEXT: 1, + BINARY: 2, + CLOSE: 8, + PING: 9, + PONG: 10 + }; + var maxUnsigned16Bit = 65535; + var parserStates = { + INFO: 0, + PAYLOADLENGTH_16: 2, + PAYLOADLENGTH_64: 3, + READ_DATA: 4 + }; + var emptyBuffer = Buffer.allocUnsafe(0); + var sendHints = { + text: 1, + typedArray: 2, + arrayBuffer: 3, + blob: 4 + }; + module2.exports = { + uid, + sentCloseFrameState, + staticPropertyDescriptors, + states, + opcodes, + maxUnsigned16Bit, + parserStates, + emptyBuffer, + sendHints }; - module2.exports.Headers = require_headers().Headers; - module2.exports.Response = require_response().Response; - module2.exports.Request = require_request2().Request; - module2.exports.FormData = require_formdata().FormData; - module2.exports.File = globalThis.File ?? require("node:buffer").File; - module2.exports.FileReader = require_filereader().FileReader; - var { setGlobalOrigin, getGlobalOrigin } = require_global(); - module2.exports.setGlobalOrigin = setGlobalOrigin; - module2.exports.getGlobalOrigin = getGlobalOrigin; - var { CacheStorage } = require_cachestorage(); - var { kConstruct } = require_symbols4(); - module2.exports.caches = new CacheStorage(kConstruct); - var { deleteCookie, getCookies, getSetCookies, setCookie } = require_cookies(); - module2.exports.deleteCookie = deleteCookie; - module2.exports.getCookies = getCookies; - module2.exports.getSetCookies = getSetCookies; - module2.exports.setCookie = setCookie; - var { parseMIMEType, serializeAMimeType } = require_data_url(); - module2.exports.parseMIMEType = parseMIMEType; - module2.exports.serializeAMimeType = serializeAMimeType; - var { CloseEvent, ErrorEvent, MessageEvent } = require_events(); - module2.exports.WebSocket = require_websocket().WebSocket; - module2.exports.CloseEvent = CloseEvent; - module2.exports.ErrorEvent = ErrorEvent; - module2.exports.MessageEvent = MessageEvent; - module2.exports.request = makeDispatcher(api.request); - module2.exports.stream = makeDispatcher(api.stream); - module2.exports.pipeline = makeDispatcher(api.pipeline); - module2.exports.connect = makeDispatcher(api.connect); - module2.exports.upgrade = makeDispatcher(api.upgrade); - module2.exports.MockClient = MockClient; - module2.exports.MockPool = MockPool; - module2.exports.MockAgent = MockAgent; - module2.exports.mockErrors = mockErrors; - var { EventSource } = require_eventsource(); - module2.exports.EventSource = EventSource; } }); -// node_modules/@actions/http-client/lib/index.js -var require_lib = __commonJS({ - "node_modules/@actions/http-client/lib/index.js"(exports2) { +// node_modules/undici/lib/web/websocket/util.js +var require_util5 = __commonJS({ + "node_modules/undici/lib/web/websocket/util.js"(exports2, module2) { "use strict"; - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) 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]; - } }; + var { states, opcodes } = require_constants5(); + var { isUtf8 } = require("node:buffer"); + var { removeHTTPWhitespace } = require_data_url(); + var { collectASequenceOfCodePointsFast } = require_infra(); + function isConnecting(readyState) { + return readyState === states.CONNECTING; + } + function isEstablished(readyState) { + return readyState === states.OPEN; + } + function isClosing(readyState) { + return readyState === states.CLOSING; + } + function isClosed(readyState) { + return readyState === states.CLOSED; + } + function fireEvent(e, target, eventFactory = (type, init2) => new Event(type, init2), eventInitDict = {}) { + const event = eventFactory(e, eventInitDict); + target.dispatchEvent(event); + } + function websocketMessageReceived(handler2, type, data) { + handler2.onMessage(type, data); + } + function toArrayBuffer(buffer) { + if (buffer.byteLength === buffer.buffer.byteLength) { + return buffer.buffer; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys2 = function(o) { - ownKeys2 = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys2(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]); - } - __setModuleDefault2(result, mod); - return result; - }; - })(); - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); - }); + return new Uint8Array(buffer).buffer; + } + function isValidSubprotocol(protocol) { + if (protocol.length === 0) { + return false; } - return new (P || (P = Promise))(function(resolve14, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + for (let i = 0; i < protocol.length; ++i) { + const code = protocol.charCodeAt(i); + if (code < 33 || // CTL, contains SP (0x20) and HT (0x09) + code > 126 || code === 34 || // " + code === 40 || // ( + code === 41 || // ) + code === 44 || // , + code === 47 || // / + code === 58 || // : + code === 59 || // ; + code === 60 || // < + code === 61 || // = + code === 62 || // > + code === 63 || // ? + code === 64 || // @ + code === 91 || // [ + code === 92 || // \ + code === 93 || // ] + code === 123 || // { + code === 125) { + return false; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; - exports2.getProxyUrl = getProxyUrl; - exports2.isHttps = isHttps; - var http = __importStar2(require("http")); - var https3 = __importStar2(require("https")); - var pm = __importStar2(require_proxy()); - var tunnel = __importStar2(require_tunnel2()); - var undici_1 = require_undici(); - var HttpCodes; - (function(HttpCodes2) { - HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; - HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; - HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; - HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; - HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; - HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; - HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; - HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; - HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; - HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; - HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; - })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); - var Headers; - (function(Headers2) { - Headers2["Accept"] = "accept"; - Headers2["ContentType"] = "content-type"; - })(Headers || (exports2.Headers = Headers = {})); - var MediaTypes; - (function(MediaTypes2) { - MediaTypes2["ApplicationJson"] = "application/json"; - })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); - function getProxyUrl(serverUrl) { - const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ""; + } + return true; } - var HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect - ]; - var HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout - ]; - var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; - var ExponentialBackoffCeiling = 10; - var ExponentialBackoffTimeSlice = 5; - var HttpClientError = class _HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = "HttpClientError"; - this.statusCode = statusCode; - Object.setPrototypeOf(this, _HttpClientError.prototype); + function isValidStatusCode(code) { + if (code >= 1e3 && code < 1015) { + return code !== 1004 && // reserved + code !== 1005 && // "MUST NOT be set as a status code" + code !== 1006; } - }; - exports2.HttpClientError = HttpClientError; - var HttpClientResponse = class { - constructor(message) { - this.message = message; + return code >= 3e3 && code <= 4999; + } + 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); + } + function parseExtensions(extensions) { + const position = { position: 0 }; + const extensionList = /* @__PURE__ */ new Map(); + while (position.position < extensions.length) { + const pair = collectASequenceOfCodePointsFast(";", extensions, position); + const [name, value = ""] = pair.split("=", 2); + extensionList.set( + removeHTTPWhitespace(name, true, false), + removeHTTPWhitespace(value, false, true) + ); + position.position++; } - readBody() { - return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14) => __awaiter2(this, void 0, void 0, function* () { - let output = Buffer.alloc(0); - this.message.on("data", (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on("end", () => { - resolve14(output.toString()); - }); - })); - }); + return extensionList; + } + function isValidClientWindowBits(value) { + if (value.length === 0) { + return false; } - readBodyBuffer() { - return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14) => __awaiter2(this, void 0, void 0, function* () { - const chunks = []; - this.message.on("data", (chunk) => { - chunks.push(chunk); - }); - this.message.on("end", () => { - resolve14(Buffer.concat(chunks)); - }); - })); - }); + for (let i = 0; i < value.length; i++) { + const byte = value.charCodeAt(i); + if (byte < 48 || byte > 57) { + return false; + } } - }; - exports2.HttpClientResponse = HttpClientResponse; - function isHttps(requestUrl) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === "https:"; + const num = Number.parseInt(value, 10); + return num >= 8 && num <= 15; } - var HttpClient2 = class { - constructor(userAgent2, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = this._getUserAgentWithOrchestrationId(userAgent2); - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } - } + function getURLRecord(url2, baseURL) { + let urlRecord; + try { + urlRecord = new URL(url2, baseURL); + } catch (e) { + throw new DOMException(e, "SyntaxError"); } - options(requestUrl, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); - }); + if (urlRecord.protocol === "http:") { + urlRecord.protocol = "ws:"; + } else if (urlRecord.protocol === "https:") { + urlRecord.protocol = "wss:"; } - get(requestUrl, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("GET", requestUrl, null, additionalHeaders || {}); - }); + if (urlRecord.protocol !== "ws:" && urlRecord.protocol !== "wss:") { + throw new DOMException("expected a ws: or wss: url", "SyntaxError"); } - del(requestUrl, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("DELETE", requestUrl, null, additionalHeaders || {}); - }); + if (urlRecord.hash.length || urlRecord.href.endsWith("#")) { + throw new DOMException("hash", "SyntaxError"); } - post(requestUrl, data, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("POST", requestUrl, data, additionalHeaders || {}); - }); + return urlRecord; + } + function validateCloseCodeAndReason(code, reason) { + if (code !== null) { + if (code !== 1e3 && (code < 3e3 || code > 4999)) { + throw new DOMException("invalid code", "InvalidAccessError"); + } } - patch(requestUrl, data, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("PATCH", requestUrl, data, additionalHeaders || {}); - }); + if (reason !== null) { + const reasonBytesLength = Buffer.byteLength(reason); + if (reasonBytesLength > 123) { + throw new DOMException(`Reason must be less than 123 bytes; received ${reasonBytesLength}`, "SyntaxError"); + } } - put(requestUrl, data, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("PUT", requestUrl, data, additionalHeaders || {}); - }); + } + var utf8Decode = (() => { + if (typeof process.versions.icu === "string") { + const fatalDecoder = new TextDecoder("utf-8", { fatal: true }); + return fatalDecoder.decode.bind(fatalDecoder); } - head(requestUrl, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("HEAD", requestUrl, null, additionalHeaders || {}); - }); + return function(buffer) { + if (isUtf8(buffer)) { + return buffer.toString("utf-8"); + } + throw new TypeError("Invalid utf-8 received."); + }; + })(); + module2.exports = { + isConnecting, + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + websocketMessageReceived, + utf8Decode, + isControlFrame, + isContinuationFrame, + isTextBinaryFrame, + isValidOpcode, + parseExtensions, + isValidClientWindowBits, + toArrayBuffer, + getURLRecord, + validateCloseCodeAndReason + }; + } +}); + +// node_modules/undici/lib/web/websocket/frame.js +var require_frame = __commonJS({ + "node_modules/undici/lib/web/websocket/frame.js"(exports2, module2) { + "use strict"; + var { runtimeFeatures } = require_runtime_features(); + var { maxUnsigned16Bit, opcodes } = require_constants5(); + var BUFFER_SIZE = 8 * 1024; + var buffer = null; + var bufIdx = BUFFER_SIZE; + var randomFillSync = runtimeFeatures.has("crypto") ? require("node:crypto").randomFillSync : function randomFillSync2(buffer2, _offset, _size) { + for (let i = 0; i < buffer2.length; ++i) { + buffer2[i] = Math.random() * 255 | 0; } - sendStream(verb, requestUrl, stream2, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream2, additionalHeaders); - }); + return buffer2; + }; + function generateMask() { + if (bufIdx === BUFFER_SIZE) { + bufIdx = 0; + randomFillSync(buffer ??= Buffer.allocUnsafeSlow(BUFFER_SIZE), 0, BUFFER_SIZE); } + return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]]; + } + var WebsocketFrameSend = class { /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + * @param {Buffer|undefined} data */ - getJson(requestUrl_1) { - return __awaiter2(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - postJson(requestUrl_1, obj_1) { - return __awaiter2(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - putJson(requestUrl_1, obj_1) { - return __awaiter2(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); + constructor(data) { + this.frameData = data; } - patchJson(requestUrl_1, obj_1) { - return __awaiter2(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); + createFrame(opcode) { + const frameData = this.frameData; + const maskKey = generateMask(); + const bodyLength = frameData?.byteLength ?? 0; + let payloadLength = bodyLength; + let offset = 6; + if (bodyLength > maxUnsigned16Bit) { + offset += 8; + payloadLength = 127; + } else if (bodyLength > 125) { + offset += 2; + payloadLength = 126; + } + const buffer2 = Buffer.allocUnsafe(bodyLength + offset); + buffer2[0] = buffer2[1] = 0; + buffer2[0] |= 128; + buffer2[0] = (buffer2[0] & 240) + opcode; + buffer2[offset - 4] = maskKey[0]; + buffer2[offset - 3] = maskKey[1]; + buffer2[offset - 2] = maskKey[2]; + buffer2[offset - 1] = maskKey[3]; + buffer2[1] = payloadLength; + if (payloadLength === 126) { + buffer2.writeUInt16BE(bodyLength, 2); + } else if (payloadLength === 127) { + buffer2[2] = buffer2[3] = 0; + buffer2.writeUIntBE(bodyLength, 4, 6); + } + buffer2[1] |= 128; + for (let i = 0; i < bodyLength; ++i) { + buffer2[offset + i] = frameData[i] ^ maskKey[i & 3]; + } + return buffer2; } /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch + * @param {Uint8Array} buffer */ - request(verb, requestUrl, data, headers) { - return __awaiter2(this, void 0, void 0, function* () { - if (this._disposed) { - throw new Error("Client has already been disposed."); - } - const parsedUrl = new URL(requestUrl); - let info8 = this._prepareRequest(verb, parsedUrl, headers); - const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; - let numTries = 0; - let response; - do { - response = yield this.requestRaw(info8, data); - if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (const handler2 of this.handlers) { - if (handler2.canHandleAuthentication(response)) { - authenticationHandler = handler2; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info8, data); - } else { - return response; - } + static createFastTextFrame(buffer2) { + const maskKey = generateMask(); + const bodyLength = buffer2.length; + for (let i = 0; i < bodyLength; ++i) { + buffer2[i] ^= maskKey[i & 3]; + } + let payloadLength = bodyLength; + let offset = 6; + if (bodyLength > maxUnsigned16Bit) { + offset += 8; + payloadLength = 127; + } else if (bodyLength > 125) { + offset += 2; + payloadLength = 126; + } + const head = Buffer.allocUnsafeSlow(offset); + head[0] = 128 | opcodes.TEXT; + head[1] = payloadLength | 128; + head[offset - 4] = maskKey[0]; + head[offset - 3] = maskKey[1]; + head[offset - 2] = maskKey[2]; + head[offset - 1] = maskKey[3]; + if (payloadLength === 126) { + head.writeUInt16BE(bodyLength, 2); + } else if (payloadLength === 127) { + head[2] = head[3] = 0; + head.writeUIntBE(bodyLength, 4, 6); + } + return [head, buffer2]; + } + }; + module2.exports = { + WebsocketFrameSend, + generateMask + // for benchmark + }; + } +}); + +// node_modules/undici/lib/web/websocket/connection.js +var require_connection = __commonJS({ + "node_modules/undici/lib/web/websocket/connection.js"(exports2, module2) { + "use strict"; + var { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require_constants5(); + var { parseExtensions, isClosed, isClosing, isEstablished, isConnecting, validateCloseCodeAndReason } = require_util5(); + var { makeRequest } = require_request2(); + var { fetching } = require_fetch(); + var { Headers, getHeadersList } = require_headers(); + var { getDecodeSplit } = require_util2(); + var { WebsocketFrameSend } = require_frame(); + var assert = require("node:assert"); + var { runtimeFeatures } = require_runtime_features(); + var crypto3 = runtimeFeatures.has("crypto") ? require("node:crypto") : null; + var warningEmitted = false; + function establishWebSocketConnection(url2, protocols, client, handler2, options) { + const requestURL = url2; + requestURL.protocol = url2.protocol === "ws:" ? "http:" : "https:"; + const request3 = makeRequest({ + urlList: [requestURL], + client, + serviceWorkers: "none", + referrer: "no-referrer", + mode: "websocket", + credentials: "include", + cache: "no-store", + redirect: "error", + useURLCredentials: true + }); + if (options.headers) { + const headersList = getHeadersList(new Headers(options.headers)); + request3.headersList = headersList; + } + const keyValue = crypto3.randomBytes(16).toString("base64"); + request3.headersList.append("sec-websocket-key", keyValue, true); + request3.headersList.append("sec-websocket-version", "13", true); + for (const protocol of protocols) { + request3.headersList.append("sec-websocket-protocol", protocol, true); + } + const permessageDeflate = "permessage-deflate; client_max_window_bits"; + request3.headersList.append("sec-websocket-extensions", permessageDeflate, true); + const controller = fetching({ + request: request3, + useParallelQueue: true, + dispatcher: options.dispatcher, + processResponse(response) { + if (response.type === "error" || response.status !== 101) { + if (response.socket?.session == null) { + failHandshake(handler2, response, 1002, "Received network error or non-101 status code.", response.error); + return; } - let redirectsRemaining = this._maxRedirects; - while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { - const redirectUrl = response.message.headers["location"]; - if (!redirectUrl) { - break; - } - const parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { - throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); - } - yield response.readBody(); - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (const header in headers) { - if (header.toLowerCase() === "authorization") { - delete headers[header]; - } - } - } - info8 = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info8, data); - redirectsRemaining--; + if (response.status !== 200) { + failHandshake(handler2, response, 1002, "Received network error or non-200 status code.", response.error); + return; } - if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { - return response; + } + if (warningEmitted === false && response.socket?.session != null) { + process.emitWarning("WebSocket over HTTP2 is experimental, and subject to change.", "ExperimentalWarning"); + warningEmitted = true; + } + if (protocols.length !== 0 && !response.headersList.get("Sec-WebSocket-Protocol")) { + failHandshake(handler2, response, 1002, "Server did not respond with sent protocols."); + return; + } + if (response.socket.session == null && response.headersList.get("Upgrade")?.toLowerCase() !== "websocket") { + failHandshake(handler2, response, 1002, 'Server did not set Upgrade header to "websocket".'); + return; + } + if (response.socket.session == null && response.headersList.get("Connection")?.toLowerCase() !== "upgrade") { + failHandshake(handler2, response, 1002, 'Server did not set Connection header to "upgrade".'); + return; + } + const secWSAccept = response.headersList.get("Sec-WebSocket-Accept"); + const digest = crypto3.hash("sha1", keyValue + uid, "base64"); + if (secWSAccept !== digest) { + failHandshake(handler2, response, 1002, "Incorrect hash received in Sec-WebSocket-Accept header."); + return; + } + const secExtension = response.headersList.get("Sec-WebSocket-Extensions"); + let extensions; + if (secExtension !== null) { + extensions = parseExtensions(secExtension); + if (!extensions.has("permessage-deflate")) { + failHandshake(handler2, response, 1002, "Sec-WebSocket-Extensions header does not match."); + return; } - numTries += 1; - if (numTries < maxTries) { - yield response.readBody(); - yield this._performExponentialBackoff(numTries); + } + const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); + if (secProtocol !== null) { + const requestProtocols = getDecodeSplit("sec-websocket-protocol", request3.headersList); + if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + failHandshake(handler2, response, 1002, "Protocol was not set in the opening handshake."); + return; } - } while (numTries < maxTries); - return response; - }); - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); + } + response.socket.on("data", handler2.onSocketData); + response.socket.on("close", handler2.onSocketClose); + response.socket.on("error", handler2.onSocketError); + handler2.wasEverConnected = true; + handler2.onConnectionEstablished(response, extensions); } - this._disposed = true; + }); + return controller; + } + function closeWebSocketConnection(object2, code, reason, validate2 = false) { + code ??= null; + reason ??= ""; + if (validate2) validateCloseCodeAndReason(code, reason); + if (isClosed(object2.readyState) || isClosing(object2.readyState)) { + } else if (!isEstablished(object2.readyState)) { + failWebsocketConnection(object2); + object2.readyState = states.CLOSING; + } else if (!object2.closeState.has(sentCloseFrameState.SENT) && !object2.closeState.has(sentCloseFrameState.RECEIVED)) { + const frame = new WebsocketFrameSend(); + if (reason.length !== 0 && code === null) { + code = 1e3; + } + assert(code === null || Number.isInteger(code)); + if (code === null && reason.length === 0) { + frame.frameData = emptyBuffer; + } else if (code !== null && reason === null) { + frame.frameData = Buffer.allocUnsafe(2); + frame.frameData.writeUInt16BE(code, 0); + } else if (code !== null && reason !== null) { + frame.frameData = Buffer.allocUnsafe(2 + Buffer.byteLength(reason)); + frame.frameData.writeUInt16BE(code, 0); + frame.frameData.write(reason, 2, "utf-8"); + } else { + frame.frameData = emptyBuffer; + } + object2.socket.write(frame.createFrame(opcodes.CLOSE)); + object2.closeState.add(sentCloseFrameState.SENT); + object2.readyState = states.CLOSING; + } else { + object2.readyState = states.CLOSING; + } + } + function failHandshake(handler2, response, code, reason, cause) { + if (response.socket?.session != null && !response.socket.destroyed) { + response.socket.destroy(); + } + failWebsocketConnection(handler2, code, reason, cause); + } + function failWebsocketConnection(handler2, code, reason, cause) { + if (isEstablished(handler2.readyState)) { + closeWebSocketConnection(handler2, code, reason, false); + } + handler2.controller.abort(); + if (isConnecting(handler2.readyState)) { + handler2.onSocketClose(); + } else if (handler2.socket?.destroyed === false) { + handler2.socket.destroy(); } + } + module2.exports = { + establishWebSocketConnection, + failWebsocketConnection, + closeWebSocketConnection + }; + } +}); + +// node_modules/undici/lib/web/websocket/permessage-deflate.js +var require_permessage_deflate = __commonJS({ + "node_modules/undici/lib/web/websocket/permessage-deflate.js"(exports2, module2) { + "use strict"; + var { createInflateRaw, Z_DEFAULT_WINDOWBITS } = require("node:zlib"); + var { isValidClientWindowBits } = require_util5(); + var { MessageSizeExceededError } = require_errors(); + var tail = Buffer.from([0, 0, 255, 255]); + var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); + var kLength = /* @__PURE__ */ Symbol("kLength"); + var PerMessageDeflate = class { + /** @type {import('node:zlib').InflateRaw} */ + #inflate; + #options = {}; + #maxPayloadSize = 0; /** - * Raw request. - * @param info - * @param data + * @param {Map} extensions */ - requestRaw(info8, data) { - return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14, reject) => { - function callbackForResult(err, res) { - if (err) { - reject(err); - } else if (!res) { - reject(new Error("Unknown error")); - } else { - resolve14(res); - } - } - this.requestRawWithCallback(info8, data, callbackForResult); - }); - }); + 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; } /** - * Raw request with callback. - * @param info - * @param data - * @param onResult + * Decompress a compressed payload. + * @param {Buffer} chunk Compressed data + * @param {boolean} fin Final fragment flag + * @param {Function} callback Callback function */ - requestRawWithCallback(info8, data, onResult) { - if (typeof data === "string") { - if (!info8.options.headers) { - info8.options.headers = {}; + decompress(chunk, fin, callback) { + if (!this.#inflate) { + let windowBits = Z_DEFAULT_WINDOWBITS; + if (this.#options.serverMaxWindowBits) { + if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) { + callback(new Error("Invalid server_max_window_bits")); + return; + } + windowBits = Number.parseInt(this.#options.serverMaxWindowBits); } - info8.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); - } - let callbackCalled = false; - function handleResult(err, res) { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); + 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.destroy(); + this.#inflate = null; + return; + } + this.#inflate[kBuffer].push(data); + }); + this.#inflate.on("error", (err) => { + this.#inflate = null; + callback(err); + }); } - const req = info8.httpModule.request(info8.options, (msg) => { - const res = new HttpClientResponse(msg); - handleResult(void 0, res); - }); - let socket; - req.on("socket", (sock) => { - socket = sock; - }); - req.setTimeout(this._socketTimeout || 3 * 6e4, () => { - if (socket) { - socket.end(); + this.#inflate.write(chunk); + if (fin) { + this.#inflate.write(tail); + } + this.#inflate.flush(() => { + if (!this.#inflate) { + return; } - handleResult(new Error(`Request timeout: ${info8.options.path}`)); - }); - req.on("error", function(err) { - handleResult(err); + const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); + this.#inflate[kBuffer].length = 0; + this.#inflate[kLength] = 0; + callback(null, full); }); - if (data && typeof data === "string") { - req.write(data, "utf8"); - } - if (data && typeof data !== "string") { - data.on("close", function() { - req.end(); - }); - data.pipe(req); - } else { - req.end(); - } } + }; + module2.exports = { PerMessageDeflate }; + } +}); + +// node_modules/undici/lib/web/websocket/receiver.js +var require_receiver = __commonJS({ + "node_modules/undici/lib/web/websocket/receiver.js"(exports2, module2) { + "use strict"; + var { Writable } = require("node:stream"); + var assert = require("node:assert"); + var { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = require_constants5(); + var { + isValidStatusCode, + isValidOpcode, + websocketMessageReceived, + utf8Decode, + isControlFrame, + isTextBinaryFrame, + isContinuationFrame + } = require_util5(); + var { failWebsocketConnection } = require_connection(); + var { WebsocketFrameSend } = require_frame(); + var { PerMessageDeflate } = require_permessage_deflate(); + var { MessageSizeExceededError } = require_errors(); + var ByteParser = class extends Writable { + #buffers = []; + #fragmentsBytes = 0; + #byteOffset = 0; + #loop = false; + #state = parserStates.INFO; + #info = {}; + #fragments = []; + /** @type {Map} */ + #extensions; + /** @type {import('./websocket').Handler} */ + #handler; + /** @type {number} */ + #maxFragments; + /** @type {number} */ + #maxPayloadSize; /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + * @param {import('./websocket').Handler} handler + * @param {Map|null} extensions + * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] */ - getAgent(serverUrl) { - const parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); - } - getAgentDispatcher(serverUrl) { - const parsedUrl = new URL(serverUrl); - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (!useProxy) { - return; - } - return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info8 = {}; - info8.parsedUrl = requestUrl; - const usingSsl = info8.parsedUrl.protocol === "https:"; - info8.httpModule = usingSsl ? https3 : http; - const defaultPort = usingSsl ? 443 : 80; - info8.options = {}; - info8.options.host = info8.parsedUrl.hostname; - info8.options.port = info8.parsedUrl.port ? parseInt(info8.parsedUrl.port) : defaultPort; - info8.options.path = (info8.parsedUrl.pathname || "") + (info8.parsedUrl.search || ""); - info8.options.method = method; - info8.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info8.options.headers["user-agent"] = this.userAgent; - } - info8.options.agent = this._getAgent(info8.parsedUrl); - if (this.handlers) { - for (const handler2 of this.handlers) { - handler2.prepareRequest(info8.options); - } - } - return info8; - } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys2(this.requestOptions.headers), lowercaseKeys2(headers || {})); + constructor(handler2, extensions, options = {}) { + super(); + this.#handler = handler2; + this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; + this.#maxFragments = options.maxFragments ?? 0; + this.#maxPayloadSize = options.maxPayloadSize ?? 0; + if (this.#extensions.has("permessage-deflate")) { + this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } - return lowercaseKeys2(headers || {}); } /** - * Gets an existing header value or returns a default. - * Handles converting number header values to strings since HTTP headers must be strings. - * Note: This returns string | string[] since some headers can have multiple values. - * For headers that must always be a single string (like Content-Type), use the - * specialized _getExistingOrDefaultContentTypeHeader method instead. + * @param {Buffer} chunk + * @param {() => void} callback */ - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - const headerValue = lowercaseKeys2(this.requestOptions.headers)[header]; - if (headerValue) { - clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; - } - } - const additionalValue = additionalHeaders[header]; - if (additionalValue !== void 0) { - return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; - } - if (clientHeader !== void 0) { - return clientHeader; + _write(chunk, _2, 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.#fragmentsBytes > this.#maxPayloadSize) { + failWebsocketConnection(this.#handler, 1009, "Payload size exceeds maximum allowed size"); + return false; } - return _default; + return true; } /** - * Specialized version of _getExistingOrDefaultHeader for Content-Type header. - * Always returns a single string (not an array) since Content-Type should be a single value. - * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. - * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers - * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + * 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. */ - _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - const headerValue = lowercaseKeys2(this.requestOptions.headers)[Headers.ContentType]; - if (headerValue) { - if (typeof headerValue === "number") { - clientHeader = String(headerValue); - } else if (Array.isArray(headerValue)) { - clientHeader = headerValue.join(", "); - } else { - clientHeader = headerValue; + run(callback) { + while (this.#loop) { + if (this.#state === parserStates.INFO) { + if (this.#byteOffset < 2) { + return callback(); + } + const buffer = this.consume(2); + const fin = (buffer[0] & 128) !== 0; + const opcode = buffer[0] & 15; + const masked = (buffer[1] & 128) === 128; + const fragmented = !fin && opcode !== opcodes.CONTINUATION; + const payloadLength = buffer[1] & 127; + const rsv1 = buffer[0] & 64; + const rsv2 = buffer[0] & 32; + const rsv3 = buffer[0] & 16; + if (!isValidOpcode(opcode)) { + failWebsocketConnection(this.#handler, 1002, "Invalid opcode received"); + return callback(); + } + if (masked) { + failWebsocketConnection(this.#handler, 1002, "Frame cannot be masked"); + return callback(); + } + if (rsv1 !== 0 && !this.#extensions.has("permessage-deflate")) { + failWebsocketConnection(this.#handler, 1002, "Expected RSV1 to be clear."); + return; + } + if (rsv2 !== 0 || rsv3 !== 0) { + failWebsocketConnection(this.#handler, 1002, "RSV1, RSV2, RSV3 must be clear"); + return; + } + if (fragmented && !isTextBinaryFrame(opcode)) { + failWebsocketConnection(this.#handler, 1002, "Invalid frame type was fragmented."); + return; + } + if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) { + failWebsocketConnection(this.#handler, 1002, "Expected continuation frame"); + return; + } + if (this.#info.fragmented && fragmented) { + failWebsocketConnection(this.#handler, 1002, "Fragmented frame exceeded 125 bytes."); + return; + } + if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) { + failWebsocketConnection(this.#handler, 1002, "Control frame either too large or fragmented"); + return; + } + if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) { + failWebsocketConnection(this.#handler, 1002, "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); + if (upper !== 0 || lower > 2 ** 31 - 1) { + failWebsocketConnection(this.#handler, 1009, "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; + if (this.#loop && this.#handler.socket.writableNeedDrain) { + this.#loop = false; + this.#handler.socket.once("drain", () => { + if (this.destroyed) return; + this.#loop = true; + this.run(callback); + }); + return; + } + } else { + if (!this.#info.compressed) { + if (!this.writeFragments(body)) { + return; + } + if (!this.#info.fragmented && this.#info.fin) { + websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments()); + } + this.#state = parserStates.INFO; + } else { + this.#extensions.get("permessage-deflate").decompress( + body, + this.#info.fin, + (error3, data) => { + if (error3) { + const code = error3 instanceof MessageSizeExceededError ? 1009 : 1007; + failWebsocketConnection(this.#handler, code, error3.message); + return; + } + if (!this.writeFragments(data)) { + return; + } + if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { + failWebsocketConnection(this.#handler, 1009, new MessageSizeExceededError().message); + return; + } + if (!this.#info.fin) { + this.#state = parserStates.INFO; + this.#loop = true; + this.run(callback); + return; + } + websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments()); + this.#loop = true; + this.#state = parserStates.INFO; + this.run(callback); + }, + this.#fragmentsBytes + ); + this.#loop = false; + break; + } } } } - const additionalValue = additionalHeaders[Headers.ContentType]; - if (additionalValue !== void 0) { - if (typeof additionalValue === "number") { - return String(additionalValue); - } else if (Array.isArray(additionalValue)) { - return additionalValue.join(", "); - } else { - return additionalValue; - } + } + /** + * 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 (clientHeader !== void 0) { - return clientHeader; + this.#byteOffset -= n; + const first = this.#buffers[0]; + if (first.length > n) { + this.#buffers[0] = first.subarray(n, first.length); + return first.subarray(0, n); + } else if (first.length === n) { + return this.#buffers.shift(); + } else { + let offset = 0; + const buffer = Buffer.allocUnsafeSlow(n); + while (offset !== n) { + const next = this.#buffers[0]; + const length = next.length; + 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 += length; + } + } + return buffer; } - return _default; } - _getAgent(parsedUrl) { - let agent; - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; + writeFragments(fragment) { + if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { + failWebsocketConnection(this.#handler, 1008, "Too many message fragments"); + return false; } - if (!useProxy) { - agent = this._agent; + this.#fragmentsBytes += fragment.length; + this.#fragments.push(fragment); + return true; + } + consumeFragments() { + const fragments = this.#fragments; + if (fragments.length === 1) { + this.#fragmentsBytes = 0; + return fragments.shift(); } - if (agent) { - return agent; + let offset = 0; + const output = Buffer.allocUnsafeSlow(this.#fragmentsBytes); + for (let i = 0; i < fragments.length; ++i) { + const buffer = fragments[i]; + output.set(buffer, offset); + offset += buffer.length; } - const usingSsl = parsedUrl.protocol === "https:"; - let maxSockets = 100; - if (this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + this.#fragments = []; + this.#fragmentsBytes = 0; + return output; + } + parseCloseBody(data) { + assert(data.length !== 1); + let code; + if (data.length >= 2) { + code = data.readUInt16BE(0); } - if (proxyUrl && proxyUrl.hostname) { - const agentOptions = { - maxSockets, - keepAlive: this._keepAlive, - proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - }), { host: proxyUrl.hostname, port: proxyUrl.port }) - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === "https:"; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; + if (code !== void 0 && !isValidStatusCode(code)) { + return { code: 1002, reason: "Invalid status code", error: true }; } - if (!agent) { - const options = { keepAlive: this._keepAlive, maxSockets }; - agent = usingSsl ? new https3.Agent(options) : new http.Agent(options); - this._agent = agent; + let reason = data.subarray(2); + if (reason[0] === 239 && reason[1] === 187 && reason[2] === 191) { + reason = reason.subarray(3); } - if (usingSsl && this._ignoreSslError) { - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); + try { + reason = utf8Decode(reason); + } catch { + return { code: 1007, reason: "Invalid UTF-8", error: true }; } - return agent; + return { code, reason, error: false }; } - _getProxyAgentDispatcher(parsedUrl, proxyUrl) { - let proxyAgent; - if (this._keepAlive) { - proxyAgent = this._proxyAgentDispatcher; - } - if (proxyAgent) { - return proxyAgent; - } - const usingSsl = parsedUrl.protocol === "https:"; - proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { - token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` - })); - this._proxyAgentDispatcher = proxyAgent; - if (usingSsl && this._ignoreSslError) { - proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { - rejectUnauthorized: false - }); + /** + * Parses control frames. + * @param {Buffer} body + */ + parseControlFrame(body) { + const { opcode, payloadLength } = this.#info; + if (opcode === opcodes.CLOSE) { + if (payloadLength === 1) { + failWebsocketConnection(this.#handler, 1002, "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; + failWebsocketConnection(this.#handler, code, reason); + return false; + } + if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + let body2 = emptyBuffer; + if (this.#info.closeInfo.code) { + body2 = Buffer.allocUnsafe(2); + body2.writeUInt16BE(this.#info.closeInfo.code, 0); + } + const closeFrame = new WebsocketFrameSend(body2); + this.#handler.socket.write(closeFrame.createFrame(opcodes.CLOSE)); + this.#handler.closeState.add(sentCloseFrameState.SENT); + } + this.#handler.readyState = states.CLOSING; + this.#handler.closeState.add(sentCloseFrameState.RECEIVED); + return false; + } else if (opcode === opcodes.PING) { + if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + const frame = new WebsocketFrameSend(body); + this.#handler.socket.write(frame.createFrame(opcodes.PONG)); + this.#handler.onPing(body); + } + } else if (opcode === opcodes.PONG) { + this.#handler.onPong(body); } - return proxyAgent; + return true; } - _getUserAgentWithOrchestrationId(userAgent2) { - const baseUserAgent = userAgent2 || "actions/http-client"; - const orchId = process.env["ACTIONS_ORCHESTRATION_ID"]; - if (orchId) { - const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, "_"); - return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`; - } - return baseUserAgent; + get closingInfo() { + return this.#info.closeInfo; } - _performExponentialBackoff(retryNumber) { - return __awaiter2(this, void 0, void 0, function* () { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise((resolve14) => setTimeout(() => resolve14(), ms)); - }); + }; + module2.exports = { + ByteParser + }; + } +}); + +// node_modules/undici/lib/web/websocket/sender.js +var require_sender = __commonJS({ + "node_modules/undici/lib/web/websocket/sender.js"(exports2, module2) { + "use strict"; + var { WebsocketFrameSend } = require_frame(); + var { opcodes, sendHints } = require_constants5(); + var FixedQueue = require_fixed_queue(); + var SendQueue = class { + /** + * @type {FixedQueue} + */ + #queue = new FixedQueue(); + /** + * @type {boolean} + */ + #running = false; + /** @type {import('node:net').Socket} */ + #socket; + constructor(socket) { + this.#socket = socket; } - _processResponse(res, options) { - return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14, reject) => __awaiter2(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode || 0; - const response = { - statusCode, - result: null, - headers: {} - }; - if (statusCode === HttpCodes.NotFound) { - resolve14(response); - } - function dateTimeDeserializer(key, value) { - if (typeof value === "string") { - const a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - let obj; - let contents; - try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, dateTimeDeserializer); - } else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } catch (err) { - } - if (statusCode > 299) { - let msg; - if (obj && obj.message) { - msg = obj.message; - } else if (contents && contents.length > 0) { - msg = contents; - } else { - msg = `Failed request: (${statusCode})`; - } - const err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); + add(item, cb, hint) { + if (hint !== sendHints.blob) { + if (!this.#running) { + if (hint === sendHints.text) { + const { 0: head, 1: body } = WebsocketFrameSend.createFastTextFrame(item); + this.#socket.cork(); + this.#socket.write(head); + this.#socket.write(body, cb); + this.#socket.uncork(); } else { - resolve14(response); + this.#socket.write(createFrame(item, hint), cb); } - })); - }); + } else { + const node2 = { + promise: null, + callback: cb, + frame: createFrame(item, hint) + }; + this.#queue.push(node2); + } + return; + } + 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 queue2 = this.#queue; + while (!queue2.isEmpty()) { + const node = queue2.shift(); + if (node.promise !== null) { + await node.promise; + } + this.#socket.write(node.frame, node.callback); + node.callback = node.frame = null; + } + this.#running = false; } }; - exports2.HttpClient = HttpClient2; - var lowercaseKeys2 = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + function createFrame(data, hint) { + return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.text ? opcodes.TEXT : opcodes.BINARY); + } + function toBuffer(data, hint) { + switch (hint) { + case sendHints.text: + case sendHints.typedArray: + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength); + case sendHints.arrayBuffer: + case sendHints.blob: + return new Uint8Array(data); + } + } + module2.exports = { SendQueue }; } }); -// node_modules/@actions/http-client/lib/auth.js -var require_auth = __commonJS({ - "node_modules/@actions/http-client/lib/auth.js"(exports2) { +// node_modules/undici/lib/web/websocket/websocket.js +var require_websocket = __commonJS({ + "node_modules/undici/lib/web/websocket/websocket.js"(exports2, module2) { "use strict"; - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); - }); + var { isArrayBuffer } = require("node:util/types"); + var { webidl } = require_webidl(); + var { URLSerializer } = require_data_url(); + var { environmentSettingsObject } = require_util2(); + var { staticPropertyDescriptors, states, sentCloseFrameState, sendHints, opcodes } = require_constants5(); + var { + isConnecting, + isEstablished, + isClosing, + isClosed, + isValidSubprotocol, + fireEvent, + utf8Decode, + toArrayBuffer, + getURLRecord + } = require_util5(); + var { establishWebSocketConnection, closeWebSocketConnection, failWebsocketConnection } = require_connection(); + var { ByteParser } = require_receiver(); + var { kEnumerableProperty } = require_util(); + var { getGlobalDispatcher } = require_global2(); + var { ErrorEvent, CloseEvent, createFastMessageEvent } = require_events(); + var { SendQueue } = require_sender(); + var { WebsocketFrameSend } = require_frame(); + var { channels } = require_diagnostics(); + function getSocketAddress(socket) { + if (typeof socket?.address === "function") { + return socket.address(); } - return new (P || (P = Promise))(function(resolve14, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + if (typeof socket?.session?.socket?.address === "function") { + return socket.session.socket.address(); + } + return null; + } + var WebSocket = class _WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + }; + #bufferedAmount = 0; + #protocol = ""; + #extensions = ""; + /** @type {SendQueue} */ + #sendQueue; + /** @type {Handler} */ + #handler = { + onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions), + onMessage: (opcode, data) => this.#onMessage(opcode, data), + onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message), + onParserDrain: () => this.#onParserDrain(), + onSocketData: (chunk) => { + if (!this.#parser.write(chunk)) { + this.#handler.socket.pause(); } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + }, + onSocketError: (err) => { + this.#handler.readyState = states.CLOSING; + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(err); + } + this.#handler.socket.destroy(); + }, + onSocketClose: () => this.#onSocketClose(), + onPing: (body) => { + if (channels.ping.hasSubscribers) { + channels.ping.publish({ + payload: body, + websocket: this + }); + } + }, + onPong: (body) => { + if (channels.pong.hasSubscribers) { + channels.pong.publish({ + payload: body, + websocket: this + }); } + }, + readyState: states.CONNECTING, + socket: null, + closeState: /* @__PURE__ */ new Set(), + controller: null, + wasEverConnected: false + }; + #url; + #binaryType; + /** @type {import('./receiver').ByteParser} */ + #parser; + /** + * @param {string} url + * @param {string|string[]} protocols + */ + constructor(url2, 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"); + url2 = webidl.converters.USVString(url2); + protocols = options.protocols; + const baseURL = environmentSettingsObject.settingsObject.baseUrl; + const urlRecord = getURLRecord(url2, baseURL); + if (typeof protocols === "string") { + protocols = [protocols]; } - function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + if (protocols.length !== new Set(protocols.map((p) => p.toLowerCase())).size) { + throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; - var BasicCredentialHandler = class { - constructor(username, password) { - this.username = username; - this.password = password; + if (protocols.length > 0 && !protocols.every((p) => isValidSubprotocol(p))) { + throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); + } + this.#url = new URL(urlRecord.href); + const client = environmentSettingsObject.settingsObject; + this.#handler.controller = establishWebSocketConnection( + urlRecord, + protocols, + client, + this.#handler, + options + ); + this.#handler.readyState = _WebSocket.CONNECTING; + this.#binaryType = "blob"; } - prepareRequest(options) { - if (!options.headers) { - throw Error("The request has no headers"); + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-close + * @param {number|undefined} code + * @param {string|undefined} reason + */ + close(code = void 0, reason = void 0) { + webidl.brandCheck(this, _WebSocket); + const prefix = "WebSocket.close"; + if (code !== void 0) { + code = webidl.converters["unsigned short"](code, prefix, "code", webidl.attributes.Clamp); } - options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; + if (reason !== void 0) { + reason = webidl.converters.USVString(reason); + } + code ??= null; + reason ??= ""; + closeWebSocketConnection(this.#handler, code, reason, true); } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; + /** + * @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"); + if (isConnecting(this.#handler.readyState)) { + throw new DOMException("Sent before connected.", "InvalidStateError"); + } + if (!isEstablished(this.#handler.readyState) || isClosing(this.#handler.readyState)) { + return; + } + if (typeof data === "string") { + const buffer = Buffer.from(data); + this.#bufferedAmount += buffer.byteLength; + this.#sendQueue.add(buffer, () => { + this.#bufferedAmount -= buffer.byteLength; + }, sendHints.text); + } else if (isArrayBuffer(data)) { + this.#bufferedAmount += data.byteLength; + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.byteLength; + }, sendHints.arrayBuffer); + } else if (ArrayBuffer.isView(data)) { + this.#bufferedAmount += data.byteLength; + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.byteLength; + }, sendHints.typedArray); + } else if (webidl.is.Blob(data)) { + this.#bufferedAmount += data.size; + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.size; + }, sendHints.blob); + } } - handleAuthentication() { - return __awaiter2(this, void 0, void 0, function* () { - throw new Error("not implemented"); - }); + get readyState() { + webidl.brandCheck(this, _WebSocket); + return this.#handler.readyState; } - }; - exports2.BasicCredentialHandler = BasicCredentialHandler; - var BearerCredentialHandler = class { - constructor(token) { - this.token = token; + get bufferedAmount() { + webidl.brandCheck(this, _WebSocket); + return this.#bufferedAmount; } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error("The request has no headers"); + get url() { + webidl.brandCheck(this, _WebSocket); + return URLSerializer(this.#url); + } + 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); + } + const listener = webidl.converters.EventHandlerNonNull(fn); + if (listener !== null) { + this.addEventListener("open", listener); + this.#events.open = fn; + } else { + this.#events.open = null; } - options.headers["Authorization"] = `Bearer ${this.token}`; } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; + get onerror() { + webidl.brandCheck(this, _WebSocket); + return this.#events.error; } - handleAuthentication() { - return __awaiter2(this, void 0, void 0, function* () { - throw new Error("not implemented"); - }); + set onerror(fn) { + webidl.brandCheck(this, _WebSocket); + if (this.#events.error) { + this.removeEventListener("error", this.#events.error); + } + const listener = webidl.converters.EventHandlerNonNull(fn); + if (listener !== null) { + this.addEventListener("error", listener); + this.#events.error = fn; + } else { + this.#events.error = null; + } } - }; - exports2.BearerCredentialHandler = BearerCredentialHandler; - var PersonalAccessTokenCredentialHandler = class { - constructor(token) { - this.token = token; + get onclose() { + webidl.brandCheck(this, _WebSocket); + return this.#events.close; } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error("The request has no headers"); + set onclose(fn) { + webidl.brandCheck(this, _WebSocket); + if (this.#events.close) { + this.removeEventListener("close", this.#events.close); + } + const listener = webidl.converters.EventHandlerNonNull(fn); + if (listener !== null) { + this.addEventListener("close", listener); + this.#events.close = fn; + } else { + this.#events.close = null; } - options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; + get onmessage() { + webidl.brandCheck(this, _WebSocket); + return this.#events.message; } - handleAuthentication() { - return __awaiter2(this, void 0, void 0, function* () { - throw new Error("not implemented"); - }); + set onmessage(fn) { + webidl.brandCheck(this, _WebSocket); + if (this.#events.message) { + this.removeEventListener("message", this.#events.message); + } + const listener = webidl.converters.EventHandlerNonNull(fn); + if (listener !== null) { + this.addEventListener("message", listener); + this.#events.message = fn; + } else { + this.#events.message = null; + } } - }; - exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; - } -}); - -// node_modules/@actions/core/lib/oidc-utils.js -var require_oidc_utils = __commonJS({ - "node_modules/@actions/core/lib/oidc-utils.js"(exports2) { - "use strict"; - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + get binaryType() { + webidl.brandCheck(this, _WebSocket); + return this.#binaryType; + } + set binaryType(type) { + webidl.brandCheck(this, _WebSocket); + if (type !== "blob" && type !== "arraybuffer") { + this.#binaryType = "blob"; + } else { + this.#binaryType = type; + } + } + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + */ + #onConnectionEstablished(response, parsedExtensions) { + this.#handler.socket = response.socket; + const webSocketOptions = this.#handler.controller.dispatcher?.webSocketOptions; + const maxFragments = webSocketOptions?.maxFragments; + const maxPayloadSize = webSocketOptions?.maxPayloadSize; + const parser = new ByteParser(this.#handler, parsedExtensions, { + maxFragments, + maxPayloadSize }); + parser.on("drain", () => this.#handler.onParserDrain()); + parser.on("error", (err) => this.#handler.onParserError(err)); + this.#parser = parser; + this.#sendQueue = new SendQueue(response.socket); + this.#handler.readyState = states.OPEN; + const extensions = response.headersList.get("sec-websocket-extensions"); + if (extensions !== null) { + this.#extensions = extensions; + } + const protocol = response.headersList.get("sec-websocket-protocol"); + if (protocol !== null) { + this.#protocol = protocol; + } + fireEvent("open", this); + if (channels.open.hasSubscribers) { + const headers = response.headersList.entries; + channels.open.publish({ + address: getSocketAddress(response.socket), + protocol: this.#protocol, + extensions: this.#extensions, + websocket: this, + handshakeResponse: { + status: response.status, + statusText: response.statusText, + headers + } + }); + } } - return new (P || (P = Promise))(function(resolve14, reject) { - function fulfilled(value) { + #onMessage(type, data) { + if (this.#handler.readyState !== states.OPEN) { + return; + } + let dataForEvent; + if (type === opcodes.TEXT) { try { - step(generator.next(value)); - } catch (e) { - reject(e); + dataForEvent = utf8Decode(data); + } catch { + failWebsocketConnection(this.#handler, 1007, "Received invalid UTF-8 in text frame."); + return; + } + } else if (type === opcodes.BINARY) { + if (this.#binaryType === "blob") { + dataForEvent = new Blob([data]); + } else { + dataForEvent = toArrayBuffer(data); } } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + fireEvent("message", this, createFastMessageEvent, { + origin: this.#url.origin, + data: dataForEvent + }); + } + #onParserDrain() { + this.#handler.socket.resume(); + } + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + */ + #onSocketClose() { + const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED); + let code = 1005; + let reason = ""; + const result = this.#parser?.closingInfo; + if (result && !result.error) { + code = result.code ?? 1005; + reason = result.reason; + } + this.#handler.readyState = states.CLOSED; + if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + code = 1006; + fireEvent("error", this, (type, init2) => new ErrorEvent(type, init2), { + error: new TypeError(reason) + }); + } + fireEvent("close", this, (type, init2) => new CloseEvent(type, init2), { + wasClean, + code, + reason + }); + if (channels.close.hasSubscribers) { + channels.close.publish({ + websocket: this, + code, + reason + }); + } + } + /** + * @param {WebSocket} ws + * @param {Buffer|undefined} buffer + */ + static ping(ws, buffer) { + if (Buffer.isBuffer(buffer)) { + if (buffer.length > 125) { + throw new TypeError("A PING frame cannot have a body larger than 125 bytes."); } + } else if (buffer !== void 0) { + throw new TypeError("Expected buffer payload"); } - function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + const readyState = ws.#handler.readyState; + if (isEstablished(readyState) && !isClosing(readyState) && !isClosed(readyState)) { + const frame = new WebsocketFrameSend(buffer); + ws.#handler.socket.write(frame.createFrame(opcodes.PING)); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + } }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.OidcClient = void 0; - var http_client_1 = require_lib(); - var auth_1 = require_auth(); - var core_1 = require_core(); - var OidcClient = class _OidcClient { - static createHttpClient(allowRetry = true, maxRetry = 10) { - const requestOptions = { - allowRetries: allowRetry, - maxRetries: maxRetry - }; - return new http_client_1.HttpClient("actions/oidc-client", [new auth_1.BearerCredentialHandler(_OidcClient.getRequestToken())], requestOptions); + var { ping } = WebSocket; + Reflect.deleteProperty(WebSocket, "ping"); + WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING; + WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN; + WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING; + 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 } - static getRequestToken() { - const token = process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"]; - if (!token) { - throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable"); - } - return token; + }); + 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) === webidl.util.Types.OBJECT && Symbol.iterator in V) { + return webidl.converters["sequence"](V); } - static getIDTokenUrl() { - const runtimeUrl = process.env["ACTIONS_ID_TOKEN_REQUEST_URL"]; - if (!runtimeUrl) { - throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable"); - } - return runtimeUrl; + return webidl.converters.DOMString(V, prefix, argument); + }; + webidl.converters.WebSocketInit = webidl.dictionaryConverter([ + { + key: "protocols", + converter: webidl.converters["DOMString or sequence"], + defaultValue: () => [] + }, + { + key: "dispatcher", + converter: webidl.converters.any, + defaultValue: () => getGlobalDispatcher() + }, + { + key: "headers", + converter: webidl.nullableConverter(webidl.converters.HeadersInit) } - static getCall(id_token_url) { - return __awaiter2(this, void 0, void 0, function* () { - var _a2; - const httpclient = _OidcClient.createHttpClient(); - const res = yield httpclient.getJson(id_token_url).catch((error3) => { - throw new Error(`Failed to get ID Token. - - Error Code : ${error3.statusCode} - - Error Message: ${error3.message}`); - }); - const id_token = (_a2 = res.result) === null || _a2 === void 0 ? void 0 : _a2.value; - if (!id_token) { - throw new Error("Response json body do not have ID Token field"); - } - return id_token; - }); + ]); + webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { + if (webidl.util.Type(V) === webidl.util.Types.OBJECT && !(Symbol.iterator in V)) { + return webidl.converters.WebSocketInit(V); } - static getIDToken(audience) { - return __awaiter2(this, void 0, void 0, function* () { - try { - let id_token_url = _OidcClient.getIDTokenUrl(); - if (audience) { - const encodedAudience = encodeURIComponent(audience); - id_token_url = `${id_token_url}&audience=${encodedAudience}`; - } - (0, core_1.debug)(`ID token url is ${id_token_url}`); - const id_token = yield _OidcClient.getCall(id_token_url); - (0, core_1.setSecret)(id_token); - return id_token; - } catch (error3) { - throw new Error(`Error message: ${error3.message}`); - } - }); + return { protocols: webidl.converters["DOMString or sequence"](V) }; + }; + webidl.converters.WebSocketSendData = function(V) { + if (webidl.util.Type(V) === webidl.util.Types.OBJECT) { + if (webidl.is.Blob(V)) { + return V; + } + if (webidl.is.BufferSource(V)) { + return V; + } } + return webidl.converters.USVString(V); + }; + module2.exports = { + WebSocket, + ping }; - exports2.OidcClient = OidcClient; } }); -// node_modules/@actions/core/lib/summary.js -var require_summary = __commonJS({ - "node_modules/@actions/core/lib/summary.js"(exports2) { +// node_modules/undici/lib/web/websocket/stream/websocketerror.js +var require_websocketerror = __commonJS({ + "node_modules/undici/lib/web/websocket/stream/websocketerror.js"(exports2, module2) { "use strict"; - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); - }); + var { webidl } = require_webidl(); + var { validateCloseCodeAndReason } = require_util5(); + var { kConstruct } = require_symbols(); + var { kEnumerableProperty } = require_util(); + function createInheritableDOMException() { + class Test extends DOMException { + get reason() { + return ""; + } } - return new (P || (P = Promise))(function(resolve14, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } + if (new Test().reason !== void 0) { + return DOMException; + } + return new Proxy(DOMException, { + construct(target, args, newTarget) { + const instance8 = Reflect.construct(target, args, target); + Object.setPrototypeOf(instance8, newTarget.prototype); + return instance8; } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + }); + } + var WebSocketError = class _WebSocketError extends createInheritableDOMException() { + #closeCode; + #reason; + constructor(message = "", init2 = void 0) { + message = webidl.converters.DOMString(message, "WebSocketError", "message"); + super(message, "WebSocketError"); + if (init2 === kConstruct) { + return; + } else if (init2 !== null) { + init2 = webidl.converters.WebSocketCloseInfo(init2); } - function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + let code = init2.closeCode ?? null; + const reason = init2.reason ?? ""; + validateCloseCodeAndReason(code, reason); + if (reason.length !== 0 && code === null) { + code = 1e3; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.summary = exports2.markdownSummary = exports2.SUMMARY_DOCS_URL = exports2.SUMMARY_ENV_VAR = void 0; - var os_1 = require("os"); - var fs_1 = require("fs"); - var { access, appendFile, writeFile } = fs_1.promises; - exports2.SUMMARY_ENV_VAR = "GITHUB_STEP_SUMMARY"; - exports2.SUMMARY_DOCS_URL = "https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary"; - var Summary = class { - constructor() { - this._buffer = ""; + this.#closeCode = code; + this.#reason = reason; + } + get closeCode() { + return this.#closeCode; + } + get reason() { + return this.#reason; } /** - * Finds the summary file path from the environment, rejects if env var is not found or file does not exist - * Also checks r/w permissions. - * - * @returns step summary file path + * @param {string} message + * @param {number|null} code + * @param {string} reason */ - filePath() { - return __awaiter2(this, void 0, void 0, function* () { - if (this._filePath) { - return this._filePath; + static createUnvalidatedWebSocketError(message, code, reason) { + const error3 = new _WebSocketError(message, kConstruct); + error3.#closeCode = code; + error3.#reason = reason; + return error3; + } + }; + var { createUnvalidatedWebSocketError } = WebSocketError; + delete WebSocketError.createUnvalidatedWebSocketError; + Object.defineProperties(WebSocketError.prototype, { + closeCode: kEnumerableProperty, + reason: kEnumerableProperty, + [Symbol.toStringTag]: { + value: "WebSocketError", + writable: false, + enumerable: false, + configurable: true + } + }); + webidl.is.WebSocketError = webidl.util.MakeTypeAssertion(WebSocketError); + module2.exports = { WebSocketError, createUnvalidatedWebSocketError }; + } +}); + +// node_modules/undici/lib/web/websocket/stream/websocketstream.js +var require_websocketstream = __commonJS({ + "node_modules/undici/lib/web/websocket/stream/websocketstream.js"(exports2, module2) { + "use strict"; + var { createDeferredPromise } = require_promise(); + var { environmentSettingsObject } = require_util2(); + var { states, opcodes, sentCloseFrameState } = require_constants5(); + var { webidl } = require_webidl(); + var { getURLRecord, isValidSubprotocol, isEstablished, utf8Decode } = require_util5(); + var { establishWebSocketConnection, failWebsocketConnection, closeWebSocketConnection } = require_connection(); + var { channels } = require_diagnostics(); + var { WebsocketFrameSend } = require_frame(); + var { ByteParser } = require_receiver(); + var { WebSocketError, createUnvalidatedWebSocketError } = require_websocketerror(); + var { kEnumerableProperty } = require_util(); + var { utf8DecodeBytes } = require_encoding(); + var emittedExperimentalWarning = false; + var WebSocketStream = class { + // Each WebSocketStream object has an associated url , which is a URL record . + /** @type {URL} */ + #url; + // Each WebSocketStream object has an associated opened promise , which is a promise. + /** @type {import('../../../util/promise').DeferredPromise} */ + #openedPromise; + // Each WebSocketStream object has an associated closed promise , which is a promise. + /** @type {import('../../../util/promise').DeferredPromise} */ + #closedPromise; + // Each WebSocketStream object has an associated readable stream , which is a ReadableStream . + /** @type {ReadableStream} */ + #readableStream; + /** @type {ReadableStreamDefaultController} */ + #readableStreamController; + // Retain the controller so the writable stream can be errored while locked. + /** @type {WritableStreamDefaultController} */ + #writableStreamController; + // Each WebSocketStream object has an associated boolean handshake aborted , which is initially false. + #handshakeAborted = false; + /** @type {import('../websocket').Handler} */ + #handler = { + // https://whatpr.org/websockets/48/7b748d3...d5570f3.html#feedback-to-websocket-stream-from-the-protocol + onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions), + onMessage: (opcode, data) => this.#onMessage(opcode, data), + onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message), + onParserDrain: () => this.#handler.socket.resume(), + onSocketData: (chunk) => { + if (!this.#parser.write(chunk)) { + this.#handler.socket.pause(); } - const pathFromEnv = process.env[exports2.SUMMARY_ENV_VAR]; - if (!pathFromEnv) { - throw new Error(`Unable to find environment variable for $${exports2.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + }, + onSocketError: (err) => { + this.#handler.readyState = states.CLOSING; + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(err); } - try { - yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); - } catch (_a2) { - throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + this.#handler.socket.destroy(); + }, + onSocketClose: () => this.#onSocketClose(), + onPing: () => { + }, + onPong: () => { + }, + readyState: states.CONNECTING, + socket: null, + closeState: /* @__PURE__ */ new Set(), + controller: null, + wasEverConnected: false + }; + /** @type {import('../receiver').ByteParser} */ + #parser; + constructor(url2, options = void 0) { + if (!emittedExperimentalWarning) { + process.emitWarning("WebSocketStream is experimental! Expect it to change at any time.", { + code: "UNDICI-WSS" + }); + emittedExperimentalWarning = true; + } + webidl.argumentLengthCheck(arguments, 1, "WebSocket"); + url2 = webidl.converters.USVString(url2); + if (options !== null) { + options = webidl.converters.WebSocketStreamOptions(options); + } + const baseURL = environmentSettingsObject.settingsObject.baseUrl; + const urlRecord = getURLRecord(url2, baseURL); + const protocols = options.protocols; + 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"); + } + this.#url = urlRecord.toString(); + this.#openedPromise = createDeferredPromise(); + this.#closedPromise = createDeferredPromise(); + if (options.signal != null) { + const signal = options.signal; + if (signal.aborted) { + this.#openedPromise.reject(signal.reason); + this.#closedPromise.reject(signal.reason); + return; } - this._filePath = pathFromEnv; - return this._filePath; - }); - } - /** - * Wraps content in an HTML tag, adding any HTML attributes - * - * @param {string} tag HTML tag to wrap - * @param {string | null} content content within the tag - * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add - * - * @returns {string} content wrapped in HTML element - */ - wrap(tag, content, attrs = {}) { - const htmlAttrs = Object.entries(attrs).map(([key, value]) => ` ${key}="${value}"`).join(""); - if (!content) { - return `<${tag}${htmlAttrs}>`; + signal.addEventListener("abort", () => { + if (!isEstablished(this.#handler.readyState)) { + failWebsocketConnection(this.#handler); + this.#handler.readyState = states.CLOSING; + this.#openedPromise.reject(signal.reason); + this.#closedPromise.reject(signal.reason); + this.#handshakeAborted = true; + } + }, { once: true }); } - return `<${tag}${htmlAttrs}>${content}`; + const client = environmentSettingsObject.settingsObject; + this.#handler.controller = establishWebSocketConnection( + urlRecord, + protocols, + client, + this.#handler, + options + ); } - /** - * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. - * - * @param {SummaryWriteOptions} [options] (optional) options for write operation - * - * @returns {Promise} summary instance - */ - write(options) { - return __awaiter2(this, void 0, void 0, function* () { - const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); - const filePath = yield this.filePath(); - const writeFunc = overwrite ? writeFile : appendFile; - yield writeFunc(filePath, this._buffer, { encoding: "utf8" }); - return this.emptyBuffer(); - }); + // The url getter steps are to return this 's url , serialized . + get url() { + return this.#url.toString(); } - /** - * Clears the summary buffer and wipes the summary file - * - * @returns {Summary} summary instance - */ - clear() { - return __awaiter2(this, void 0, void 0, function* () { - return this.emptyBuffer().write({ overwrite: true }); - }); + // The opened getter steps are to return this 's opened promise . + get opened() { + return this.#openedPromise.promise; } - /** - * Returns the current summary buffer as a string - * - * @returns {string} string of summary buffer - */ - stringify() { - return this._buffer; + // The closed getter steps are to return this 's closed promise . + get closed() { + return this.#closedPromise.promise; } - /** - * If the summary buffer is empty - * - * @returns {boolen} true if the buffer is empty - */ - isEmptyBuffer() { - return this._buffer.length === 0; + // The close( closeInfo ) method steps are: + close(closeInfo = void 0) { + if (closeInfo !== null) { + closeInfo = webidl.converters.WebSocketCloseInfo(closeInfo); + } + const code = closeInfo.closeCode ?? null; + const reason = closeInfo.reason; + closeWebSocketConnection(this.#handler, code, reason, true); + } + #write(chunk) { + chunk = webidl.converters.WebSocketStreamWrite(chunk); + const promise = createDeferredPromise(); + let data = null; + let opcode = null; + if (webidl.is.BufferSource(chunk)) { + data = new Uint8Array(ArrayBuffer.isView(chunk) ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength) : chunk.slice()); + opcode = opcodes.BINARY; + } else { + let string2; + try { + string2 = webidl.converters.DOMString(chunk); + } catch (e) { + promise.reject(e); + return promise.promise; + } + data = new TextEncoder().encode(string2); + opcode = opcodes.TEXT; + } + if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + const frame = new WebsocketFrameSend(data); + this.#handler.socket.write(frame.createFrame(opcode), () => { + promise.resolve(void 0); + }); + } + return promise.promise; + } + /** @type {import('../websocket').Handler['onConnectionEstablished']} */ + #onConnectionEstablished(response, parsedExtensions) { + this.#handler.socket = response.socket; + const maxFragments = this.#handler.controller.dispatcher?.webSocketOptions?.maxFragments; + const maxPayloadSize = this.#handler.controller.dispatcher?.webSocketOptions?.maxPayloadSize; + const parser = new ByteParser(this.#handler, parsedExtensions, { + maxFragments, + maxPayloadSize + }); + parser.on("drain", () => this.#handler.onParserDrain()); + parser.on("error", (err) => this.#handler.onParserError(err)); + this.#parser = parser; + this.#handler.readyState = states.OPEN; + const extensions = parsedExtensions ?? ""; + const protocol = response.headersList.get("sec-websocket-protocol") ?? ""; + const readable = new ReadableStream({ + start: (controller) => { + this.#readableStreamController = controller; + }, + cancel: (reason) => this.#cancel(reason) + }); + const writable = new WritableStream({ + start: (controller) => { + this.#writableStreamController = controller; + }, + write: (chunk) => this.#write(chunk), + close: () => closeWebSocketConnection(this.#handler, null, null), + abort: (reason) => this.#closeUsingReason(reason) + }); + this.#readableStream = readable; + this.#openedPromise.resolve({ + extensions, + protocol, + readable, + writable + }); + } + /** @type {import('../websocket').Handler['onMessage']} */ + #onMessage(type, data) { + if (this.#handler.readyState !== states.OPEN) { + return; + } + let chunk; + if (type === opcodes.TEXT) { + try { + chunk = utf8Decode(data); + } catch { + failWebsocketConnection(this.#handler, 1007, "Received invalid UTF-8 in text frame."); + return; + } + } else if (type === opcodes.BINARY) { + chunk = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); + } + this.#readableStreamController.enqueue(chunk); + } + /** @type {import('../websocket').Handler['onSocketClose']} */ + #onSocketClose() { + const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED); + this.#handler.readyState = states.CLOSED; + if (this.#handshakeAborted) { + return; + } + if (!this.#handler.wasEverConnected) { + this.#openedPromise.reject(new WebSocketError("Socket never opened")); + } + const result = this.#parser?.closingInfo; + let code = result?.code ?? 1005; + if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + code = 1006; + } + const reason = result?.reason == null ? "" : utf8DecodeBytes(Buffer.from(result.reason)); + if (wasClean) { + this.#readableStreamController.close(); + this.#writableStreamController.error(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError")); + this.#closedPromise.resolve({ + closeCode: code, + reason + }); + } else { + const error3 = createUnvalidatedWebSocketError("unclean close", code, reason); + this.#readableStreamController?.error(error3); + this.#writableStreamController?.error(error3); + this.#closedPromise.reject(error3); + } + } + #closeUsingReason(reason) { + let code = null; + let reasonString = ""; + if (webidl.is.WebSocketError(reason)) { + code = reason.closeCode; + reasonString = reason.reason; + } + closeWebSocketConnection(this.#handler, code, reasonString); + } + // To cancel a WebSocketStream stream given reason , close using reason giving stream and reason . + #cancel(reason) { + this.#closeUsingReason(reason); + } + }; + Object.defineProperties(WebSocketStream.prototype, { + url: kEnumerableProperty, + opened: kEnumerableProperty, + closed: kEnumerableProperty, + close: kEnumerableProperty, + [Symbol.toStringTag]: { + value: "WebSocketStream", + writable: false, + enumerable: false, + configurable: true + } + }); + webidl.converters.WebSocketStreamOptions = webidl.dictionaryConverter([ + { + key: "protocols", + converter: webidl.sequenceConverter(webidl.converters.USVString), + defaultValue: () => [] + }, + { + key: "signal", + converter: webidl.nullableConverter(webidl.converters.AbortSignal), + defaultValue: () => null + } + ]); + webidl.converters.WebSocketCloseInfo = webidl.dictionaryConverter([ + { + key: "closeCode", + converter: (V) => webidl.converters["unsigned short"](V, webidl.attributes.EnforceRange) + }, + { + key: "reason", + converter: webidl.converters.USVString, + defaultValue: () => "" + } + ]); + webidl.converters.WebSocketStreamWrite = function(V) { + if (typeof V === "string") { + return webidl.converters.USVString(V); + } + return webidl.converters.BufferSource(V); + }; + module2.exports = { WebSocketStream }; + } +}); + +// node_modules/undici/lib/web/eventsource/util.js +var require_util6 = __commonJS({ + "node_modules/undici/lib/web/eventsource/util.js"(exports2, module2) { + "use strict"; + function isValidLastEventId(value) { + return value.indexOf("\0") === -1; + } + function isASCIINumber(value) { + if (value.length === 0) return false; + for (let i = 0; i < value.length; i++) { + if (value.charCodeAt(i) < 48 || value.charCodeAt(i) > 57) return false; + } + return true; + } + module2.exports = { + isValidLastEventId, + isASCIINumber + }; + } +}); + +// node_modules/undici/lib/web/eventsource/eventsource-stream.js +var require_eventsource_stream = __commonJS({ + "node_modules/undici/lib/web/eventsource/eventsource-stream.js"(exports2, module2) { + "use strict"; + var buffer = require("node:buffer"); + var { Transform: Transform5 } = require("node:stream"); + var { isASCIINumber, isValidLastEventId } = require_util6(); + var BOM = [239, 187, 191]; + var LF = 10; + var CR = 13; + var COLON = 58; + var SPACE = 32; + var defaultMaxEventSize = buffer.kStringMaxLength; + var DATA = Buffer.from("data"); + var EVENT = Buffer.from("event"); + var ID2 = Buffer.from("id"); + var RETRY = Buffer.from("retry"); + var minParserItems = 1024; + var maxParserItems = 131072; + var bytesPerParserItem = 128; + function isASCIINumberBytes(buffer2, start) { + if (start >= buffer2.length) { + return false; + } + for (let i = start; i < buffer2.length; i++) { + if (buffer2[i] < 48 || buffer2[i] > 57) { + return false; + } + } + return true; + } + function isValidLastEventIdBytes(buffer2, start) { + for (let i = start; i < buffer2.length; i++) { + if (buffer2[i] === 0) { + return false; + } + } + return true; + } + function isFieldName(line, length, field) { + if (length !== field.length) { + return false; + } + for (let i = 0; i < length; i++) { + if (line[i] !== field[i]) { + return false; + } } + return true; + } + function createMaxEventSizeExceededError() { + const error3 = new Error("EventSource message size exceeded"); + error3.aborted = false; + return error3; + } + var EventSourceStream = class extends Transform5 { /** - * Resets the summary buffer without writing to summary file - * - * @returns {Summary} summary instance + * @type {eventSourceSettings} */ - emptyBuffer() { - this._buffer = ""; - return this; - } + state; /** - * Adds raw text to the summary buffer - * - * @param {string} text content to add - * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) - * - * @returns {Summary} summary instance + * Leading byte-order-mark check. + * @type {boolean} */ - addRaw(text, addEOL = false) { - this._buffer += text; - return addEOL ? this.addEOL() : this; - } + checkBOM = true; /** - * Adds the operating system-specific end-of-line marker to the buffer - * - * @returns {Summary} summary instance + * @type {boolean} */ - addEOL() { - return this.addRaw(os_1.EOL); + crlfCheck = false; + /** + * @type {boolean} + */ + eventEndCheck = false; + /** + * @type {Buffer[]} + */ + chunks = []; + chunkIndex = 0; + pos = 0; + lineChunkIndex = 0; + linePos = 0; + lineLength = 0; + eventSize = 0; + eventFieldSizes = { data: 0, event: 0, id: 0, retry: 0 }; + dataLineCount = 0; + maxEventSize; + maxDataLines; + maxBufferedChunks; + event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; + /** + * @param {object} options + * @param {boolean} [options.readableObjectMode] + * @param {number} [options.maxEventSize] + * @param {eventSourceSettings} [options.eventSourceSettings] + * @param {(chunk: any, encoding?: BufferEncoding | undefined) => boolean} [options.push] + */ + constructor(options = {}) { + options.readableObjectMode = true; + super(options); + this.state = options.eventSourceSettings || {}; + this.maxEventSize = options.maxEventSize ?? defaultMaxEventSize; + const parserItemLimit = this.maxEventSize > 0 ? Math.min(maxParserItems, Math.max(minParserItems, Math.floor(this.maxEventSize / bytesPerParserItem))) : 0; + this.maxDataLines = parserItemLimit; + this.maxBufferedChunks = parserItemLimit; + if (options.push) { + this.push = options.push; + } } /** - * Adds an HTML codeblock to the summary buffer - * - * @param {string} code content to render within fenced code block - * @param {string} lang (optional) language to syntax highlight code - * - * @returns {Summary} summary instance + * @param {Buffer} chunk + * @param {string} _encoding + * @param {Function} callback + * @returns {void} */ - addCodeBlock(code, lang) { - const attrs = Object.assign({}, lang && { lang }); - const element = this.wrap("pre", this.wrap("code", code), attrs); - return this.addRaw(element).addEOL(); + _transform(chunk, _encoding, callback) { + if (chunk.length === 0) { + callback(); + return; + } + if (this.maxEventSize > 0 && this.chunks.length >= this.maxBufferedChunks && chunk[0] !== LF && chunk[0] !== CR) { + callback(createMaxEventSizeExceededError()); + return; + } + this.chunks.push(chunk); + if (this.checkBOM) { + if (this.handleBOM()) { + callback(); + return; + } + } + while (this.hasCurrentByte()) { + const byte = this.currentByte(); + if (this.eventEndCheck) { + if (this.crlfCheck) { + if (byte === LF) { + this.crlfCheck = false; + this.consumeCurrentByte(); + continue; + } + this.crlfCheck = false; + } + if (byte === LF || byte === CR) { + if (byte === CR) { + this.crlfCheck = true; + } + this.consumeCurrentByte(); + if (this.hasPendingEvent()) { + this.processEvent(this.event); + } + this.clearEvent(); + continue; + } + this.eventEndCheck = false; + continue; + } + if (byte === LF || byte === CR) { + if (byte === CR) { + this.crlfCheck = true; + } + try { + this.parseLine(this.readLine(), this.event); + } catch (error3) { + callback(error3); + return; + } + this.consumeCurrentByte(); + this.eventEndCheck = true; + continue; + } + if (this.maxEventSize > 0 && ++this.lineLength > this.maxEventSize + 7) { + callback(createMaxEventSizeExceededError()); + return; + } + this.advanceCursor(); + } + callback(); + } + _destroy(error3, callback) { + this.chunks.length = 0; + this.clearEvent(); + super._destroy(error3, callback); } /** - * Adds an HTML list to the summary buffer - * - * @param {string[]} items list of items to render - * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) - * - * @returns {Summary} summary instance + * @param {Buffer} line + * @param {EventSourceStreamEvent} event */ - addList(items, ordered = false) { - const tag = ordered ? "ol" : "ul"; - const listItems = items.map((item) => this.wrap("li", item)).join(""); - const element = this.wrap(tag, listItems); - return this.addRaw(element).addEOL(); + parseLine(line, event) { + if (line.length === 0) { + return; + } + const colonPosition = line.indexOf(COLON); + if (colonPosition === 0) { + return; + } + let fieldLength = line.length; + let valueStart = line.length; + if (colonPosition !== -1) { + fieldLength = colonPosition; + valueStart = colonPosition + 1; + if (line[valueStart] === SPACE) { + ++valueStart; + } + } + if (isFieldName(line, fieldLength, DATA)) { + if (this.maxEventSize > 0 && this.dataLineCount >= this.maxDataLines) { + throw createMaxEventSizeExceededError(); + } + const valueBytes = line.length - valueStart; + const dataSize = this.eventFieldSizes.data + (event.data === void 0 ? 0 : 1) + valueBytes; + this.setEventFieldSize("data", dataSize); + const value = line.toString("utf8", valueStart); + if (event.data === void 0) { + event.data = value; + } else { + event.data += ` +${value}`; + } + this.dataLineCount++; + return; + } + if (isFieldName(line, fieldLength, RETRY)) { + if (isASCIINumberBytes(line, valueStart)) { + this.setEventFieldSize("retry", line.length - valueStart); + event.retry = line.toString("utf8", valueStart); + } + return; + } + if (isFieldName(line, fieldLength, ID2)) { + if (isValidLastEventIdBytes(line, valueStart)) { + this.setEventFieldSize("id", line.length - valueStart); + event.id = line.toString("utf8", valueStart); + } + return; + } + if (isFieldName(line, fieldLength, EVENT)) { + if (valueStart < line.length) { + this.setEventFieldSize("event", line.length - valueStart); + event.event = line.toString("utf8", valueStart); + } + } + } + setEventFieldSize(field, size) { + const eventSize = this.eventSize - this.eventFieldSizes[field] + size; + if (this.maxEventSize > 0 && eventSize > this.maxEventSize) { + throw createMaxEventSizeExceededError(); + } + this.eventSize = eventSize; + this.eventFieldSizes[field] = size; } /** - * Adds an HTML table to the summary buffer - * - * @param {SummaryTableCell[]} rows table rows - * - * @returns {Summary} summary instance + * @param {EventSourceStreamEvent} event */ - addTable(rows) { - const tableBody = rows.map((row) => { - const cells = row.map((cell) => { - if (typeof cell === "string") { - return this.wrap("td", cell); + processEvent(event) { + if (event.retry && isASCIINumber(event.retry)) { + this.state.reconnectionTime = parseInt(event.retry, 10); + } + if (event.id !== void 0 && isValidLastEventId(event.id)) { + this.state.lastEventId = event.id; + } + if (event.data !== void 0) { + this.push({ + type: event.event || "message", + options: { + data: event.data, + lastEventId: this.state.lastEventId, + origin: this.state.origin } - const { header, data, colspan, rowspan } = cell; - const tag = header ? "th" : "td"; - const attrs = Object.assign(Object.assign({}, colspan && { colspan }), rowspan && { rowspan }); - return this.wrap(tag, data, attrs); - }).join(""); - return this.wrap("tr", cells); - }).join(""); - const element = this.wrap("table", tableBody); - return this.addRaw(element).addEOL(); + }); + } + } + clearEvent() { + this.event.data = void 0; + this.event.event = void 0; + this.event.id = void 0; + this.event.retry = void 0; + this.eventSize = 0; + this.dataLineCount = 0; + this.eventFieldSizes.data = 0; + this.eventFieldSizes.event = 0; + this.eventFieldSizes.id = 0; + this.eventFieldSizes.retry = 0; + } + hasPendingEvent() { + return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; + } + hasCurrentByte() { + return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; + } + currentByte() { + return this.chunks[this.chunkIndex][this.pos]; + } + consumeCurrentByte() { + this.advanceCursor(); + this.syncLineStartToCursor(); + } + advanceCursor() { + this.pos++; + while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { + this.chunkIndex++; + this.pos = 0; + } + } + syncLineStartToCursor() { + this.lineChunkIndex = this.chunkIndex; + this.linePos = this.pos; + this.lineLength = 0; + this.dropConsumedChunks(); + } + dropConsumedChunks() { + if (this.lineChunkIndex > 0) { + const consumed = this.lineChunkIndex; + this.chunks.splice(0, consumed); + this.lineChunkIndex = 0; + this.chunkIndex -= consumed; + } + if (this.chunkIndex === this.chunks.length) { + this.chunks.length = 0; + this.chunkIndex = 0; + this.pos = 0; + this.lineChunkIndex = 0; + this.linePos = 0; + } + } + readLine() { + if (this.lineChunkIndex === this.chunkIndex) { + return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); + } + const chunks = []; + let length = 0; + for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { + const chunk = this.chunks[i]; + const start = i === this.lineChunkIndex ? this.linePos : 0; + const end = i === this.chunkIndex ? this.pos : chunk.length; + const slice = chunk.subarray(start, end); + length += slice.length; + chunks.push(slice); + } + return Buffer.concat(chunks, length); + } + peekBufferedByte(offset) { + let chunkIndex = this.lineChunkIndex; + let pos = this.linePos; + while (chunkIndex < this.chunks.length) { + const chunk = this.chunks[chunkIndex]; + const remaining = chunk.length - pos; + if (offset < remaining) { + return chunk[pos + offset]; + } + offset -= remaining; + chunkIndex++; + pos = 0; + } + } + discardLeadingBytes(count) { + while (count > 0 && this.lineChunkIndex < this.chunks.length) { + const chunk = this.chunks[this.lineChunkIndex]; + const remaining = chunk.length - this.linePos; + if (count < remaining) { + this.linePos += count; + count = 0; + } else { + count -= remaining; + this.lineChunkIndex++; + this.linePos = 0; + } + } + this.chunkIndex = this.lineChunkIndex; + this.pos = this.linePos; + this.dropConsumedChunks(); + } + handleBOM() { + const first = this.peekBufferedByte(0); + const second = this.peekBufferedByte(1); + const third = this.peekBufferedByte(2); + if (second === void 0) { + if (first === BOM[0]) { + return true; + } + this.checkBOM = false; + return true; + } + if (third === void 0) { + if (first === BOM[0] && second === BOM[1]) { + return true; + } + this.checkBOM = false; + return false; + } + if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { + this.discardLeadingBytes(3); + } + this.checkBOM = false; + return !this.hasCurrentByte(); } + }; + module2.exports = { + EventSourceStream + }; + } +}); + +// node_modules/undici/lib/web/eventsource/eventsource.js +var require_eventsource = __commonJS({ + "node_modules/undici/lib/web/eventsource/eventsource.js"(exports2, module2) { + "use strict"; + var { pipeline: pipeline2 } = require("node:stream"); + var { fetching } = require_fetch(); + var { makeRequest } = require_request2(); + var { webidl } = require_webidl(); + var { EventSourceStream } = require_eventsource_stream(); + var { parseMIMEType } = require_data_url(); + var { createFastMessageEvent } = require_events(); + var { isNetworkError } = require_response(); + var { kEnumerableProperty } = require_util(); + var { environmentSettingsObject } = require_util2(); + var { getGlobalDispatcher } = require_global2(); + var experimentalWarned = false; + var defaultReconnectionTime = 3e3; + var CONNECTING = 0; + var OPEN = 1; + var CLOSED = 2; + var ANONYMOUS = "anonymous"; + var USE_CREDENTIALS = "use-credentials"; + var EventSource = class _EventSource extends EventTarget { + #events = { + open: null, + error: null, + message: null + }; + #url; + #withCredentials = false; /** - * Adds a collapsable HTML details element to the summary buffer - * - * @param {string} label text for the closed state - * @param {string} content collapsable content - * - * @returns {Summary} summary instance + * @type {ReadyState} */ - addDetails(label, content) { - const element = this.wrap("details", this.wrap("summary", label) + content); - return this.addRaw(element).addEOL(); - } + #readyState = CONNECTING; + #request = null; + #controller = null; + #dispatcher; /** - * Adds an HTML image tag to the summary buffer - * - * @param {string} src path to the image you to embed - * @param {string} alt text description of the image - * @param {SummaryImageOptions} options (optional) addition image attributes - * - * @returns {Summary} summary instance + * @type {import('./eventsource-stream').eventSourceSettings} */ - addImage(src, alt, options) { - const { width, height } = options || {}; - const attrs = Object.assign(Object.assign({}, width && { width }), height && { height }); - const element = this.wrap("img", null, Object.assign({ src, alt }, attrs)); - return this.addRaw(element).addEOL(); + #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(url2, eventSourceInitDict = {}) { + 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" + }); + } + url2 = webidl.converters.USVString(url2); + eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, "eventSourceInitDict"); + this.#dispatcher = eventSourceInitDict.node.dispatcher || eventSourceInitDict.dispatcher; + this.#state = { + lastEventId: "", + reconnectionTime: eventSourceInitDict.node.reconnectionTime + }; + const settings = environmentSettingsObject; + let urlRecord; + try { + urlRecord = new URL(url2, settings.settingsObject.baseUrl); + this.#state.origin = urlRecord.origin; + } catch (e) { + throw new DOMException(e, "SyntaxError"); + } + this.#url = urlRecord.href; + let corsAttributeState = ANONYMOUS; + if (eventSourceInitDict.withCredentials === true) { + corsAttributeState = USE_CREDENTIALS; + this.#withCredentials = true; + } + 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" + }; + initRequest.client = environmentSettingsObject.settingsObject; + initRequest.headersList = [["accept", { name: "accept", value: "text/event-stream" }]]; + initRequest.cache = "no-store"; + initRequest.initiator = "other"; + initRequest.urlList = [new URL(this.#url)]; + this.#request = makeRequest(initRequest); + this.#connect(); } /** - * Adds an HTML section heading element - * - * @param {string} text heading text - * @param {number | string} [level=1] (optional) the heading level, default: 1 - * - * @returns {Summary} summary instance + * Returns the state of this EventSource object's connection. It can have the + * values described below. + * @returns {ReadyState} + * @readonly */ - addHeading(text, level) { - const tag = `h${level}`; - const allowedTag = ["h1", "h2", "h3", "h4", "h5", "h6"].includes(tag) ? tag : "h1"; - const element = this.wrap(allowedTag, text); - return this.addRaw(element).addEOL(); + get readyState() { + return this.#readyState; } /** - * Adds an HTML thematic break (
) to the summary buffer - * - * @returns {Summary} summary instance + * Returns the URL providing the event stream. + * @readonly + * @returns {string} */ - addSeparator() { - const element = this.wrap("hr", null); - return this.addRaw(element).addEOL(); + get url() { + return this.#url; } /** - * Adds an HTML line break (
) to the summary buffer - * - * @returns {Summary} summary instance + * Returns a boolean indicating whether the EventSource object was + * instantiated with CORS credentials set (true), or not (false, the default). */ - addBreak() { - const element = this.wrap("br", null); - return this.addRaw(element).addEOL(); + get withCredentials() { + return this.#withCredentials; + } + #connect() { + if (this.#readyState === CLOSED) return; + this.#readyState = CONNECTING; + const fetchParams = { + request: this.#request, + dispatcher: this.#dispatcher + }; + const processEventSourceEndOfBody = (response) => { + if (!isNetworkError(response)) { + return this.#reconnect(); + } + }; + fetchParams.processResponseEndOfBody = processEventSourceEndOfBody; + fetchParams.processResponse = (response) => { + if (isNetworkError(response)) { + if (response.aborted) { + this.close(); + this.dispatchEvent(new Event("error")); + return; + } else { + this.#reconnect(); + return; + } + } + 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; + } + this.#readyState = OPEN; + this.dispatchEvent(new Event("open")); + this.#state.origin = response.urlList[response.urlList.length - 1].origin; + const eventSourceStream = new EventSourceStream({ + eventSourceSettings: this.#state, + maxEventSize: this.#dispatcher.eventSourceOptions?.maxEventSize, + push: (event) => { + this.dispatchEvent(createFastMessageEvent( + event.type, + event.options + )); + } + }); + pipeline2( + response.body.stream, + eventSourceStream, + (error3) => { + if (error3?.aborted === false) { + this.close(); + this.dispatchEvent(new Event("error")); + } + } + ); + }; + this.#controller = fetching(fetchParams); } /** - * Adds an HTML blockquote to the summary buffer - * - * @param {string} text quote text - * @param {string} cite (optional) citation url - * - * @returns {Summary} summary instance + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model + * @returns {void} */ - addQuote(text, cite) { - const attrs = Object.assign({}, cite && { cite }); - const element = this.wrap("blockquote", text, attrs); - return this.addRaw(element).addEOL(); + #reconnect() { + if (this.#readyState === CLOSED) return; + this.#readyState = CONNECTING; + this.dispatchEvent(new Event("error")); + setTimeout(() => { + if (this.#readyState !== CONNECTING) return; + if (this.#state.lastEventId.length) { + this.#request.headersList.set("last-event-id", this.#state.lastEventId, true); + } + this.#connect(); + }, this.#state.reconnectionTime)?.unref(); } /** - * Adds an HTML anchor tag to the summary buffer - * - * @param {string} text link text/content - * @param {string} href hyperlink - * - * @returns {Summary} summary instance + * Closes the connection, if any, and sets the readyState attribute to + * CLOSED. */ - addLink(text, href) { - const element = this.wrap("a", text, { href }); - return this.addRaw(element).addEOL(); + close() { + webidl.brandCheck(this, _EventSource); + if (this.#readyState === CLOSED) return; + this.#readyState = CLOSED; + this.#controller.abort(); + this.#request = null; } - }; - var _summary = new Summary(); - exports2.markdownSummary = _summary; - exports2.summary = _summary; - } -}); - -// node_modules/@actions/core/lib/path-utils.js -var require_path_utils = __commonJS({ - "node_modules/@actions/core/lib/path-utils.js"(exports2) { - "use strict"; - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) 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]; - } }; + get onopen() { + return this.#events.open; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys2 = function(o) { - ownKeys2 = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys2(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]); + set onopen(fn) { + if (this.#events.open) { + this.removeEventListener("open", this.#events.open); } - __setModuleDefault2(result, mod); - return result; - }; - })(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.toPosixPath = toPosixPath; - exports2.toWin32Path = toWin32Path; - exports2.toPlatformPath = toPlatformPath; - var path30 = __importStar2(require("path")); - function toPosixPath(pth) { - return pth.replace(/[\\]/g, "/"); - } - function toWin32Path(pth) { - return pth.replace(/[/]/g, "\\"); - } - function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path30.sep); - } - } -}); - -// node_modules/@actions/io/lib/io-util.js -var require_io_util = __commonJS({ - "node_modules/@actions/io/lib/io-util.js"(exports2) { - "use strict"; - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) 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 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys2 = function(o) { - ownKeys2 = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys2(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]); + const listener = webidl.converters.EventHandlerNonNull(fn); + if (listener !== null) { + this.addEventListener("open", listener); + this.#events.open = fn; + } else { + this.#events.open = null; } - __setModuleDefault2(result, mod); - return result; - }; - })(); - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); - }); } - return new (P || (P = Promise))(function(resolve14, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + get onmessage() { + return this.#events.message; + } + set onmessage(fn) { + if (this.#events.message) { + this.removeEventListener("message", this.#events.message); } - function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + const listener = webidl.converters.EventHandlerNonNull(fn); + if (listener !== null) { + this.addEventListener("message", listener); + this.#events.message = fn; + } else { + this.#events.message = null; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var _a2; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.READONLY = exports2.UV_FS_O_EXLOCK = exports2.IS_WINDOWS = exports2.unlink = exports2.symlink = exports2.stat = exports2.rmdir = exports2.rm = exports2.rename = exports2.readdir = exports2.open = exports2.mkdir = exports2.lstat = exports2.copyFile = exports2.chmod = void 0; - exports2.readlink = readlink; - exports2.exists = exists; - exports2.isDirectory = isDirectory; - exports2.isRooted = isRooted; - exports2.tryGetExecutablePath = tryGetExecutablePath; - exports2.getCmdPath = getCmdPath; - var fs32 = __importStar2(require("fs")); - var path30 = __importStar2(require("path")); - _a2 = fs32.promises, exports2.chmod = _a2.chmod, exports2.copyFile = _a2.copyFile, exports2.lstat = _a2.lstat, exports2.mkdir = _a2.mkdir, exports2.open = _a2.open, exports2.readdir = _a2.readdir, exports2.rename = _a2.rename, exports2.rm = _a2.rm, exports2.rmdir = _a2.rmdir, exports2.stat = _a2.stat, exports2.symlink = _a2.symlink, exports2.unlink = _a2.unlink; - exports2.IS_WINDOWS = process.platform === "win32"; - function readlink(fsPath) { - return __awaiter2(this, void 0, void 0, function* () { - const result = yield fs32.promises.readlink(fsPath); - if (exports2.IS_WINDOWS && !result.endsWith("\\")) { - return `${result}\\`; + } + get onerror() { + return this.#events.error; + } + set onerror(fn) { + if (this.#events.error) { + this.removeEventListener("error", this.#events.error); } - return result; - }); - } - exports2.UV_FS_O_EXLOCK = 268435456; - exports2.READONLY = fs32.constants.O_RDONLY; - function exists(fsPath) { - return __awaiter2(this, void 0, void 0, function* () { - try { - yield (0, exports2.stat)(fsPath); - } catch (err) { - if (err.code === "ENOENT") { - return false; - } - throw err; + const listener = webidl.converters.EventHandlerNonNull(fn); + if (listener !== null) { + this.addEventListener("error", listener); + this.#events.error = fn; + } else { + this.#events.error = null; } - return true; - }); - } - function isDirectory(fsPath_1) { - return __awaiter2(this, arguments, void 0, function* (fsPath, useStat = false) { - const stats = useStat ? yield (0, exports2.stat)(fsPath) : yield (0, exports2.lstat)(fsPath); - return stats.isDirectory(); - }); - } - function isRooted(p) { - p = normalizeSeparators(p); - if (!p) { - throw new Error('isRooted() parameter "p" cannot be empty'); } - if (exports2.IS_WINDOWS) { - return p.startsWith("\\") || /^[A-Z]:/i.test(p); + }; + var 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 } - return p.startsWith("/"); - } - function tryGetExecutablePath(filePath, extensions) { - return __awaiter2(this, void 0, void 0, function* () { - let stats = void 0; - try { - stats = yield (0, exports2.stat)(filePath); - } catch (err) { - if (err.code !== "ENOENT") { - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + }; + 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, + defaultValue: () => getGlobalDispatcher() + }, + { + key: "node", + // undici only + converter: webidl.dictionaryConverter([ + { + key: "reconnectionTime", + converter: webidl.converters["unsigned long"], + defaultValue: () => defaultReconnectionTime + }, + { + key: "dispatcher", + converter: webidl.converters.any } + ]), + defaultValue: () => ({}) + } + ]); + module2.exports = { + EventSource, + defaultReconnectionTime + }; + } +}); + +// node_modules/undici/index.js +var require_undici = __commonJS({ + "node_modules/undici/index.js"(exports2, module2) { + "use strict"; + var Client = require_client(); + var Dispatcher = require_dispatcher(); + var Pool = require_pool(); + var BalancedPool = require_balanced_pool(); + var RoundRobinPool = require_round_robin_pool(); + var Agent = require_agent(); + var ProxyAgent2 = require_proxy_agent(); + var Socks5ProxyAgent = require_socks5_proxy_agent(); + var EnvHttpProxyAgent = require_env_http_proxy_agent(); + var RetryAgent = require_retry_agent(); + var H2CClient = require_h2c_client(); + var errors = require_errors(); + var util4 = require_util(); + var { InvalidArgumentError } = errors; + var api = require_api(); + var buildConnector = require_connect(); + var MockClient = require_mock_client(); + var { MockCallHistory, MockCallHistoryLog } = require_mock_call_history(); + var MockAgent = require_mock_agent(); + var MockPool = require_mock_pool(); + var SnapshotAgent = require_snapshot_agent(); + var mockErrors = require_mock_errors(); + var RetryHandler = require_retry_handler(); + var { getGlobalDispatcher, setGlobalDispatcher } = require_global2(); + var DecoratorHandler = require_decorator_handler(); + var RedirectHandler = require_redirect_handler(); + Object.assign(Dispatcher.prototype, api); + module2.exports.Dispatcher = Dispatcher; + module2.exports.Client = Client; + module2.exports.Pool = Pool; + module2.exports.BalancedPool = BalancedPool; + module2.exports.RoundRobinPool = RoundRobinPool; + module2.exports.Agent = Agent; + module2.exports.ProxyAgent = ProxyAgent2; + module2.exports.Socks5ProxyAgent = Socks5ProxyAgent; + module2.exports.EnvHttpProxyAgent = EnvHttpProxyAgent; + module2.exports.RetryAgent = RetryAgent; + module2.exports.H2CClient = H2CClient; + module2.exports.RetryHandler = RetryHandler; + module2.exports.DecoratorHandler = DecoratorHandler; + module2.exports.RedirectHandler = RedirectHandler; + module2.exports.interceptors = { + redirect: require_redirect(), + responseError: require_response_error(), + retry: require_retry(), + dump: require_dump(), + dns: require_dns(), + cache: require_cache2(), + decompress: require_decompress(), + deduplicate: require_deduplicate() + }; + module2.exports.cacheStores = { + MemoryCacheStore: require_memory_cache_store() + }; + var SqliteCacheStore = require_sqlite_cache_store(); + module2.exports.cacheStores.SqliteCacheStore = SqliteCacheStore; + module2.exports.buildConnector = buildConnector; + module2.exports.errors = errors; + module2.exports.util = { + parseHeaders: util4.parseHeaders, + headerNameToString: util4.headerNameToString + }; + function makeDispatcher(fn) { + return (url2, opts, handler2) => { + if (typeof opts === "function") { + handler2 = opts; + opts = null; } - if (stats && stats.isFile()) { - if (exports2.IS_WINDOWS) { - const upperExt = path30.extname(filePath).toUpperCase(); - if (extensions.some((validExt) => validExt.toUpperCase() === upperExt)) { - return filePath; - } - } else { - if (isUnixExecutable(stats)) { - return filePath; - } - } + if (!url2 || typeof url2 !== "string" && typeof url2 !== "object" && !(url2 instanceof URL)) { + throw new InvalidArgumentError("invalid url"); } - const originalFilePath = filePath; - for (const extension of extensions) { - filePath = originalFilePath + extension; - stats = void 0; - try { - stats = yield (0, exports2.stat)(filePath); - } catch (err) { - if (err.code !== "ENOENT") { - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } + 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"); } - if (stats && stats.isFile()) { - if (exports2.IS_WINDOWS) { - try { - const directory = path30.dirname(filePath); - const upperName = path30.basename(filePath).toUpperCase(); - for (const actualName of yield (0, exports2.readdir)(directory)) { - if (upperName === actualName.toUpperCase()) { - filePath = path30.join(directory, actualName); - break; - } - } - } catch (err) { - console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); - } - return filePath; - } else { - if (isUnixExecutable(stats)) { - return filePath; - } - } + let path30 = opts.path; + if (!opts.path.startsWith("/")) { + path30 = `/${path30}`; + } + url2 = new URL(util4.parseOrigin(url2).origin + path30); + } else { + if (!opts) { + opts = typeof url2 === "object" ? url2 : {}; } + url2 = util4.parseURL(url2); } - return ""; - }); + const { agent, dispatcher = getGlobalDispatcher() } = opts; + if (agent) { + throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?"); + } + return fn.call(dispatcher, { + ...opts, + origin: url2.origin, + path: url2.search ? `${url2.pathname}${url2.search}` : url2.pathname, + method: opts.method || (opts.body ? "PUT" : "GET") + }, handler2); + }; } - function normalizeSeparators(p) { - p = p || ""; - if (exports2.IS_WINDOWS) { - p = p.replace(/\//g, "\\"); - return p.replace(/\\\\+/g, "\\"); + module2.exports.setGlobalDispatcher = setGlobalDispatcher; + module2.exports.getGlobalDispatcher = getGlobalDispatcher; + var fetchImpl = require_fetch().fetch; + var currentFilename = typeof __filename !== "undefined" ? __filename : void 0; + function appendFetchStackTrace(err, filename) { + if (!err || typeof err !== "object") { + return; } - return p.replace(/\/\/+/g, "/"); - } - function isUnixExecutable(stats) { - return (stats.mode & 1) > 0 || (stats.mode & 8) > 0 && process.getgid !== void 0 && stats.gid === process.getgid() || (stats.mode & 64) > 0 && process.getuid !== void 0 && stats.uid === process.getuid(); + const stack = typeof err.stack === "string" ? err.stack : ""; + const normalizedFilename = filename.replace(/\\/g, "/"); + if (stack && (stack.includes(filename) || stack.includes(normalizedFilename))) { + return; + } + const capture = {}; + Error.captureStackTrace(capture, appendFetchStackTrace); + if (!capture.stack) { + return; + } + const captureLines = capture.stack.split("\n").slice(1).join("\n"); + err.stack = stack ? `${stack} +${captureLines}` : capture.stack; } - function getCmdPath() { - var _a3; - return (_a3 = process.env["COMSPEC"]) !== null && _a3 !== void 0 ? _a3 : `cmd.exe`; + module2.exports.fetch = function fetch(init2, options = void 0) { + return fetchImpl(init2, options).catch((err) => { + if (currentFilename) { + appendFetchStackTrace(err, currentFilename); + } else if (err && typeof err === "object") { + Error.captureStackTrace(err, module2.exports.fetch); + } + throw err; + }); + }; + module2.exports.Headers = require_headers().Headers; + module2.exports.Response = require_response().Response; + module2.exports.Request = require_request2().Request; + module2.exports.FormData = require_formdata().FormData; + var { setGlobalOrigin, getGlobalOrigin } = require_global(); + module2.exports.setGlobalOrigin = setGlobalOrigin; + module2.exports.getGlobalOrigin = getGlobalOrigin; + var { CacheStorage } = require_cachestorage(); + var { kConstruct } = require_symbols(); + module2.exports.caches = new CacheStorage(kConstruct); + var { deleteCookie, getCookies, getSetCookies, setCookie, parseCookie } = require_cookies(); + module2.exports.deleteCookie = deleteCookie; + module2.exports.getCookies = getCookies; + module2.exports.getSetCookies = getSetCookies; + module2.exports.setCookie = setCookie; + module2.exports.parseCookie = parseCookie; + var { parseMIMEType, serializeAMimeType } = require_data_url(); + module2.exports.parseMIMEType = parseMIMEType; + module2.exports.serializeAMimeType = serializeAMimeType; + var { CloseEvent, ErrorEvent, MessageEvent } = require_events(); + var { WebSocket, ping } = require_websocket(); + module2.exports.WebSocket = WebSocket; + module2.exports.CloseEvent = CloseEvent; + module2.exports.ErrorEvent = ErrorEvent; + module2.exports.MessageEvent = MessageEvent; + module2.exports.ping = ping; + module2.exports.WebSocketStream = require_websocketstream().WebSocketStream; + module2.exports.WebSocketError = require_websocketerror().WebSocketError; + module2.exports.request = makeDispatcher(api.request); + module2.exports.stream = makeDispatcher(api.stream); + module2.exports.pipeline = makeDispatcher(api.pipeline); + module2.exports.connect = makeDispatcher(api.connect); + module2.exports.upgrade = makeDispatcher(api.upgrade); + module2.exports.MockClient = MockClient; + module2.exports.MockCallHistory = MockCallHistory; + module2.exports.MockCallHistoryLog = MockCallHistoryLog; + module2.exports.MockPool = MockPool; + module2.exports.MockAgent = MockAgent; + module2.exports.SnapshotAgent = SnapshotAgent; + module2.exports.mockErrors = mockErrors; + var { EventSource } = require_eventsource(); + module2.exports.EventSource = EventSource; + function install() { + globalThis.fetch = module2.exports.fetch; + globalThis.Headers = module2.exports.Headers; + globalThis.Response = module2.exports.Response; + globalThis.Request = module2.exports.Request; + globalThis.FormData = module2.exports.FormData; + globalThis.WebSocket = module2.exports.WebSocket; + globalThis.CloseEvent = module2.exports.CloseEvent; + globalThis.ErrorEvent = module2.exports.ErrorEvent; + globalThis.MessageEvent = module2.exports.MessageEvent; + globalThis.EventSource = module2.exports.EventSource; } + module2.exports.install = install; } }); -// node_modules/@actions/io/lib/io.js -var require_io = __commonJS({ - "node_modules/@actions/io/lib/io.js"(exports2) { +// node_modules/@actions/http-client/lib/index.js +var require_lib = __commonJS({ + "node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -20606,11 +26875,11 @@ var require_io = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -20626,252 +26895,645 @@ var require_io = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.cp = cp; - exports2.mv = mv; - exports2.rmRF = rmRF; - exports2.mkdirP = mkdirP; - exports2.which = which9; - exports2.findInPath = findInPath; - var assert_1 = require("assert"); - var path30 = __importStar2(require("path")); - var ioUtil = __importStar2(require_io_util()); - function cp(source_1, dest_1) { - return __awaiter2(this, arguments, void 0, function* (source, dest, options = {}) { - const { force, recursive, copySourceDirectory } = readCopyOptions(options); - const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; - if (destStat && destStat.isFile() && !force) { - return; - } - const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path30.join(dest, path30.basename(source)) : dest; - if (!(yield ioUtil.exists(source))) { - throw new Error(`no such file or directory: ${source}`); - } - const sourceStat = yield ioUtil.stat(source); - if (sourceStat.isDirectory()) { - if (!recursive) { - throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); - } else { - yield cpDirRecursive(source, newDest, 0, force); + exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + exports2.getProxyUrl = getProxyUrl; + exports2.isHttps = isHttps; + var http = __importStar2(require("http")); + var https3 = __importStar2(require("https")); + var pm = __importStar2(require_proxy()); + var tunnel = __importStar2(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); + } + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter2(this, void 0, void 0, function* () { + return new Promise((resolve15) => __awaiter2(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve15(output.toString()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter2(this, void 0, void 0, function* () { + return new Promise((resolve15) => __awaiter2(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve15(Buffer.concat(chunks)); + }); + })); + }); + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + var HttpClient2 = class { + constructor(userAgent2, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = this._getUserAgentWithOrchestrationId(userAgent2); + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - } else { - if (path30.relative(source, newDest) === "") { - throw new Error(`'${newDest}' and '${source}' are the same file`); + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - yield copyFile2(source, newDest, force); - } - }); - } - function mv(source_1, dest_1) { - return __awaiter2(this, arguments, void 0, function* (source, dest, options = {}) { - if (yield ioUtil.exists(dest)) { - let destExists = true; - if (yield ioUtil.isDirectory(dest)) { - dest = path30.join(dest, path30.basename(source)); - destExists = yield ioUtil.exists(dest); + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } - if (destExists) { - if (options.force == null || options.force) { - yield rmRF(dest); - } else { - throw new Error("Destination already exists"); - } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - yield mkdirP(path30.dirname(dest)); - yield ioUtil.rename(source, dest); - }); - } - function rmRF(inputPath) { - return __awaiter2(this, void 0, void 0, function* () { - if (ioUtil.IS_WINDOWS) { - if (/[*"<>|]/.test(inputPath)) { - throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); + } + options(requestUrl, additionalHeaders) { + return __awaiter2(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter2(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter2(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter2(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter2(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter2(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter2(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter2(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl_1) { + return __awaiter2(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl_1, obj_1) { + return __awaiter2(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl_1, obj_1) { + return __awaiter2(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter2(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter2(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } + const parsedUrl = new URL(requestUrl); + let info8 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info8, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler2 of this.handlers) { + if (handler2.canHandleAuthentication(response)) { + authenticationHandler = handler2; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info8, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info8 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info8, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - try { - yield ioUtil.rm(inputPath, { - force: true, - maxRetries: 3, - recursive: true, - retryDelay: 300 + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info8, data) { + return __awaiter2(this, void 0, void 0, function* () { + return new Promise((resolve15, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve15(res); + } + } + this.requestRawWithCallback(info8, data, callbackForResult); }); - } catch (err) { - throw new Error(`File was unable to be removed ${err}`); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info8, data, onResult) { + if (typeof data === "string") { + if (!info8.options.headers) { + info8.options.headers = {}; + } + info8.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - }); - } - function mkdirP(fsPath) { - return __awaiter2(this, void 0, void 0, function* () { - (0, assert_1.ok)(fsPath, "a path argument must be provided"); - yield ioUtil.mkdir(fsPath, { recursive: true }); - }); - } - function which9(tool, check) { - return __awaiter2(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (check) { - const result = yield which9(tool, false); - if (!result) { - if (ioUtil.IS_WINDOWS) { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); - } else { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); - } + const req = info8.httpModule.request(info8.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } - return result; + handleResult(new Error(`Request timeout: ${info8.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - const matches = yield findInPath(tool); - if (matches && matches.length > 0) { - return matches[0]; + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); } - return ""; - }); - } - function findInPath(tool) { - return __awaiter2(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - const extensions = []; - if (ioUtil.IS_WINDOWS && process.env["PATHEXT"]) { - for (const extension of process.env["PATHEXT"].split(path30.delimiter)) { - if (extension) { - extensions.push(extension); - } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info8 = {}; + info8.parsedUrl = requestUrl; + const usingSsl = info8.parsedUrl.protocol === "https:"; + info8.httpModule = usingSsl ? https3 : http; + const defaultPort = usingSsl ? 443 : 80; + info8.options = {}; + info8.options.host = info8.parsedUrl.hostname; + info8.options.port = info8.parsedUrl.port ? parseInt(info8.parsedUrl.port) : defaultPort; + info8.options.path = (info8.parsedUrl.pathname || "") + (info8.parsedUrl.search || ""); + info8.options.method = method; + info8.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info8.options.headers["user-agent"] = this.userAgent; + } + info8.options.agent = this._getAgent(info8.parsedUrl); + if (this.handlers) { + for (const handler2 of this.handlers) { + handler2.prepareRequest(info8.options); } } - if (ioUtil.isRooted(tool)) { - const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); - if (filePath) { - return [filePath]; + return info8; + } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys2(this.requestOptions.headers), lowercaseKeys2(headers || {})); + } + return lowercaseKeys2(headers || {}); + } + /** + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. + */ + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys2(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; } - return []; } - if (tool.includes(path30.sep)) { - return []; + const additionalValue = additionalHeaders[header]; + if (additionalValue !== void 0) { + return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; } - const directories = []; - if (process.env.PATH) { - for (const p of process.env.PATH.split(path30.delimiter)) { - if (p) { - directories.push(p); + if (clientHeader !== void 0) { + return clientHeader; + } + return _default; + } + /** + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + */ + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys2(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === "number") { + clientHeader = String(headerValue); + } else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(", "); + } else { + clientHeader = headerValue; } } } - const matches = []; - for (const directory of directories) { - const filePath = yield ioUtil.tryGetExecutablePath(path30.join(directory, tool), extensions); - if (filePath) { - matches.push(filePath); + const additionalValue = additionalHeaders[Headers.ContentType]; + if (additionalValue !== void 0) { + if (typeof additionalValue === "number") { + return String(additionalValue); + } else if (Array.isArray(additionalValue)) { + return additionalValue.join(", "); + } else { + return additionalValue; } } - return matches; - }); - } - function readCopyOptions(options) { - const force = options.force == null ? true : options.force; - const recursive = Boolean(options.recursive); - const copySourceDirectory = options.copySourceDirectory == null ? true : Boolean(options.copySourceDirectory); - return { force, recursive, copySourceDirectory }; - } - function cpDirRecursive(sourceDir, destDir, currentDepth, force) { - return __awaiter2(this, void 0, void 0, function* () { - if (currentDepth >= 255) - return; - currentDepth++; - yield mkdirP(destDir); - const files = yield ioUtil.readdir(sourceDir); - for (const fileName of files) { - const srcFile = `${sourceDir}/${fileName}`; - const destFile = `${destDir}/${fileName}`; - const srcFileStat = yield ioUtil.lstat(srcFile); - if (srcFileStat.isDirectory()) { - yield cpDirRecursive(srcFile, destFile, currentDepth, force); + if (clientHeader !== void 0) { + return clientHeader; + } + return _default; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { - yield copyFile2(srcFile, destFile, force); + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); - }); - } - function copyFile2(srcFile, destFile, force) { - return __awaiter2(this, void 0, void 0, function* () { - if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { - try { - yield ioUtil.lstat(destFile); - yield ioUtil.unlink(destFile); - } catch (e) { - if (e.code === "EPERM") { - yield ioUtil.chmod(destFile, "0666"); - yield ioUtil.unlink(destFile); - } - } - const symlinkFull = yield ioUtil.readlink(srcFile); - yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? "junction" : null); - } else if (!(yield ioUtil.exists(destFile)) || force) { - yield ioUtil.copyFile(srcFile, destFile); + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https3.Agent(options) : new http.Agent(options); + this._agent = agent; } - }); - } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _getUserAgentWithOrchestrationId(userAgent2) { + const baseUserAgent = userAgent2 || "actions/http-client"; + const orchId = process.env["ACTIONS_ORCHESTRATION_ID"]; + if (orchId) { + const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, "_"); + return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`; + } + return baseUserAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter2(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve15) => setTimeout(() => resolve15(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter2(this, void 0, void 0, function* () { + return new Promise((resolve15, reject) => __awaiter2(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve15(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve15(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys2 = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/exec/lib/toolrunner.js -var require_toolrunner = __commonJS({ - "node_modules/@actions/exec/lib/toolrunner.js"(exports2) { +// node_modules/@actions/http-client/lib/auth.js +var require_auth = __commonJS({ + "node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) 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 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys2 = function(o) { - ownKeys2 = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys2(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]); - } - __setModuleDefault2(result, mod); - return result; - }; - })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -20887,444 +27549,537 @@ var require_toolrunner = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ToolRunner = void 0; - exports2.argStringToArray = argStringToArray; - var os7 = __importStar2(require("os")); - var events = __importStar2(require("events")); - var child = __importStar2(require("child_process")); - var path30 = __importStar2(require("path")); - var io9 = __importStar2(require_io()); - var ioUtil = __importStar2(require_io_util()); - var timers_1 = require("timers"); - var IS_WINDOWS = process.platform === "win32"; - var ToolRunner7 = class extends events.EventEmitter { - constructor(toolPath, args, options) { - super(); - if (!toolPath) { - throw new Error("Parameter 'toolPath' cannot be null or empty."); - } - this.toolPath = toolPath; - this.args = args || []; - this.options = options || {}; + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; } - _debug(message) { - if (this.options.listeners && this.options.listeners.debug) { - this.options.listeners.debug(message); + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; } - _getCommandString(options, noPrefix) { - const toolPath = this._getSpawnFileName(); - const args = this._getSpawnArgs(options); - let cmd = noPrefix ? "" : "[command]"; - if (IS_WINDOWS) { - if (this._isCmdFile()) { - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } else if (options.windowsVerbatimArguments) { - cmd += `"${toolPath}"`; - for (const a of args) { - cmd += ` ${a}`; - } - } else { - cmd += this._windowsQuoteCmdArg(toolPath); - for (const a of args) { - cmd += ` ${this._windowsQuoteCmdArg(a)}`; - } - } - } else { - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } - return cmd; + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - _processLineBuffer(data, strBuffer, onLine) { - try { - let s = strBuffer + data.toString(); - let n = s.indexOf(os7.EOL); - while (n > -1) { - const line = s.substring(0, n); - onLine(line); - s = s.substring(n + os7.EOL.length); - n = s.indexOf(os7.EOL); - } - return s; - } catch (err) { - this._debug(`error processing line. Failed with error ${err}`); - return ""; - } + handleAuthentication() { + return __awaiter2(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } - _getSpawnFileName() { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - return process.env["COMSPEC"] || "cmd.exe"; - } - } - return this.toolPath; + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; } - _getSpawnArgs(options) { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; - for (const a of this.args) { - argline += " "; - argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); - } - argline += '"'; - return [argline]; - } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } - return this.args; + options.headers["Authorization"] = `Bearer ${this.token}`; } - _endsWith(str, end) { - return str.endsWith(end); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - _isCmdFile() { - const upperToolPath = this.toolPath.toUpperCase(); - return this._endsWith(upperToolPath, ".CMD") || this._endsWith(upperToolPath, ".BAT"); + handleAuthentication() { + return __awaiter2(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } - _windowsQuoteCmdArg(arg) { - if (!this._isCmdFile()) { - return this._uvQuoteCmdArg(arg); - } - if (!arg) { - return '""'; + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } - const cmdSpecialChars = [ - " ", - " ", - "&", - "(", - ")", - "[", - "]", - "{", - "}", - "^", - "=", - ";", - "!", - "'", - "+", - ",", - "`", - "~", - "|", - "<", - ">", - '"' - ]; - let needsQuotes = false; - for (const char of arg) { - if (cmdSpecialChars.some((x) => x === char)) { - needsQuotes = true; - break; + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter2(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; + } +}); + +// node_modules/@actions/core/lib/oidc-utils.js +var require_oidc_utils = __commonJS({ + "node_modules/@actions/core/lib/oidc-utils.js"(exports2) { + "use strict"; + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); + }); + } + return new (P || (P = Promise))(function(resolve15, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - if (!needsQuotes) { - return arg; - } - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === "\\") { - reverse += "\\"; - } else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += '"'; - } else { - quoteHit = false; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } } - reverse += '"'; - return reverse.split("").reverse().join(""); - } - _uvQuoteCmdArg(arg) { - if (!arg) { - return '""'; + function step(result) { + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } - if (!arg.includes(" ") && !arg.includes(" ") && !arg.includes('"')) { - return arg; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.OidcClient = void 0; + var http_client_1 = require_lib(); + var auth_1 = require_auth(); + var core_1 = require_core(); + var OidcClient = class _OidcClient { + static createHttpClient(allowRetry = true, maxRetry = 10) { + const requestOptions = { + allowRetries: allowRetry, + maxRetries: maxRetry + }; + return new http_client_1.HttpClient("actions/oidc-client", [new auth_1.BearerCredentialHandler(_OidcClient.getRequestToken())], requestOptions); + } + static getRequestToken() { + const token = process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"]; + if (!token) { + throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable"); } - if (!arg.includes('"') && !arg.includes("\\")) { - return `"${arg}"`; + return token; + } + static getIDTokenUrl() { + const runtimeUrl = process.env["ACTIONS_ID_TOKEN_REQUEST_URL"]; + if (!runtimeUrl) { + throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable"); } - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === "\\") { - reverse += "\\"; - } else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += "\\"; - } else { - quoteHit = false; - } - } - reverse += '"'; - return reverse.split("").reverse().join(""); - } - _cloneExecOptions(options) { - options = options || {}; - const result = { - cwd: options.cwd || process.cwd(), - env: options.env || process.env, - silent: options.silent || false, - windowsVerbatimArguments: options.windowsVerbatimArguments || false, - failOnStdErr: options.failOnStdErr || false, - ignoreReturnCode: options.ignoreReturnCode || false, - delay: options.delay || 1e4 - }; - result.outStream = options.outStream || process.stdout; - result.errStream = options.errStream || process.stderr; - return result; - } - _getSpawnOptions(options, toolPath) { - options = options || {}; - const result = {}; - result.cwd = options.cwd; - result.env = options.env; - result["windowsVerbatimArguments"] = options.windowsVerbatimArguments || this._isCmdFile(); - if (options.windowsVerbatimArguments) { - result.argv0 = `"${toolPath}"`; - } - return result; + return runtimeUrl; } - /** - * Exec a tool. - * Output will be streamed to the live console. - * Returns promise with return code - * - * @param tool path to tool to exec - * @param options optional exec options. See ExecOptions - * @returns number - */ - exec() { + static getCall(id_token_url) { return __awaiter2(this, void 0, void 0, function* () { - if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes("/") || IS_WINDOWS && this.toolPath.includes("\\"))) { - this.toolPath = path30.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); + var _a6; + const httpclient = _OidcClient.createHttpClient(); + const res = yield httpclient.getJson(id_token_url).catch((error3) => { + throw new Error(`Failed to get ID Token. + + Error Code : ${error3.statusCode} + + Error Message: ${error3.message}`); + }); + const id_token = (_a6 = res.result) === null || _a6 === void 0 ? void 0 : _a6.value; + if (!id_token) { + throw new Error("Response json body do not have ID Token field"); } - this.toolPath = yield io9.which(this.toolPath, true); - return new Promise((resolve14, reject) => __awaiter2(this, void 0, void 0, function* () { - this._debug(`exec tool: ${this.toolPath}`); - this._debug("arguments:"); - for (const arg of this.args) { - this._debug(` ${arg}`); - } - const optionsNonNull = this._cloneExecOptions(this.options); - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os7.EOL); - } - const state = new ExecState(optionsNonNull, this.toolPath); - state.on("debug", (message) => { - this._debug(message); - }); - if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { - return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); - } - const fileName = this._getSpawnFileName(); - const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); - let stdbuffer = ""; - if (cp.stdout) { - cp.stdout.on("data", (data) => { - if (this.options.listeners && this.options.listeners.stdout) { - this.options.listeners.stdout(data); - } - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(data); - } - stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { - if (this.options.listeners && this.options.listeners.stdline) { - this.options.listeners.stdline(line); - } - }); - }); - } - let errbuffer = ""; - if (cp.stderr) { - cp.stderr.on("data", (data) => { - state.processStderr = true; - if (this.options.listeners && this.options.listeners.stderr) { - this.options.listeners.stderr(data); - } - if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { - const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; - s.write(data); - } - errbuffer = this._processLineBuffer(data, errbuffer, (line) => { - if (this.options.listeners && this.options.listeners.errline) { - this.options.listeners.errline(line); - } - }); - }); - } - cp.on("error", (err) => { - state.processError = err.message; - state.processExited = true; - state.processClosed = true; - state.CheckComplete(); - }); - cp.on("exit", (code) => { - state.processExitCode = code; - state.processExited = true; - this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); - state.CheckComplete(); - }); - cp.on("close", (code) => { - state.processExitCode = code; - state.processExited = true; - state.processClosed = true; - this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); - state.CheckComplete(); - }); - state.on("done", (error3, exitCode) => { - if (stdbuffer.length > 0) { - this.emit("stdline", stdbuffer); - } - if (errbuffer.length > 0) { - this.emit("errline", errbuffer); - } - cp.removeAllListeners(); - if (error3) { - reject(error3); - } else { - resolve14(exitCode); - } - }); - if (this.options.input) { - if (!cp.stdin) { - throw new Error("child process missing stdin"); - } - cp.stdin.end(this.options.input); + return id_token; + }); + } + static getIDToken(audience) { + return __awaiter2(this, void 0, void 0, function* () { + try { + let id_token_url = _OidcClient.getIDTokenUrl(); + if (audience) { + const encodedAudience = encodeURIComponent(audience); + id_token_url = `${id_token_url}&audience=${encodedAudience}`; } - })); + (0, core_1.debug)(`ID token url is ${id_token_url}`); + const id_token = yield _OidcClient.getCall(id_token_url); + (0, core_1.setSecret)(id_token); + return id_token; + } catch (error3) { + throw new Error(`Error message: ${error3.message}`); + } }); } }; - exports2.ToolRunner = ToolRunner7; - function argStringToArray(argString) { - const args = []; - let inQuotes = false; - let escaped = false; - let arg = ""; - function append(c) { - if (escaped && c !== '"') { - arg += "\\"; - } - arg += c; - escaped = false; + exports2.OidcClient = OidcClient; + } +}); + +// node_modules/@actions/core/lib/summary.js +var require_summary = __commonJS({ + "node_modules/@actions/core/lib/summary.js"(exports2) { + "use strict"; + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); + }); } - for (let i = 0; i < argString.length; i++) { - const c = argString.charAt(i); - if (c === '"') { - if (!escaped) { - inQuotes = !inQuotes; - } else { - append(c); + return new (P || (P = Promise))(function(resolve15, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - continue; } - if (c === "\\" && escaped) { - append(c); - continue; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if (c === "\\" && inQuotes) { - escaped = true; - continue; + function step(result) { + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } - if (c === " " && !inQuotes) { - if (arg.length > 0) { - args.push(arg); - arg = ""; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.summary = exports2.markdownSummary = exports2.SUMMARY_DOCS_URL = exports2.SUMMARY_ENV_VAR = void 0; + var os_1 = require("os"); + var fs_1 = require("fs"); + var { access, appendFile, writeFile } = fs_1.promises; + exports2.SUMMARY_ENV_VAR = "GITHUB_STEP_SUMMARY"; + exports2.SUMMARY_DOCS_URL = "https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary"; + var Summary = class { + constructor() { + this._buffer = ""; + } + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + filePath() { + return __awaiter2(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; } - continue; + const pathFromEnv = process.env[exports2.SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${exports2.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + } + try { + yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); + } catch (_a6) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + } + this._filePath = pathFromEnv; + return this._filePath; + }); + } + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs).map(([key, value]) => ` ${key}="${value}"`).join(""); + if (!content) { + return `<${tag}${htmlAttrs}>`; } - append(c); + return `<${tag}${htmlAttrs}>${content}`; } - if (arg.length > 0) { - args.push(arg.trim()); + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options) { + return __awaiter2(this, void 0, void 0, function* () { + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: "utf8" }); + return this.emptyBuffer(); + }); } - return args; - } - var ExecState = class _ExecState extends events.EventEmitter { - constructor(options, toolPath) { - super(); - this.processClosed = false; - this.processError = ""; - this.processExitCode = 0; - this.processExited = false; - this.processStderr = false; - this.delay = 1e4; - this.done = false; - this.timeout = null; - if (!toolPath) { - throw new Error("toolPath must not be empty"); - } - this.options = options; - this.toolPath = toolPath; - if (options.delay) { - this.delay = options.delay; - } + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { + return __awaiter2(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); } - CheckComplete() { - if (this.done) { - return; - } - if (this.processClosed) { - this._setResult(); - } else if (this.processExited) { - this.timeout = (0, timers_1.setTimeout)(_ExecState.HandleTimeout, this.delay, this); - } + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; } - _debug(message) { - this.emit("debug", message); + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; } - _setResult() { - let error3; - if (this.processExited) { - if (this.processError) { - error3 = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); - } else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { - error3 = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); - } else if (this.processStderr && this.options.failOnStdErr) { - error3 = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); - } - } - if (this.timeout) { - clearTimeout(this.timeout); - this.timeout = null; - } - this.done = true; - this.emit("done", error3, this.processExitCode); + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ""; + return this; } - static HandleTimeout(state) { - if (state.done) { - return; - } - if (!state.processClosed && state.processExited) { - const message = `The STDIO streams did not close within ${state.delay / 1e3} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; - state._debug(message); - } - state._setResult(); + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; + } + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(os_1.EOL); + } + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code, lang) { + const attrs = Object.assign({}, lang && { lang }); + const element = this.wrap("pre", this.wrap("code", code), attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items, ordered = false) { + const tag = ordered ? "ol" : "ul"; + const listItems = items.map((item) => this.wrap("li", item)).join(""); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows.map((row) => { + const cells = row.map((cell) => { + if (typeof cell === "string") { + return this.wrap("td", cell); + } + const { header, data, colspan, rowspan } = cell; + const tag = header ? "th" : "td"; + const attrs = Object.assign(Object.assign({}, colspan && { colspan }), rowspan && { rowspan }); + return this.wrap(tag, data, attrs); + }).join(""); + return this.wrap("tr", cells); + }).join(""); + const element = this.wrap("table", tableBody); + return this.addRaw(element).addEOL(); + } + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label, content) { + const element = this.wrap("details", this.wrap("summary", label) + content); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, width && { width }), height && { height }); + const element = this.wrap("img", null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ["h1", "h2", "h3", "h4", "h5", "h6"].includes(tag) ? tag : "h1"; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap("hr", null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap("br", null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, cite && { cite }); + const element = this.wrap("blockquote", text, attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap("a", text, { href }); + return this.addRaw(element).addEOL(); } }; + var _summary = new Summary(); + exports2.markdownSummary = _summary; + exports2.summary = _summary; } }); -// node_modules/@actions/exec/lib/exec.js -var require_exec = __commonJS({ - "node_modules/@actions/exec/lib/exec.js"(exports2) { +// node_modules/@actions/core/lib/path-utils.js +var require_path_utils = __commonJS({ + "node_modules/@actions/core/lib/path-utils.js"(exports2) { + "use strict"; + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys2 = function(o) { + ownKeys2 = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys2(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]); + } + __setModuleDefault2(result, mod); + return result; + }; + })(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.toPosixPath = toPosixPath; + exports2.toWin32Path = toWin32Path; + exports2.toPlatformPath = toPlatformPath; + var path30 = __importStar2(require("path")); + function toPosixPath(pth) { + return pth.replace(/[\\]/g, "/"); + } + function toWin32Path(pth) { + return pth.replace(/[/]/g, "\\"); + } + function toPlatformPath(pth) { + return pth.replace(/[/\\]/g, path30.sep); + } + } +}); + +// node_modules/@actions/io/lib/io-util.js +var require_io_util = __commonJS({ + "node_modules/@actions/io/lib/io-util.js"(exports2) { "use strict"; var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -21365,11 +28120,11 @@ var require_exec = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -21385,66 +28140,143 @@ var require_exec = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; + var _a6; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exec = exec3; - exports2.getExecOutput = getExecOutput; - var string_decoder_1 = require("string_decoder"); - var tr = __importStar2(require_toolrunner()); - function exec3(commandLine, args, options) { + exports2.READONLY = exports2.UV_FS_O_EXLOCK = exports2.IS_WINDOWS = exports2.unlink = exports2.symlink = exports2.stat = exports2.rmdir = exports2.rm = exports2.rename = exports2.readdir = exports2.open = exports2.mkdir = exports2.lstat = exports2.copyFile = exports2.chmod = void 0; + exports2.readlink = readlink; + exports2.exists = exists; + exports2.isDirectory = isDirectory; + exports2.isRooted = isRooted; + exports2.tryGetExecutablePath = tryGetExecutablePath; + exports2.getCmdPath = getCmdPath; + var fs34 = __importStar2(require("fs")); + var path30 = __importStar2(require("path")); + _a6 = fs34.promises, exports2.chmod = _a6.chmod, exports2.copyFile = _a6.copyFile, exports2.lstat = _a6.lstat, exports2.mkdir = _a6.mkdir, exports2.open = _a6.open, exports2.readdir = _a6.readdir, exports2.rename = _a6.rename, exports2.rm = _a6.rm, exports2.rmdir = _a6.rmdir, exports2.stat = _a6.stat, exports2.symlink = _a6.symlink, exports2.unlink = _a6.unlink; + exports2.IS_WINDOWS = process.platform === "win32"; + function readlink(fsPath) { return __awaiter2(this, void 0, void 0, function* () { - const commandArgs = tr.argStringToArray(commandLine); - if (commandArgs.length === 0) { - throw new Error(`Parameter 'commandLine' cannot be null or empty.`); + const result = yield fs34.promises.readlink(fsPath); + if (exports2.IS_WINDOWS && !result.endsWith("\\")) { + return `${result}\\`; } - const toolPath = commandArgs[0]; - args = commandArgs.slice(1).concat(args || []); - const runner = new tr.ToolRunner(toolPath, args, options); - return runner.exec(); + return result; }); } - function getExecOutput(commandLine, args, options) { + exports2.UV_FS_O_EXLOCK = 268435456; + exports2.READONLY = fs34.constants.O_RDONLY; + function exists(fsPath) { return __awaiter2(this, void 0, void 0, function* () { - var _a2, _b; - let stdout = ""; - let stderr = ""; - const stdoutDecoder = new string_decoder_1.StringDecoder("utf8"); - const stderrDecoder = new string_decoder_1.StringDecoder("utf8"); - const originalStdoutListener = (_a2 = options === null || options === void 0 ? void 0 : options.listeners) === null || _a2 === void 0 ? void 0 : _a2.stdout; - const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; - const stdErrListener = (data) => { - stderr += stderrDecoder.write(data); - if (originalStdErrListener) { - originalStdErrListener(data); + try { + yield (0, exports2.stat)(fsPath); + } catch (err) { + if (err.code === "ENOENT") { + return false; } - }; - const stdOutListener = (data) => { - stdout += stdoutDecoder.write(data); - if (originalStdoutListener) { - originalStdoutListener(data); + throw err; + } + return true; + }); + } + function isDirectory(fsPath_1) { + return __awaiter2(this, arguments, void 0, function* (fsPath, useStat = false) { + const stats = useStat ? yield (0, exports2.stat)(fsPath) : yield (0, exports2.lstat)(fsPath); + return stats.isDirectory(); + }); + } + function isRooted(p) { + p = normalizeSeparators(p); + if (!p) { + throw new Error('isRooted() parameter "p" cannot be empty'); + } + if (exports2.IS_WINDOWS) { + return p.startsWith("\\") || /^[A-Z]:/i.test(p); + } + return p.startsWith("/"); + } + function tryGetExecutablePath(filePath, extensions) { + return __awaiter2(this, void 0, void 0, function* () { + let stats = void 0; + try { + stats = yield (0, exports2.stat)(filePath); + } catch (err) { + if (err.code !== "ENOENT") { + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } - }; - const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); - const exitCode = yield exec3(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); - stdout += stdoutDecoder.end(); - stderr += stderrDecoder.end(); - return { - exitCode, - stdout, - stderr - }; + } + if (stats && stats.isFile()) { + if (exports2.IS_WINDOWS) { + const upperExt = path30.extname(filePath).toUpperCase(); + if (extensions.some((validExt) => validExt.toUpperCase() === upperExt)) { + return filePath; + } + } else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + const originalFilePath = filePath; + for (const extension of extensions) { + filePath = originalFilePath + extension; + stats = void 0; + try { + stats = yield (0, exports2.stat)(filePath); + } catch (err) { + if (err.code !== "ENOENT") { + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports2.IS_WINDOWS) { + try { + const directory = path30.dirname(filePath); + const upperName = path30.basename(filePath).toUpperCase(); + for (const actualName of yield (0, exports2.readdir)(directory)) { + if (upperName === actualName.toUpperCase()) { + filePath = path30.join(directory, actualName); + break; + } + } + } catch (err) { + console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); + } + return filePath; + } else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + } + return ""; }); } + function normalizeSeparators(p) { + p = p || ""; + if (exports2.IS_WINDOWS) { + p = p.replace(/\//g, "\\"); + return p.replace(/\\\\+/g, "\\"); + } + return p.replace(/\/\/+/g, "/"); + } + function isUnixExecutable(stats) { + return (stats.mode & 1) > 0 || (stats.mode & 8) > 0 && process.getgid !== void 0 && stats.gid === process.getgid() || (stats.mode & 64) > 0 && process.getuid !== void 0 && stats.uid === process.getuid(); + } + function getCmdPath() { + var _a7; + return (_a7 = process.env["COMSPEC"]) !== null && _a7 !== void 0 ? _a7 : `cmd.exe`; + } } }); -// node_modules/@actions/core/lib/platform.js -var require_platform = __commonJS({ - "node_modules/@actions/core/lib/platform.js"(exports2) { +// node_modules/@actions/io/lib/io.js +var require_io = __commonJS({ + "node_modules/@actions/io/lib/io.js"(exports2) { "use strict"; var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -21485,11 +28317,11 @@ var require_platform = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -21505,75 +28337,207 @@ var require_platform = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isLinux = exports2.isMacOS = exports2.isWindows = exports2.arch = exports2.platform = void 0; - exports2.getDetails = getDetails; - var os_1 = __importDefault2(require("os")); - var exec3 = __importStar2(require_exec()); - var getWindowsInfo = () => __awaiter2(void 0, void 0, void 0, function* () { - const { stdout: version } = yield exec3.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', void 0, { - silent: true + exports2.cp = cp; + exports2.mv = mv; + exports2.rmRF = rmRF; + exports2.mkdirP = mkdirP; + exports2.which = which10; + exports2.findInPath = findInPath; + var assert_1 = require("assert"); + var path30 = __importStar2(require("path")); + var ioUtil = __importStar2(require_io_util()); + function cp(source_1, dest_1) { + return __awaiter2(this, arguments, void 0, function* (source, dest, options = {}) { + const { force, recursive, copySourceDirectory } = readCopyOptions(options); + const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; + if (destStat && destStat.isFile() && !force) { + return; + } + const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path30.join(dest, path30.basename(source)) : dest; + if (!(yield ioUtil.exists(source))) { + throw new Error(`no such file or directory: ${source}`); + } + const sourceStat = yield ioUtil.stat(source); + if (sourceStat.isDirectory()) { + if (!recursive) { + throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); + } else { + yield cpDirRecursive(source, newDest, 0, force); + } + } else { + if (path30.relative(source, newDest) === "") { + throw new Error(`'${newDest}' and '${source}' are the same file`); + } + yield copyFile2(source, newDest, force); + } }); - const { stdout: name } = yield exec3.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', void 0, { - silent: true + } + function mv(source_1, dest_1) { + return __awaiter2(this, arguments, void 0, function* (source, dest, options = {}) { + if (yield ioUtil.exists(dest)) { + let destExists = true; + if (yield ioUtil.isDirectory(dest)) { + dest = path30.join(dest, path30.basename(source)); + destExists = yield ioUtil.exists(dest); + } + if (destExists) { + if (options.force == null || options.force) { + yield rmRF(dest); + } else { + throw new Error("Destination already exists"); + } + } + } + yield mkdirP(path30.dirname(dest)); + yield ioUtil.rename(source, dest); }); - return { - name: name.trim(), - version: version.trim() - }; - }); - var getMacOsInfo = () => __awaiter2(void 0, void 0, void 0, function* () { - var _a2, _b, _c, _d; - const { stdout } = yield exec3.getExecOutput("sw_vers", void 0, { - silent: true + } + function rmRF(inputPath) { + return __awaiter2(this, void 0, void 0, function* () { + if (ioUtil.IS_WINDOWS) { + if (/[*"<>|]/.test(inputPath)) { + throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); + } + } + try { + yield ioUtil.rm(inputPath, { + force: true, + maxRetries: 3, + recursive: true, + retryDelay: 300 + }); + } catch (err) { + throw new Error(`File was unable to be removed ${err}`); + } }); - const version = (_b = (_a2 = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a2 === void 0 ? void 0 : _a2[1]) !== null && _b !== void 0 ? _b : ""; - const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ""; - return { - name, - version - }; - }); - var getLinuxInfo = () => __awaiter2(void 0, void 0, void 0, function* () { - const { stdout } = yield exec3.getExecOutput("lsb_release", ["-i", "-r", "-s"], { - silent: true + } + function mkdirP(fsPath) { + return __awaiter2(this, void 0, void 0, function* () { + (0, assert_1.ok)(fsPath, "a path argument must be provided"); + yield ioUtil.mkdir(fsPath, { recursive: true }); }); - const [name, version] = stdout.trim().split("\n"); - return { - name, - version - }; - }); - exports2.platform = os_1.default.platform(); - exports2.arch = os_1.default.arch(); - exports2.isWindows = exports2.platform === "win32"; - exports2.isMacOS = exports2.platform === "darwin"; - exports2.isLinux = exports2.platform === "linux"; - function getDetails() { + } + function which10(tool, check) { return __awaiter2(this, void 0, void 0, function* () { - return Object.assign(Object.assign({}, yield exports2.isWindows ? getWindowsInfo() : exports2.isMacOS ? getMacOsInfo() : getLinuxInfo()), { - platform: exports2.platform, - arch: exports2.arch, - isWindows: exports2.isWindows, - isMacOS: exports2.isMacOS, - isLinux: exports2.isLinux - }); + if (!tool) { + throw new Error("parameter 'tool' is required"); + } + if (check) { + const result = yield which10(tool, false); + if (!result) { + if (ioUtil.IS_WINDOWS) { + throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); + } else { + throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); + } + } + return result; + } + const matches = yield findInPath(tool); + if (matches && matches.length > 0) { + return matches[0]; + } + return ""; + }); + } + function findInPath(tool) { + return __awaiter2(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); + } + const extensions = []; + if (ioUtil.IS_WINDOWS && process.env["PATHEXT"]) { + for (const extension of process.env["PATHEXT"].split(path30.delimiter)) { + if (extension) { + extensions.push(extension); + } + } + } + if (ioUtil.isRooted(tool)) { + const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); + if (filePath) { + return [filePath]; + } + return []; + } + if (tool.includes(path30.sep)) { + return []; + } + const directories = []; + if (process.env.PATH) { + for (const p of process.env.PATH.split(path30.delimiter)) { + if (p) { + directories.push(p); + } + } + } + const matches = []; + for (const directory of directories) { + const filePath = yield ioUtil.tryGetExecutablePath(path30.join(directory, tool), extensions); + if (filePath) { + matches.push(filePath); + } + } + return matches; + }); + } + function readCopyOptions(options) { + const force = options.force == null ? true : options.force; + const recursive = Boolean(options.recursive); + const copySourceDirectory = options.copySourceDirectory == null ? true : Boolean(options.copySourceDirectory); + return { force, recursive, copySourceDirectory }; + } + function cpDirRecursive(sourceDir, destDir, currentDepth, force) { + return __awaiter2(this, void 0, void 0, function* () { + if (currentDepth >= 255) + return; + currentDepth++; + yield mkdirP(destDir); + const files = yield ioUtil.readdir(sourceDir); + for (const fileName of files) { + const srcFile = `${sourceDir}/${fileName}`; + const destFile = `${destDir}/${fileName}`; + const srcFileStat = yield ioUtil.lstat(srcFile); + if (srcFileStat.isDirectory()) { + yield cpDirRecursive(srcFile, destFile, currentDepth, force); + } else { + yield copyFile2(srcFile, destFile, force); + } + } + yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); + }); + } + function copyFile2(srcFile, destFile, force) { + return __awaiter2(this, void 0, void 0, function* () { + if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { + try { + yield ioUtil.lstat(destFile); + yield ioUtil.unlink(destFile); + } catch (e) { + if (e.code === "EPERM") { + yield ioUtil.chmod(destFile, "0666"); + yield ioUtil.unlink(destFile); + } + } + const symlinkFull = yield ioUtil.readlink(srcFile); + yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? "junction" : null); + } else if (!(yield ioUtil.exists(destFile)) || force) { + yield ioUtil.copyFile(srcFile, destFile); + } }); } } }); -// node_modules/@actions/core/lib/core.js -var require_core = __commonJS({ - "node_modules/@actions/core/lib/core.js"(exports2) { +// node_modules/@actions/exec/lib/toolrunner.js +var require_toolrunner = __commonJS({ + "node_modules/@actions/exec/lib/toolrunner.js"(exports2) { "use strict"; var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -21614,11 +28578,11 @@ var require_core = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -21634,61 +28598,808 @@ var require_core = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.platform = exports2.toPlatformPath = exports2.toWin32Path = exports2.toPosixPath = exports2.markdownSummary = exports2.summary = exports2.ExitCode = void 0; - exports2.exportVariable = exportVariable16; - exports2.setSecret = setSecret2; - exports2.addPath = addPath2; - exports2.getInput = getInput2; - exports2.getMultilineInput = getMultilineInput; - exports2.getBooleanInput = getBooleanInput; - exports2.setOutput = setOutput7; - exports2.setCommandEcho = setCommandEcho; - exports2.setFailed = setFailed12; - exports2.isDebug = isDebug5; - exports2.debug = debug6; - exports2.error = error3; - exports2.warning = warning14; - exports2.notice = notice; - exports2.info = info8; - exports2.startGroup = startGroup4; - exports2.endGroup = endGroup4; - exports2.group = group; - exports2.saveState = saveState3; - exports2.getState = getState3; - exports2.getIDToken = getIDToken; - var command_1 = require_command(); - var file_command_1 = require_file_command(); - var utils_1 = require_utils(); - var os7 = __importStar2(require("os")); + exports2.ToolRunner = void 0; + exports2.argStringToArray = argStringToArray; + var os8 = __importStar2(require("os")); + var events = __importStar2(require("events")); + var child = __importStar2(require("child_process")); var path30 = __importStar2(require("path")); - var oidc_utils_1 = require_oidc_utils(); - var ExitCode; - (function(ExitCode2) { - ExitCode2[ExitCode2["Success"] = 0] = "Success"; - ExitCode2[ExitCode2["Failure"] = 1] = "Failure"; - })(ExitCode || (exports2.ExitCode = ExitCode = {})); - function exportVariable16(name, val) { - const convertedVal = (0, utils_1.toCommandValue)(val); - process.env[name] = convertedVal; - const filePath = process.env["GITHUB_ENV"] || ""; - if (filePath) { - return (0, file_command_1.issueFileCommand)("ENV", (0, file_command_1.prepareKeyValueMessage)(name, val)); - } - (0, command_1.issueCommand)("set-env", { name }, convertedVal); - } - function setSecret2(secret) { - (0, command_1.issueCommand)("add-mask", {}, secret); - } - function addPath2(inputPath) { - const filePath = process.env["GITHUB_PATH"] || ""; - if (filePath) { - (0, file_command_1.issueFileCommand)("PATH", inputPath); + var io10 = __importStar2(require_io()); + var ioUtil = __importStar2(require_io_util()); + var timers_1 = require("timers"); + var IS_WINDOWS = process.platform === "win32"; + var ToolRunner8 = class extends events.EventEmitter { + constructor(toolPath, args, options) { + super(); + if (!toolPath) { + throw new Error("Parameter 'toolPath' cannot be null or empty."); + } + this.toolPath = toolPath; + this.args = args || []; + this.options = options || {}; + } + _debug(message) { + if (this.options.listeners && this.options.listeners.debug) { + this.options.listeners.debug(message); + } + } + _getCommandString(options, noPrefix) { + const toolPath = this._getSpawnFileName(); + const args = this._getSpawnArgs(options); + let cmd = noPrefix ? "" : "[command]"; + if (IS_WINDOWS) { + if (this._isCmdFile()) { + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; + } + } else if (options.windowsVerbatimArguments) { + cmd += `"${toolPath}"`; + for (const a of args) { + cmd += ` ${a}`; + } + } else { + cmd += this._windowsQuoteCmdArg(toolPath); + for (const a of args) { + cmd += ` ${this._windowsQuoteCmdArg(a)}`; + } + } + } else { + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; + } + } + return cmd; + } + _processLineBuffer(data, strBuffer, onLine) { + try { + let s = strBuffer + data.toString(); + let n = s.indexOf(os8.EOL); + while (n > -1) { + const line = s.substring(0, n); + onLine(line); + s = s.substring(n + os8.EOL.length); + n = s.indexOf(os8.EOL); + } + return s; + } catch (err) { + this._debug(`error processing line. Failed with error ${err}`); + return ""; + } + } + _getSpawnFileName() { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + return process.env["COMSPEC"] || "cmd.exe"; + } + } + return this.toolPath; + } + _getSpawnArgs(options) { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; + for (const a of this.args) { + argline += " "; + argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); + } + argline += '"'; + return [argline]; + } + } + return this.args; + } + _endsWith(str, end) { + return str.endsWith(end); + } + _isCmdFile() { + const upperToolPath = this.toolPath.toUpperCase(); + return this._endsWith(upperToolPath, ".CMD") || this._endsWith(upperToolPath, ".BAT"); + } + _windowsQuoteCmdArg(arg) { + if (!this._isCmdFile()) { + return this._uvQuoteCmdArg(arg); + } + if (!arg) { + return '""'; + } + const cmdSpecialChars = [ + " ", + " ", + "&", + "(", + ")", + "[", + "]", + "{", + "}", + "^", + "=", + ";", + "!", + "'", + "+", + ",", + "`", + "~", + "|", + "<", + ">", + '"' + ]; + let needsQuotes = false; + for (const char of arg) { + if (cmdSpecialChars.some((x) => x === char)) { + needsQuotes = true; + break; + } + } + if (!needsQuotes) { + return arg; + } + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === "\\") { + reverse += "\\"; + } else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '"'; + } else { + quoteHit = false; + } + } + reverse += '"'; + return reverse.split("").reverse().join(""); + } + _uvQuoteCmdArg(arg) { + if (!arg) { + return '""'; + } + if (!arg.includes(" ") && !arg.includes(" ") && !arg.includes('"')) { + return arg; + } + if (!arg.includes('"') && !arg.includes("\\")) { + return `"${arg}"`; + } + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === "\\") { + reverse += "\\"; + } else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += "\\"; + } else { + quoteHit = false; + } + } + reverse += '"'; + return reverse.split("").reverse().join(""); + } + _cloneExecOptions(options) { + options = options || {}; + const result = { + cwd: options.cwd || process.cwd(), + env: options.env || process.env, + silent: options.silent || false, + windowsVerbatimArguments: options.windowsVerbatimArguments || false, + failOnStdErr: options.failOnStdErr || false, + ignoreReturnCode: options.ignoreReturnCode || false, + delay: options.delay || 1e4 + }; + result.outStream = options.outStream || process.stdout; + result.errStream = options.errStream || process.stderr; + return result; + } + _getSpawnOptions(options, toolPath) { + options = options || {}; + const result = {}; + result.cwd = options.cwd; + result.env = options.env; + result["windowsVerbatimArguments"] = options.windowsVerbatimArguments || this._isCmdFile(); + if (options.windowsVerbatimArguments) { + result.argv0 = `"${toolPath}"`; + } + return result; + } + /** + * Exec a tool. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param tool path to tool to exec + * @param options optional exec options. See ExecOptions + * @returns number + */ + exec() { + return __awaiter2(this, void 0, void 0, function* () { + if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes("/") || IS_WINDOWS && this.toolPath.includes("\\"))) { + this.toolPath = path30.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); + } + this.toolPath = yield io10.which(this.toolPath, true); + return new Promise((resolve15, reject) => __awaiter2(this, void 0, void 0, function* () { + this._debug(`exec tool: ${this.toolPath}`); + this._debug("arguments:"); + for (const arg of this.args) { + this._debug(` ${arg}`); + } + const optionsNonNull = this._cloneExecOptions(this.options); + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os8.EOL); + } + const state = new ExecState(optionsNonNull, this.toolPath); + state.on("debug", (message) => { + this._debug(message); + }); + if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { + return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); + } + const fileName = this._getSpawnFileName(); + const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); + let stdbuffer = ""; + if (cp.stdout) { + cp.stdout.on("data", (data) => { + if (this.options.listeners && this.options.listeners.stdout) { + this.options.listeners.stdout(data); + } + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(data); + } + stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { + if (this.options.listeners && this.options.listeners.stdline) { + this.options.listeners.stdline(line); + } + }); + }); + } + let errbuffer = ""; + if (cp.stderr) { + cp.stderr.on("data", (data) => { + state.processStderr = true; + if (this.options.listeners && this.options.listeners.stderr) { + this.options.listeners.stderr(data); + } + if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { + const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; + s.write(data); + } + errbuffer = this._processLineBuffer(data, errbuffer, (line) => { + if (this.options.listeners && this.options.listeners.errline) { + this.options.listeners.errline(line); + } + }); + }); + } + cp.on("error", (err) => { + state.processError = err.message; + state.processExited = true; + state.processClosed = true; + state.CheckComplete(); + }); + cp.on("exit", (code) => { + state.processExitCode = code; + state.processExited = true; + this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); + state.CheckComplete(); + }); + cp.on("close", (code) => { + state.processExitCode = code; + state.processExited = true; + state.processClosed = true; + this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); + state.CheckComplete(); + }); + state.on("done", (error3, exitCode) => { + if (stdbuffer.length > 0) { + this.emit("stdline", stdbuffer); + } + if (errbuffer.length > 0) { + this.emit("errline", errbuffer); + } + cp.removeAllListeners(); + if (error3) { + reject(error3); + } else { + resolve15(exitCode); + } + }); + if (this.options.input) { + if (!cp.stdin) { + throw new Error("child process missing stdin"); + } + cp.stdin.end(this.options.input); + } + })); + }); + } + }; + exports2.ToolRunner = ToolRunner8; + function argStringToArray(argString) { + const args = []; + let inQuotes = false; + let escaped = false; + let arg = ""; + function append(c) { + if (escaped && c !== '"') { + arg += "\\"; + } + arg += c; + escaped = false; + } + for (let i = 0; i < argString.length; i++) { + const c = argString.charAt(i); + if (c === '"') { + if (!escaped) { + inQuotes = !inQuotes; + } else { + append(c); + } + continue; + } + if (c === "\\" && escaped) { + append(c); + continue; + } + if (c === "\\" && inQuotes) { + escaped = true; + continue; + } + if (c === " " && !inQuotes) { + if (arg.length > 0) { + args.push(arg); + arg = ""; + } + continue; + } + append(c); + } + if (arg.length > 0) { + args.push(arg.trim()); + } + return args; + } + var ExecState = class _ExecState extends events.EventEmitter { + constructor(options, toolPath) { + super(); + this.processClosed = false; + this.processError = ""; + this.processExitCode = 0; + this.processExited = false; + this.processStderr = false; + this.delay = 1e4; + this.done = false; + this.timeout = null; + if (!toolPath) { + throw new Error("toolPath must not be empty"); + } + this.options = options; + this.toolPath = toolPath; + if (options.delay) { + this.delay = options.delay; + } + } + CheckComplete() { + if (this.done) { + return; + } + if (this.processClosed) { + this._setResult(); + } else if (this.processExited) { + this.timeout = (0, timers_1.setTimeout)(_ExecState.HandleTimeout, this.delay, this); + } + } + _debug(message) { + this.emit("debug", message); + } + _setResult() { + let error3; + if (this.processExited) { + if (this.processError) { + error3 = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); + } else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { + error3 = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); + } else if (this.processStderr && this.options.failOnStdErr) { + error3 = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); + } + } + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = null; + } + this.done = true; + this.emit("done", error3, this.processExitCode); + } + static HandleTimeout(state) { + if (state.done) { + return; + } + if (!state.processClosed && state.processExited) { + const message = `The STDIO streams did not close within ${state.delay / 1e3} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; + state._debug(message); + } + state._setResult(); + } + }; + } +}); + +// node_modules/@actions/exec/lib/exec.js +var require_exec = __commonJS({ + "node_modules/@actions/exec/lib/exec.js"(exports2) { + "use strict"; + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys2 = function(o) { + ownKeys2 = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys2(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]); + } + __setModuleDefault2(result, mod); + return result; + }; + })(); + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); + }); + } + return new (P || (P = Promise))(function(resolve15, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.exec = exec3; + exports2.getExecOutput = getExecOutput; + var string_decoder_1 = require("string_decoder"); + var tr = __importStar2(require_toolrunner()); + function exec3(commandLine, args, options) { + return __awaiter2(this, void 0, void 0, function* () { + const commandArgs = tr.argStringToArray(commandLine); + if (commandArgs.length === 0) { + throw new Error(`Parameter 'commandLine' cannot be null or empty.`); + } + const toolPath = commandArgs[0]; + args = commandArgs.slice(1).concat(args || []); + const runner = new tr.ToolRunner(toolPath, args, options); + return runner.exec(); + }); + } + function getExecOutput(commandLine, args, options) { + return __awaiter2(this, void 0, void 0, function* () { + var _a6, _b2; + let stdout = ""; + let stderr = ""; + const stdoutDecoder = new string_decoder_1.StringDecoder("utf8"); + const stderrDecoder = new string_decoder_1.StringDecoder("utf8"); + const originalStdoutListener = (_a6 = options === null || options === void 0 ? void 0 : options.listeners) === null || _a6 === void 0 ? void 0 : _a6.stdout; + const originalStdErrListener = (_b2 = options === null || options === void 0 ? void 0 : options.listeners) === null || _b2 === void 0 ? void 0 : _b2.stderr; + const stdErrListener = (data) => { + stderr += stderrDecoder.write(data); + if (originalStdErrListener) { + originalStdErrListener(data); + } + }; + const stdOutListener = (data) => { + stdout += stdoutDecoder.write(data); + if (originalStdoutListener) { + originalStdoutListener(data); + } + }; + const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); + const exitCode = yield exec3(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); + stdout += stdoutDecoder.end(); + stderr += stderrDecoder.end(); + return { + exitCode, + stdout, + stderr + }; + }); + } + } +}); + +// node_modules/@actions/core/lib/platform.js +var require_platform = __commonJS({ + "node_modules/@actions/core/lib/platform.js"(exports2) { + "use strict"; + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys2 = function(o) { + ownKeys2 = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys2(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]); + } + __setModuleDefault2(result, mod); + return result; + }; + })(); + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); + }); + } + return new (P || (P = Promise))(function(resolve15, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isLinux = exports2.isMacOS = exports2.isWindows = exports2.arch = exports2.platform = void 0; + exports2.getDetails = getDetails; + var os_1 = __importDefault2(require("os")); + var exec3 = __importStar2(require_exec()); + var getWindowsInfo = () => __awaiter2(void 0, void 0, void 0, function* () { + const { stdout: version } = yield exec3.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', void 0, { + silent: true + }); + const { stdout: name } = yield exec3.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', void 0, { + silent: true + }); + return { + name: name.trim(), + version: version.trim() + }; + }); + var getMacOsInfo = () => __awaiter2(void 0, void 0, void 0, function* () { + var _a6, _b2, _c2, _d2; + const { stdout } = yield exec3.getExecOutput("sw_vers", void 0, { + silent: true + }); + const version = (_b2 = (_a6 = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a6 === void 0 ? void 0 : _a6[1]) !== null && _b2 !== void 0 ? _b2 : ""; + const name = (_d2 = (_c2 = stdout.match(/ProductName:\s*(.+)/)) === null || _c2 === void 0 ? void 0 : _c2[1]) !== null && _d2 !== void 0 ? _d2 : ""; + return { + name, + version + }; + }); + var getLinuxInfo = () => __awaiter2(void 0, void 0, void 0, function* () { + const { stdout } = yield exec3.getExecOutput("lsb_release", ["-i", "-r", "-s"], { + silent: true + }); + const [name, version] = stdout.trim().split("\n"); + return { + name, + version + }; + }); + exports2.platform = os_1.default.platform(); + exports2.arch = os_1.default.arch(); + exports2.isWindows = exports2.platform === "win32"; + exports2.isMacOS = exports2.platform === "darwin"; + exports2.isLinux = exports2.platform === "linux"; + function getDetails() { + return __awaiter2(this, void 0, void 0, function* () { + return Object.assign(Object.assign({}, yield exports2.isWindows ? getWindowsInfo() : exports2.isMacOS ? getMacOsInfo() : getLinuxInfo()), { + platform: exports2.platform, + arch: exports2.arch, + isWindows: exports2.isWindows, + isMacOS: exports2.isMacOS, + isLinux: exports2.isLinux + }); + }); + } + } +}); + +// node_modules/@actions/core/lib/core.js +var require_core = __commonJS({ + "node_modules/@actions/core/lib/core.js"(exports2) { + "use strict"; + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys2 = function(o) { + ownKeys2 = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys2(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]); + } + __setModuleDefault2(result, mod); + return result; + }; + })(); + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); + }); + } + return new (P || (P = Promise))(function(resolve15, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.platform = exports2.toPlatformPath = exports2.toWin32Path = exports2.toPosixPath = exports2.markdownSummary = exports2.summary = exports2.ExitCode = void 0; + exports2.exportVariable = exportVariable2; + exports2.setSecret = setSecret2; + exports2.addPath = addPath2; + exports2.getInput = getInput2; + exports2.getMultilineInput = getMultilineInput; + exports2.getBooleanInput = getBooleanInput; + exports2.setOutput = setOutput7; + exports2.setCommandEcho = setCommandEcho; + exports2.setFailed = setFailed12; + exports2.isDebug = isDebug5; + exports2.debug = debug6; + exports2.error = error3; + exports2.warning = warning14; + exports2.notice = notice; + exports2.info = info8; + exports2.startGroup = startGroup3; + exports2.endGroup = endGroup3; + exports2.group = group; + exports2.saveState = saveState3; + exports2.getState = getState3; + exports2.getIDToken = getIDToken; + var command_1 = require_command(); + var file_command_1 = require_file_command(); + var utils_1 = require_utils(); + var os8 = __importStar2(require("os")); + var path30 = __importStar2(require("path")); + var oidc_utils_1 = require_oidc_utils(); + var ExitCode; + (function(ExitCode2) { + ExitCode2[ExitCode2["Success"] = 0] = "Success"; + ExitCode2[ExitCode2["Failure"] = 1] = "Failure"; + })(ExitCode || (exports2.ExitCode = ExitCode = {})); + function exportVariable2(name, val) { + const convertedVal = (0, utils_1.toCommandValue)(val); + process.env[name] = convertedVal; + const filePath = process.env["GITHUB_ENV"] || ""; + if (filePath) { + return (0, file_command_1.issueFileCommand)("ENV", (0, file_command_1.prepareKeyValueMessage)(name, val)); + } + (0, command_1.issueCommand)("set-env", { name }, convertedVal); + } + function setSecret2(secret) { + (0, command_1.issueCommand)("add-mask", {}, secret); + } + function addPath2(inputPath) { + const filePath = process.env["GITHUB_PATH"] || ""; + if (filePath) { + (0, file_command_1.issueFileCommand)("PATH", inputPath); } else { (0, command_1.issueCommand)("add-path", {}, inputPath); } @@ -21727,7 +29438,7 @@ Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); if (filePath) { return (0, file_command_1.issueFileCommand)("OUTPUT", (0, file_command_1.prepareKeyValueMessage)(name, value)); } - process.stdout.write(os7.EOL); + process.stdout.write(os8.EOL); (0, command_1.issueCommand)("set-output", { name }, (0, utils_1.toCommandValue)(value)); } function setCommandEcho(enabled) { @@ -21753,22 +29464,22 @@ Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); (0, command_1.issueCommand)("notice", (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } function info8(message) { - process.stdout.write(message + os7.EOL); + process.stdout.write(message + os8.EOL); } - function startGroup4(name) { + function startGroup3(name) { (0, command_1.issue)("group", name); } - function endGroup4() { + function endGroup3() { (0, command_1.issue)("endgroup"); } function group(name, fn) { return __awaiter2(this, void 0, void 0, function* () { - startGroup4(name); + startGroup3(name); let result; try { result = yield fn(); } finally { - endGroup4(); + endGroup3(); } return result; }); @@ -21823,7 +29534,7 @@ var require_context = __commonJS({ * Hydrate the context from the environment */ constructor() { - var _a2, _b, _c; + var _a6, _b2, _c2; this.payload = {}; if (process.env.GITHUB_EVENT_PATH) { if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { @@ -21843,9 +29554,9 @@ var require_context = __commonJS({ this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10); this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); - this.apiUrl = (_a2 = process.env.GITHUB_API_URL) !== null && _a2 !== void 0 ? _a2 : `https://api.github.com`; - this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; - this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; + this.apiUrl = (_a6 = process.env.GITHUB_API_URL) !== null && _a6 !== void 0 ? _a6 : `https://api.github.com`; + this.serverUrl = (_b2 = process.env.GITHUB_SERVER_URL) !== null && _b2 !== void 0 ? _b2 : `https://github.com`; + this.graphqlUrl = (_c2 = process.env.GITHUB_GRAPHQL_URL) !== null && _c2 !== void 0 ? _c2 : `https://api.github.com/graphql`; } get issue() { const payload = this.payload; @@ -21912,11 +29623,11 @@ var require_utils3 = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -21932,7 +29643,7 @@ var require_utils3 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -22275,23 +29986,23 @@ function getValues(context5, operator, key, modifier) { }); } } else { - const tmp = []; + const tmp2 = []; if (Array.isArray(value)) { value.filter(isDefined).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); + tmp2.push(encodeValue(operator, value2)); }); } else { Object.keys(value).forEach(function(k) { if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); + tmp2.push(encodeUnreserved(k)); + tmp2.push(encodeValue(operator, value[k].toString())); } }); } if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); + result.push(encodeUnreserved(key) + "=" + tmp2.join(",")); + } else if (tmp2.length !== 0) { + result.push(tmp2.join(",")); } } } @@ -22326,8 +30037,8 @@ function expand(template, context5) { expression = expression.substr(1); } expression.split(/,/g).forEach(function(variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context5, operator, tmp[1], tmp[2] || tmp[3])); + var tmp2 = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context5, operator, tmp2[1], tmp2[2] || tmp2[3])); }); if (operator && operator !== "+") { var separator = ","; @@ -22465,134 +30176,112 @@ var init_universal_user_agent3 = __esm({ }); // node_modules/content-type/dist/index.js -var require_dist = __commonJS({ - "node_modules/content-type/dist/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.format = format; - exports2.parse = parse3; - var TEXT_REGEXP = /^[\u0009\u0020-\u007e\u0080-\u00ff]*$/; - var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; - var QUOTE_REGEXP = /[\\"]/g; - var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; - var NullObject = /* @__PURE__ */ (() => { - const C = function() { - }; - C.prototype = /* @__PURE__ */ Object.create(null); - return C; - })(); - function format(obj) { - const { type, parameters } = obj; - if (!type || !TYPE_REGEXP.test(type)) { - throw new TypeError(`Invalid type: ${type}`); - } - let result = type; - if (parameters) { - for (const param of Object.keys(parameters)) { - if (!TOKEN_REGEXP.test(param)) { - throw new TypeError(`Invalid parameter name: ${param}`); - } - result += `; ${param}=${qstring(parameters[param])}`; - } - } - return result; - } - function parse3(header, options) { - const len = header.length; - let index2 = skipOWS(header, 0, len); - const valueStart = index2; - index2 = skipValue(header, index2, len); - const valueEnd = trailingOWS(header, valueStart, index2); - const type = header.slice(valueStart, valueEnd).toLowerCase(); - const parameters = options?.parameters === false ? new NullObject() : parseParameters(header, index2, len); - return { type, parameters }; - } - var SP = 32; - var HTAB = 9; - var SEMI = 59; - var EQ = 61; - var DQUOTE = 34; - var BSLASH = 92; - function parseParameters(header, index2, len) { - const parameters = new NullObject(); - parameter: while (index2 < len) { +function parse2(header, options) { + const stopChar = options?.comma === true ? COMMA : 65536; + const len = header.length; + let index2 = skipOWS(header, options?.start ?? 0, len); + const valueStart = index2; + index2 = skipValue(header, index2, len, stopChar); + const valueEnd = trailingOWS(header, valueStart, index2); + const type = header.slice(valueStart, valueEnd).toLowerCase(); + if (options?.parameters === false) { + return { type, index: index2, parameters: new NullObject() }; + } + return parseParameters(header, type, index2, len, stopChar); +} +function parseParameters(header, type, index2, len, stopChar) { + const parameters = new NullObject(); + parameter: while (index2 < len) { + if (header.charCodeAt(index2) === stopChar) + break; + index2 = skipOWS(header, index2 + 1, len); + const keyStart = index2; + while (index2 < len) { + const code = header.charCodeAt(index2); + if (code === stopChar) + break parameter; + if (code === SEMI) + continue parameter; + if (code === EQ) { + const keyEnd = trailingOWS(header, keyStart, index2); + const key = header.slice(keyStart, keyEnd).toLowerCase(); index2 = skipOWS(header, index2 + 1, len); - const keyStart = index2; - while (index2 < len) { - const code = header.charCodeAt(index2); - if (code === SEMI) - continue parameter; - if (code === EQ) { - const keyEnd = trailingOWS(header, keyStart, index2); - const key = header.slice(keyStart, keyEnd).toLowerCase(); - index2 = skipOWS(header, index2 + 1, len); - if (index2 < len && header.charCodeAt(index2) === DQUOTE) { - index2++; - let value = ""; - while (index2 < len) { - const code2 = header.charCodeAt(index2++); - if (code2 === DQUOTE) { - index2 = skipValue(header, index2, len); - if (parameters[key] === void 0) - parameters[key] = value; - break; - } - if (code2 === BSLASH && index2 < len) { - value += header[index2++]; - continue; - } - value += String.fromCharCode(code2); - } - continue parameter; + if (index2 < len && header.charCodeAt(index2) === DQUOTE) { + index2++; + let value = ""; + while (index2 < len) { + const code2 = header.charCodeAt(index2++); + if (code2 === DQUOTE) { + index2 = skipValue(header, index2, len, stopChar); + if (parameters[key] === void 0) + parameters[key] = value; + break; } - const valueStart = index2; - index2 = skipValue(header, index2, len); - if (parameters[key] === void 0) { - const valueEnd = trailingOWS(header, valueStart, index2); - parameters[key] = header.slice(valueStart, valueEnd); + if (code2 === BSLASH && index2 < len) { + value += header[index2++]; + continue; } - continue parameter; + value += String.fromCharCode(code2); } - index2++; + continue parameter; } + const valueStart = index2; + index2 = skipValue(header, index2, len, stopChar); + if (parameters[key] === void 0) { + const valueEnd = trailingOWS(header, valueStart, index2); + parameters[key] = header.slice(valueStart, valueEnd); + } + continue parameter; } - return parameters; - } - function skipValue(str, index2, len) { - while (index2 < len) { - const char = str.charCodeAt(index2); - if (char === SEMI) - break; - index2++; - } - return index2; - } - function skipOWS(header, index2, len) { - while (index2 < len) { - const char = header.charCodeAt(index2); - if (char !== SP && char !== HTAB) - break; - index2++; - } - return index2; - } - function trailingOWS(header, start, end) { - while (end > start) { - const char = header.charCodeAt(end - 1); - if (char !== SP && char !== HTAB) - break; - end--; - } - return end; - } - function qstring(str) { - if (TOKEN_REGEXP.test(str)) - return str; - if (TEXT_REGEXP.test(str)) - return `"${str.replace(QUOTE_REGEXP, "\\$&")}"`; - throw new TypeError(`Invalid parameter value: ${str}`); + index2++; } } + return { type, index: index2, parameters }; +} +function skipValue(str, index2, len, stopChar) { + while (index2 < len) { + const code = str.charCodeAt(index2); + if (code === SEMI || code === stopChar) + break; + index2++; + } + return index2; +} +function skipOWS(header, index2, len) { + while (index2 < len) { + const char = header.charCodeAt(index2); + if (char !== SP && char !== HTAB) + break; + index2++; + } + return index2; +} +function trailingOWS(header, start, end) { + while (end > start) { + const char = header.charCodeAt(end - 1); + if (char !== SP && char !== HTAB) + break; + end--; + } + return end; +} +var NullObject, SP, HTAB, SEMI, EQ, DQUOTE, BSLASH, COMMA; +var init_dist = __esm({ + "node_modules/content-type/dist/index.js"() { + NullObject = /* @__PURE__ */ (() => { + const C = function() { + }; + C.prototype = /* @__PURE__ */ Object.create(null); + return C; + })(); + SP = 32; + HTAB = 9; + SEMI = 59; + EQ = 61; + DQUOTE = 34; + BSLASH = 92; + COMMA = 44; + } }); // node_modules/json-with-bigint/json-with-bigint.js @@ -22618,8 +30307,8 @@ var init_json_with_bigint = __esm({ const isFunctionReplacer = typeof replacer === "function"; const propertyList = Array.isArray(replacer) ? new Set(replacer.map(String)) : null; const prepareVal = (parent, key, val) => { - const isObject2 = val !== null && typeof val === "object"; - const hasToJSON = isObject2 && typeof val.toJSON === "function"; + const isObject4 = val !== null && typeof val === "object"; + const hasToJSON = isObject4 && typeof val.toJSON === "function"; if (hasToJSON) { val = val.toJSON(key); } @@ -22842,9 +30531,9 @@ var init_json_with_bigint = __esm({ }; JSONParseV2 = (text, reviver) => { return JSON.parse(text, (key, value, context5) => { - const isNumber2 = typeof value === "number"; + const isNumber3 = typeof value === "number"; const isOutOfBounds = value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER; - const isBigNumber = isNumber2 && isOutOfBounds; + const isBigNumber = isNumber3 && isOutOfBounds; const isInt = context5 && intRegex.test(context5.source); const isBigInt = isBigNumber && isInt; if (isBigInt) return BigInt(context5.source); @@ -22855,7 +30544,7 @@ var init_json_with_bigint = __esm({ }; MAX_INT = Number.MAX_SAFE_INTEGER.toString(); MAX_DIGITS = MAX_INT.length; - stringsOrLargeNumbers = /"(?:\\.|[^"])*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g; + stringsOrLargeNumbers = /"(?:[^"\\]|\\.)*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g; noiseValueWithQuotes = /^"-?\d+n+"$/; applyReviverIteratively = (parsed, userReviver) => { const rootHolder = { "": parsed }; @@ -23091,7 +30780,7 @@ async function getResponseData(response) { if (!contentType) { return response.text().catch(noop); } - const mimetype = (0, import_content_type.parse)(contentType); + const mimetype = parse2(contentType); if (isJSONResponse(mimetype)) { let text = ""; try { @@ -23152,15 +30841,15 @@ function withDefaults2(oldEndpoint, newDefaults) { defaults: withDefaults2.bind(null, endpoint2) }); } -var import_content_type, VERSION2, defaults_default, noop, request; +var VERSION2, defaults_default, noop, request; var init_dist_bundle2 = __esm({ "node_modules/@octokit/request/dist-bundle/index.js"() { init_dist_bundle(); init_universal_user_agent3(); - import_content_type = __toESM(require_dist(), 1); + init_dist(); init_json_with_bigint(); init_dist_src(); - VERSION2 = "10.0.13"; + VERSION2 = "10.0.16"; defaults_default = { headers: { "user-agent": `octokit-request.js/${VERSION2} ${getUserAgent3()}` @@ -23357,7 +31046,7 @@ var init_dist_bundle4 = __esm({ var VERSION4; var init_version = __esm({ "node_modules/@octokit/core/dist-src/version.js"() { - VERSION4 = "7.0.7"; + VERSION4 = "7.0.8"; } }); @@ -23366,20 +31055,20 @@ var dist_src_exports = {}; __export(dist_src_exports, { Octokit: () => Octokit }); -function createLogger(logger = {}) { - if (typeof logger.debug !== "function") { - logger.debug = noop2; +function createLogger(logger2 = {}) { + if (typeof logger2.debug !== "function") { + logger2.debug = noop2; } - if (typeof logger.info !== "function") { - logger.info = noop2; + if (typeof logger2.info !== "function") { + logger2.info = noop2; } - if (typeof logger.warn !== "function") { - logger.warn = consoleWarn; + if (typeof logger2.warn !== "function") { + logger2.warn = consoleWarn; } - if (typeof logger.error !== "function") { - logger.error = consoleError; + if (typeof logger2.error !== "function") { + logger2.error = consoleError; } - return logger; + return logger2; } var noop2, consoleWarn, consoleError, userAgentTrail, Octokit; var init_dist_src2 = __esm({ @@ -23510,18 +31199,18 @@ var init_dist_src2 = __esm({ } }); -// node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js +// node_modules/@actions/github/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js var VERSION5; var init_version2 = __esm({ - "node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js"() { + "node_modules/@actions/github/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js"() { VERSION5 = "17.0.0"; } }); -// node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js +// node_modules/@actions/github/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js var Endpoints, endpoints_default; var init_endpoints = __esm({ - "node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js"() { + "node_modules/@actions/github/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js"() { Endpoints = { actions: { addCustomLabelsToSelfHostedRunnerForOrg: [ @@ -25815,7 +33504,7 @@ var init_endpoints = __esm({ } }); -// node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js +// node_modules/@actions/github/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js function endpointsToMethods(octokit) { const newMethods = {}; for (const scope of endpointMethodsMap.keys()) { @@ -25866,7 +33555,7 @@ function decorate(octokit, scope, methodName, defaults3, decorations) { } var endpointMethodsMap, handler; var init_endpoints_to_methods = __esm({ - "node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js"() { + "node_modules/@actions/github/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js"() { init_endpoints(); endpointMethodsMap = /* @__PURE__ */ new Map(); for (const [scope, endpoints] of Object.entries(endpoints_default)) { @@ -25944,7 +33633,7 @@ var init_endpoints_to_methods = __esm({ } }); -// node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js +// node_modules/@actions/github/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js var dist_src_exports2 = {}; __export(dist_src_exports2, { legacyRestEndpointMethods: () => legacyRestEndpointMethods, @@ -25964,7 +33653,7 @@ function legacyRestEndpointMethods(octokit) { }; } var init_dist_src3 = __esm({ - "node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js"() { + "node_modules/@actions/github/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js"() { init_version2(); init_endpoints_to_methods(); restEndpointMethods.VERSION = VERSION5; @@ -25972,7 +33661,7 @@ var init_dist_src3 = __esm({ } }); -// node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js +// node_modules/@actions/github/node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js var dist_bundle_exports = {}; __export(dist_bundle_exports, { composePaginateRest: () => composePaginateRest, @@ -26098,7 +33787,7 @@ function paginateRest(octokit) { } var VERSION6, composePaginateRest, paginatingEndpoints; var init_dist_bundle5 = __esm({ - "node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js"() { + "node_modules/@actions/github/node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js"() { VERSION6 = "0.0.0-development"; composePaginateRest = Object.assign(paginate, { iterator @@ -26423,7 +34112,7 @@ var require_utils4 = __commonJS({ })(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.GitHub = exports2.defaults = exports2.context = void 0; - exports2.getOctokitOptions = getOctokitOptions2; + exports2.getOctokitOptions = getOctokitOptions; var Context = __importStar2(require_context()); var Utils = __importStar2(require_utils3()); var core_1 = (init_dist_src2(), __toCommonJS(dist_src_exports)); @@ -26439,7 +34128,7 @@ var require_utils4 = __commonJS({ } }; exports2.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports2.defaults); - function getOctokitOptions2(token, options) { + function getOctokitOptions(token, options) { const opts = Object.assign({}, options || {}); const auth2 = Utils.getAuthString(token, opts); if (auth2) { @@ -26853,8 +34542,8 @@ var require_semver = __commonJS({ } // 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(release2, identifier, identifierBase) { - if (release2.startsWith("pre")) { + inc(release3, identifier, identifierBase) { + if (release3.startsWith("pre")) { if (!identifier && identifierBase === false) { throw new Error("invalid increment argument: identifier is empty"); } @@ -26865,7 +34554,7 @@ var require_semver = __commonJS({ } } } - switch (release2) { + switch (release3) { case "premajor": this.prerelease.length = 0; this.patch = 0; @@ -26957,7 +34646,7 @@ var require_semver = __commonJS({ break; } default: - throw new Error(`invalid increment argument: ${release2}`); + throw new Error(`invalid increment argument: ${release3}`); } this.raw = this.format(); if (this.build.length) { @@ -26975,7 +34664,7 @@ var require_parse2 = __commonJS({ "node_modules/semver/functions/parse.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); - var parse3 = (version, options, throwErrors = false) => { + var parse4 = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version; } @@ -26988,7 +34677,7 @@ var require_parse2 = __commonJS({ throw er; } }; - module2.exports = parse3; + module2.exports = parse4; } }); @@ -26996,9 +34685,9 @@ var require_parse2 = __commonJS({ var require_valid = __commonJS({ "node_modules/semver/functions/valid.js"(exports2, module2) { "use strict"; - var parse3 = require_parse2(); + var parse4 = require_parse2(); var valid4 = (version, options) => { - const v = parse3(version, options); + const v = parse4(version, options); return v ? v.version : null; }; module2.exports = valid4; @@ -27009,9 +34698,9 @@ var require_valid = __commonJS({ var require_clean = __commonJS({ "node_modules/semver/functions/clean.js"(exports2, module2) { "use strict"; - var parse3 = require_parse2(); + var parse4 = require_parse2(); var clean3 = (version, options) => { - const s = parse3(version.trim().replace(/^[=v]+/, ""), options); + const s = parse4(version.trim().replace(/^[=v]+/, ""), options); return s ? s.version : null; }; module2.exports = clean3; @@ -27023,7 +34712,7 @@ var require_inc = __commonJS({ "node_modules/semver/functions/inc.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); - var inc = (version, release2, options, identifier, identifierBase) => { + var inc = (version, release3, options, identifier, identifierBase) => { if (typeof options === "string") { identifierBase = identifier; identifier = options; @@ -27033,7 +34722,7 @@ var require_inc = __commonJS({ return new SemVer( version instanceof SemVer ? version.version : version, options - ).inc(release2, identifier, identifierBase).version; + ).inc(release3, identifier, identifierBase).version; } catch (er) { return null; } @@ -27046,10 +34735,10 @@ var require_inc = __commonJS({ var require_diff = __commonJS({ "node_modules/semver/functions/diff.js"(exports2, module2) { "use strict"; - var parse3 = require_parse2(); + var parse4 = require_parse2(); var diff = (version1, version2) => { - const v1 = parse3(version1, null, true); - const v2 = parse3(version2, null, true); + const v1 = parse4(version1, null, true); + const v2 = parse4(version2, null, true); const comparison = v1.compare(v2); if (comparison === 0) { return null; @@ -27120,9 +34809,9 @@ var require_patch = __commonJS({ var require_prerelease = __commonJS({ "node_modules/semver/functions/prerelease.js"(exports2, module2) { "use strict"; - var parse3 = require_parse2(); + var parse4 = require_parse2(); var prerelease = (version, options) => { - const parsed = parse3(version, options); + const parsed = parse4(version, options); return parsed && parsed.prerelease.length ? parsed.prerelease : null; }; module2.exports = prerelease; @@ -27308,9 +34997,9 @@ var require_coerce = __commonJS({ "node_modules/semver/functions/coerce.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); - var parse3 = require_parse2(); + var parse4 = require_parse2(); var { safeRe: re, t } = require_re(); - var coerce3 = (version, options) => { + var coerce4 = (version, options) => { if (version instanceof SemVer) { return version; } @@ -27343,9 +35032,9 @@ var require_coerce = __commonJS({ const patch = match2[4] || "0"; const prerelease = options.includePrerelease && match2[5] ? `-${match2[5]}` : ""; const build2 = options.includePrerelease && match2[6] ? `+${match2[6]}` : ""; - return parse3(`${major}.${minor}.${patch}${prerelease}${build2}`, options); + return parse4(`${major}.${minor}.${patch}${prerelease}${build2}`, options); }; - module2.exports = coerce3; + module2.exports = coerce4; } }); @@ -27353,7 +35042,7 @@ var require_coerce = __commonJS({ var require_truncate = __commonJS({ "node_modules/semver/functions/truncate.js"(exports2, module2) { "use strict"; - var parse3 = require_parse2(); + var parse4 = require_parse2(); var constants = require_constants6(); var SemVer = require_semver(); var truncate = (version, truncation, options) => { @@ -27365,7 +35054,7 @@ var require_truncate = __commonJS({ }; var cloneInputVersion = (version, options) => { const versionStringToParse = version instanceof SemVer ? version.version : version; - return parse3(versionStringToParse, options); + return parse4(versionStringToParse, options); }; var doTruncation = (version, truncation) => { if (isPrerelease(truncation)) { @@ -28409,7 +36098,7 @@ var require_semver2 = __commonJS({ var constants = require_constants6(); var SemVer = require_semver(); var identifiers = require_identifiers(); - var parse3 = require_parse2(); + var parse4 = require_parse2(); var valid4 = require_valid(); var clean3 = require_clean(); var inc = require_inc(); @@ -28431,7 +36120,7 @@ var require_semver2 = __commonJS({ var gte7 = require_gte(); var lte2 = require_lte(); var cmp = require_cmp(); - var coerce3 = require_coerce(); + var coerce4 = require_coerce(); var truncate = require_truncate(); var Comparator = require_comparator(); var Range2 = require_range(); @@ -28448,7 +36137,7 @@ var require_semver2 = __commonJS({ var simplifyRange = require_simplify(); var subset = require_subset(); module2.exports = { - parse: parse3, + parse: parse4, valid: valid4, clean: clean3, inc, @@ -28470,7 +36159,7 @@ var require_semver2 = __commonJS({ gte: gte7, lte: lte2, cmp, - coerce: coerce3, + coerce: coerce4, truncate, Comparator, Range: Range2, @@ -28616,8 +36305,8 @@ var require_light = __commonJS({ var DLList_1 = DLList; var Events; Events = class Events { - constructor(instance) { - this.instance = instance; + constructor(instance8) { + this.instance = instance8; this._events = {}; if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) { throw new Error("An Emitter already exists for this object"); @@ -28652,7 +36341,7 @@ var require_light = __commonJS({ } } async trigger(name, ...args) { - var e, promises6; + var e, promises7; try { if (name !== "debug") { this.trigger("debug", `Event triggered: ${name}`, args); @@ -28663,7 +36352,7 @@ var require_light = __commonJS({ this._events[name] = this._events[name].filter(function(listener) { return listener.status !== "none"; }); - promises6 = this._events[name].map(async (listener) => { + promises7 = this._events[name].map(async (listener) => { var e2, returned; if (listener.status === "none") { return; @@ -28686,7 +36375,7 @@ var require_light = __commonJS({ return null; } }); - return (await Promise.all(promises6)).find(function(x) { + return (await Promise.all(promises7)).find(function(x) { return x != null; }); } catch (error3) { @@ -28899,8 +36588,8 @@ var require_light = __commonJS({ parser$2 = parser; BottleneckError$2 = BottleneckError_1; LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; + constructor(instance8, storeOptions, storeInstanceOptions) { + this.instance = instance8; this.storeOptions = storeOptions; this.clientId = this.instance._randomIndex(); parser$2.load(storeInstanceOptions, storeInstanceOptions, this); @@ -28951,8 +36640,8 @@ var require_light = __commonJS({ return this.Promise.resolve(); } yieldLoop(t = 0) { - return new this.Promise(function(resolve14, reject) { - return setTimeout(resolve14, t); + return new this.Promise(function(resolve15, reject) { + return setTimeout(resolve15, t); }); } computePenalty() { @@ -29163,15 +36852,15 @@ var require_light = __commonJS({ return this._queue.length === 0; } async _tryToRun() { - var args, cb, error3, reject, resolve14, returned, task; + var args, cb, error3, reject, resolve15, returned, task; if (this._running < 1 && this._queue.length > 0) { this._running++; - ({ task, args, resolve: resolve14, reject } = this._queue.shift()); + ({ task, args, resolve: resolve15, reject } = this._queue.shift()); cb = await (async function() { try { returned = await task(...args); return function() { - return resolve14(returned); + return resolve15(returned); }; } catch (error1) { error3 = error1; @@ -29186,13 +36875,13 @@ var require_light = __commonJS({ } } schedule(task, ...args) { - var promise, reject, resolve14; - resolve14 = reject = null; + var promise, reject, resolve15; + resolve15 = reject = null; promise = new this.Promise(function(_resolve, _reject) { - resolve14 = _resolve; + resolve15 = _resolve; return reject = _reject; }); - this._queue.push({ task, args, resolve: resolve14, reject }); + this._queue.push({ task, args, resolve: resolve15, reject }); this._tryToRun(); return promise; } @@ -29248,16 +36937,16 @@ var require_light = __commonJS({ })(); } async deleteKey(key = "") { - var deleted, instance; - instance = this.instances[key]; + var deleted, instance8; + instance8 = this.instances[key]; if (this.connection) { deleted = await this.connection.__runCommand__(["del", ...Scripts$1.allKeys(`${this.id}-${key}`)]); } - if (instance != null) { + if (instance8 != null) { delete this.instances[key]; - await instance.disconnect(); + await instance8.disconnect(); } - return instance != null || deleted > 0; + return instance8 != null || deleted > 0; } limiters() { var k, ref, results, v; @@ -29593,14 +37282,14 @@ var require_light = __commonJS({ counts = this._states.counts; return counts[0] + counts[1] + counts[2] + counts[3] === at; }; - return new this.Promise((resolve14, reject) => { + return new this.Promise((resolve15, reject) => { if (finished()) { - return resolve14(); + return resolve15(); } else { return this.on("done", () => { if (finished()) { this.removeAllListeners("done"); - return resolve14(); + return resolve15(); } }); } @@ -29693,9 +37382,9 @@ var require_light = __commonJS({ options = parser$5.load(options, this.jobDefaults); } task = (...args2) => { - return new this.Promise(function(resolve14, reject) { + return new this.Promise(function(resolve15, reject) { return fn(...args2, function(...args3) { - return (args3[0] != null ? reject : resolve14)(args3); + return (args3[0] != null ? reject : resolve15)(args3); }); }); }; @@ -29821,7 +37510,7 @@ var require_light = __commonJS({ var require_helpers = __commonJS({ "node_modules/jsonschema/lib/helpers.js"(exports2, module2) { "use strict"; - var ValidationError = exports2.ValidationError = function ValidationError2(message, instance, schema, path30, name, argument) { + var ValidationError = exports2.ValidationError = function ValidationError2(message, instance8, schema, path30, name, argument) { if (Array.isArray(path30)) { this.path = path30; this.property = path30.reduce(function(sum, item) { @@ -29837,8 +37526,8 @@ var require_helpers = __commonJS({ var id = schema.$id || schema.id; this.schema = id || schema; } - if (instance !== void 0) { - this.instance = instance; + if (instance8 !== void 0) { + this.instance = instance8; } this.name = name; this.argument = argument; @@ -29847,8 +37536,8 @@ var require_helpers = __commonJS({ ValidationError.prototype.toString = function toString2() { return this.property + " " + this.message; }; - var ValidatorResult = exports2.ValidatorResult = function ValidatorResult2(instance, schema, options, ctx) { - this.instance = instance; + var ValidatorResult = exports2.ValidatorResult = function ValidatorResult2(instance8, schema, options, ctx) { + this.instance = instance8; this.schema = schema; this.options = options; this.path = ctx.path; @@ -29935,7 +37624,7 @@ var require_helpers = __commonJS({ this.base = base; this.schemas = schemas; }; - SchemaContext.prototype.resolve = function resolve14(target) { + SchemaContext.prototype.resolve = function resolve15(target) { return (() => resolveUrl(this.base, target))(); }; SchemaContext.prototype.makeChild = function makeChild(schema, propertyName) { @@ -30170,13 +37859,13 @@ var require_attribute = __commonJS({ "extends": true }; var validators = attribute.validators = {}; - validators.type = function validateType(instance, schema, options, ctx) { - if (instance === void 0) { + validators.type = function validateType(instance8, schema, options, ctx) { + if (instance8 === void 0) { return null; } - var result = new ValidatorResult(instance, schema, options, ctx); + var result = new ValidatorResult(instance8, schema, options, ctx); var types2 = Array.isArray(schema.type) ? schema.type : [schema.type]; - if (!types2.some(this.testType.bind(this, instance, schema, options, ctx))) { + if (!types2.some(this.testType.bind(this, instance8, schema, options, ctx))) { var list = types2.map(function(v) { if (!v) return; var id = v.$id || v.id; @@ -30190,12 +37879,12 @@ var require_attribute = __commonJS({ } return result; }; - function testSchemaNoThrow(instance, options, ctx, callback, schema) { + function testSchemaNoThrow(instance8, options, ctx, callback, schema) { var throwError2 = options.throwError; var throwAll = options.throwAll; options.throwError = false; options.throwAll = false; - var res = this.validateSchema(instance, schema, options, ctx); + var res = this.validateSchema(instance8, schema, options, ctx); options.throwError = throwError2; options.throwAll = throwAll; if (!res.valid && callback instanceof Function) { @@ -30203,19 +37892,19 @@ var require_attribute = __commonJS({ } return res.valid; } - validators.anyOf = function validateAnyOf(instance, schema, options, ctx) { - if (instance === void 0) { + validators.anyOf = function validateAnyOf(instance8, schema, options, ctx) { + if (instance8 === void 0) { return null; } - var result = new ValidatorResult(instance, schema, options, ctx); - var inner = new ValidatorResult(instance, schema, options, ctx); + var result = new ValidatorResult(instance8, schema, options, ctx); + var inner = new ValidatorResult(instance8, schema, options, ctx); if (!Array.isArray(schema.anyOf)) { throw new SchemaError("anyOf must be an array"); } if (!schema.anyOf.some( testSchemaNoThrow.bind( this, - instance, + instance8, options, ctx, function(res) { @@ -30239,17 +37928,17 @@ var require_attribute = __commonJS({ } return result; }; - validators.allOf = function validateAllOf(instance, schema, options, ctx) { - if (instance === void 0) { + validators.allOf = function validateAllOf(instance8, schema, options, ctx) { + if (instance8 === void 0) { return null; } if (!Array.isArray(schema.allOf)) { throw new SchemaError("allOf must be an array"); } - var result = new ValidatorResult(instance, schema, options, ctx); + var result = new ValidatorResult(instance8, schema, options, ctx); var self2 = this; schema.allOf.forEach(function(v, i) { - var valid4 = self2.validateSchema(instance, v, options, ctx); + var valid4 = self2.validateSchema(instance8, v, options, ctx); if (!valid4.valid) { var id = v.$id || v.id; var msg = id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]"; @@ -30263,19 +37952,19 @@ var require_attribute = __commonJS({ }); return result; }; - validators.oneOf = function validateOneOf(instance, schema, options, ctx) { - if (instance === void 0) { + validators.oneOf = function validateOneOf(instance8, schema, options, ctx) { + if (instance8 === void 0) { return null; } if (!Array.isArray(schema.oneOf)) { throw new SchemaError("oneOf must be an array"); } - var result = new ValidatorResult(instance, schema, options, ctx); - var inner = new ValidatorResult(instance, schema, options, ctx); + var result = new ValidatorResult(instance8, schema, options, ctx); + var inner = new ValidatorResult(instance8, schema, options, ctx); var count = schema.oneOf.filter( testSchemaNoThrow.bind( this, - instance, + instance8, options, ctx, function(res) { @@ -30299,21 +37988,21 @@ var require_attribute = __commonJS({ } return result; }; - validators.if = function validateIf(instance, schema, options, ctx) { - if (instance === void 0) return null; + validators.if = function validateIf(instance8, schema, options, ctx) { + if (instance8 === void 0) return null; if (!helpers.isSchema(schema.if)) throw new Error('Expected "if" keyword to be a schema'); - var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema.if); - var result = new ValidatorResult(instance, schema, options, ctx); + var ifValid = testSchemaNoThrow.call(this, instance8, options, ctx, null, schema.if); + var result = new ValidatorResult(instance8, schema, options, ctx); var res; if (ifValid) { if (schema.then === void 0) return; if (!helpers.isSchema(schema.then)) throw new Error('Expected "then" keyword to be a schema'); - res = this.validateSchema(instance, schema.then, options, ctx.makeChild(schema.then)); + res = this.validateSchema(instance8, schema.then, options, ctx.makeChild(schema.then)); result.importErrors(res); } else { if (schema.else === void 0) return; if (!helpers.isSchema(schema.else)) throw new Error('Expected "else" keyword to be a schema'); - res = this.validateSchema(instance, schema.else, options, ctx.makeChild(schema.else)); + res = this.validateSchema(instance8, schema.else, options, ctx.makeChild(schema.else)); result.importErrors(res); } return result; @@ -30325,22 +38014,22 @@ var require_attribute = __commonJS({ if (Object.propertyIsEnumerable.call(object2, key)) return object2[key]; } } - validators.propertyNames = function validatePropertyNames(instance, schema, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); + validators.propertyNames = function validatePropertyNames(instance8, schema, options, ctx) { + if (!this.types.object(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); var subschema = schema.propertyNames !== void 0 ? schema.propertyNames : {}; if (!helpers.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)'); - for (var property in instance) { - if (getEnumerableProperty(instance, property) !== void 0) { + for (var property in instance8) { + if (getEnumerableProperty(instance8, property) !== void 0) { var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema)); result.importErrors(res); } } return result; }; - validators.properties = function validateProperties(instance, schema, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); + validators.properties = function validateProperties(instance8, schema, options, ctx) { + if (!this.types.object(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); var properties = schema.properties || {}; for (var property in properties) { var subschema = properties[property]; @@ -30350,17 +38039,17 @@ var require_attribute = __commonJS({ throw new SchemaError('Unexpected null, expected schema in "properties"'); } if (typeof options.preValidateProperty == "function") { - options.preValidateProperty(instance, property, subschema, options, ctx); + options.preValidateProperty(instance8, property, subschema, options, ctx); } - var prop = getEnumerableProperty(instance, property); + var prop = getEnumerableProperty(instance8, property); var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property)); if (res.instance !== result.instance[property]) result.instance[property] = res.instance; result.importErrors(res); } return result; }; - function testAdditionalProperty(instance, schema, options, ctx, property, result) { - if (!this.types.object(instance)) return; + function testAdditionalProperty(instance8, schema, options, ctx, property, result) { + if (!this.types.object(instance8)) return; if (schema.properties && schema.properties[property] !== void 0) { return; } @@ -30373,18 +38062,18 @@ var require_attribute = __commonJS({ } else { var additionalProperties = schema.additionalProperties || {}; if (typeof options.preValidateProperty == "function") { - options.preValidateProperty(instance, property, additionalProperties, options, ctx); + options.preValidateProperty(instance8, property, additionalProperties, options, ctx); } - var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property)); + var res = this.validateSchema(instance8[property], additionalProperties, options, ctx.makeChild(additionalProperties, property)); if (res.instance !== result.instance[property]) result.instance[property] = res.instance; result.importErrors(res); } } - validators.patternProperties = function validatePatternProperties(instance, schema, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); + validators.patternProperties = function validatePatternProperties(instance8, schema, options, ctx) { + if (!this.types.object(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); var patternProperties = schema.patternProperties || {}; - for (var property in instance) { + for (var property in instance8) { var test = true; for (var pattern in patternProperties) { var subschema = patternProperties[pattern]; @@ -30395,7 +38084,7 @@ var require_attribute = __commonJS({ } try { var regexp = new RegExp(pattern, "u"); - } catch (_e) { + } catch (_e2) { regexp = new RegExp(pattern); } if (!regexp.test(property)) { @@ -30403,33 +38092,33 @@ var require_attribute = __commonJS({ } test = false; if (typeof options.preValidateProperty == "function") { - options.preValidateProperty(instance, property, subschema, options, ctx); + options.preValidateProperty(instance8, property, subschema, options, ctx); } - var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property)); + var res = this.validateSchema(instance8[property], subschema, options, ctx.makeChild(subschema, property)); if (res.instance !== result.instance[property]) result.instance[property] = res.instance; result.importErrors(res); } if (test) { - testAdditionalProperty.call(this, instance, schema, options, ctx, property, result); + testAdditionalProperty.call(this, instance8, schema, options, ctx, property, result); } } return result; }; - validators.additionalProperties = function validateAdditionalProperties(instance, schema, options, ctx) { - if (!this.types.object(instance)) return; + validators.additionalProperties = function validateAdditionalProperties(instance8, schema, options, ctx) { + if (!this.types.object(instance8)) return; if (schema.patternProperties) { return null; } - var result = new ValidatorResult(instance, schema, options, ctx); - for (var property in instance) { - testAdditionalProperty.call(this, instance, schema, options, ctx, property, result); + var result = new ValidatorResult(instance8, schema, options, ctx); + for (var property in instance8) { + testAdditionalProperty.call(this, instance8, schema, options, ctx, property, result); } return result; }; - validators.minProperties = function validateMinProperties(instance, schema, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var keys = Object.keys(instance); + validators.minProperties = function validateMinProperties(instance8, schema, options, ctx) { + if (!this.types.object(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); + var keys = Object.keys(instance8); if (!(keys.length >= schema.minProperties)) { result.addError({ name: "minProperties", @@ -30439,10 +38128,10 @@ var require_attribute = __commonJS({ } return result; }; - validators.maxProperties = function validateMaxProperties(instance, schema, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var keys = Object.keys(instance); + validators.maxProperties = function validateMaxProperties(instance8, schema, options, ctx) { + if (!this.types.object(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); + var keys = Object.keys(instance8); if (!(keys.length <= schema.maxProperties)) { result.addError({ name: "maxProperties", @@ -30452,12 +38141,12 @@ var require_attribute = __commonJS({ } return result; }; - validators.items = function validateItems(instance, schema, options, ctx) { + validators.items = function validateItems(instance8, schema, options, ctx) { var self2 = this; - if (!this.types.array(instance)) return; + if (!this.types.array(instance8)) return; if (schema.items === void 0) return; - var result = new ValidatorResult(instance, schema, options, ctx); - instance.every(function(value, i) { + var result = new ValidatorResult(instance8, schema, options, ctx); + instance8.every(function(value, i) { if (Array.isArray(schema.items)) { var items = schema.items[i] === void 0 ? schema.additionalItems : schema.items[i]; } else { @@ -30480,13 +38169,13 @@ var require_attribute = __commonJS({ }); return result; }; - validators.contains = function validateContains(instance, schema, options, ctx) { + validators.contains = function validateContains(instance8, schema, options, ctx) { var self2 = this; - if (!this.types.array(instance)) return; + if (!this.types.array(instance8)) return; if (schema.contains === void 0) return; if (!helpers.isSchema(schema.contains)) throw new Error('Expected "contains" keyword to be a schema'); - var result = new ValidatorResult(instance, schema, options, ctx); - var count = instance.some(function(value, i) { + var result = new ValidatorResult(instance8, schema, options, ctx); + var count = instance8.some(function(value, i) { var res = self2.validateSchema(value, schema.contains, options, ctx.makeChild(schema.contains, i)); return res.errors.length === 0; }); @@ -30499,11 +38188,11 @@ var require_attribute = __commonJS({ } return result; }; - validators.minimum = function validateMinimum(instance, schema, options, ctx) { - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); + validators.minimum = function validateMinimum(instance8, schema, options, ctx) { + if (!this.types.number(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); if (schema.exclusiveMinimum && schema.exclusiveMinimum === true) { - if (!(instance > schema.minimum)) { + if (!(instance8 > schema.minimum)) { result.addError({ name: "minimum", argument: schema.minimum, @@ -30511,7 +38200,7 @@ var require_attribute = __commonJS({ }); } } else { - if (!(instance >= schema.minimum)) { + if (!(instance8 >= schema.minimum)) { result.addError({ name: "minimum", argument: schema.minimum, @@ -30521,11 +38210,11 @@ var require_attribute = __commonJS({ } return result; }; - validators.maximum = function validateMaximum(instance, schema, options, ctx) { - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); + validators.maximum = function validateMaximum(instance8, schema, options, ctx) { + if (!this.types.number(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); if (schema.exclusiveMaximum && schema.exclusiveMaximum === true) { - if (!(instance < schema.maximum)) { + if (!(instance8 < schema.maximum)) { result.addError({ name: "maximum", argument: schema.maximum, @@ -30533,7 +38222,7 @@ var require_attribute = __commonJS({ }); } } else { - if (!(instance <= schema.maximum)) { + if (!(instance8 <= schema.maximum)) { result.addError({ name: "maximum", argument: schema.maximum, @@ -30543,11 +38232,11 @@ var require_attribute = __commonJS({ } return result; }; - validators.exclusiveMinimum = function validateExclusiveMinimum(instance, schema, options, ctx) { + validators.exclusiveMinimum = function validateExclusiveMinimum(instance8, schema, options, ctx) { if (typeof schema.exclusiveMinimum === "boolean") return; - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var valid4 = instance > schema.exclusiveMinimum; + if (!this.types.number(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); + var valid4 = instance8 > schema.exclusiveMinimum; if (!valid4) { result.addError({ name: "exclusiveMinimum", @@ -30557,11 +38246,11 @@ var require_attribute = __commonJS({ } return result; }; - validators.exclusiveMaximum = function validateExclusiveMaximum(instance, schema, options, ctx) { + validators.exclusiveMaximum = function validateExclusiveMaximum(instance8, schema, options, ctx) { if (typeof schema.exclusiveMaximum === "boolean") return; - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var valid4 = instance < schema.exclusiveMaximum; + if (!this.types.number(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); + var valid4 = instance8 < schema.exclusiveMaximum; if (!valid4) { result.addError({ name: "exclusiveMaximum", @@ -30571,18 +38260,18 @@ var require_attribute = __commonJS({ } return result; }; - var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy2(instance, schema, options, ctx, validationType, errorMessage) { - if (!this.types.number(instance)) return; + var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy2(instance8, schema, options, ctx, validationType, errorMessage) { + if (!this.types.number(instance8)) return; var validationArgument = schema[validationType]; if (validationArgument == 0) { throw new SchemaError(validationType + " cannot be zero"); } - var result = new ValidatorResult(instance, schema, options, ctx); - var instanceDecimals = helpers.getDecimalPlaces(instance); + var result = new ValidatorResult(instance8, schema, options, ctx); + var instanceDecimals = helpers.getDecimalPlaces(instance8); var divisorDecimals = helpers.getDecimalPlaces(validationArgument); var maxDecimals = Math.max(instanceDecimals, divisorDecimals); var multiplier = Math.pow(10, maxDecimals); - if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) { + if (Math.round(instance8 * multiplier) % Math.round(validationArgument * multiplier) !== 0) { result.addError({ name: validationType, argument: validationArgument, @@ -30591,22 +38280,22 @@ var require_attribute = __commonJS({ } return result; }; - validators.multipleOf = function validateMultipleOf(instance, schema, options, ctx) { - return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "multipleOf", "is not a multiple of (divisible by) "); + validators.multipleOf = function validateMultipleOf(instance8, schema, options, ctx) { + return validateMultipleOfOrDivisbleBy.call(this, instance8, schema, options, ctx, "multipleOf", "is not a multiple of (divisible by) "); }; - validators.divisibleBy = function validateDivisibleBy(instance, schema, options, ctx) { - return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "divisibleBy", "is not divisible by (multiple of) "); + validators.divisibleBy = function validateDivisibleBy(instance8, schema, options, ctx) { + return validateMultipleOfOrDivisbleBy.call(this, instance8, schema, options, ctx, "divisibleBy", "is not divisible by (multiple of) "); }; - validators.required = function validateRequired(instance, schema, options, ctx) { - var result = new ValidatorResult(instance, schema, options, ctx); - if (instance === void 0 && schema.required === true) { + validators.required = function validateRequired(instance8, schema, options, ctx) { + var result = new ValidatorResult(instance8, schema, options, ctx); + if (instance8 === void 0 && schema.required === true) { result.addError({ name: "required", message: "is required" }); - } else if (this.types.object(instance) && Array.isArray(schema.required)) { + } else if (this.types.object(instance8) && Array.isArray(schema.required)) { schema.required.forEach(function(n) { - if (getEnumerableProperty(instance, n) === void 0) { + if (getEnumerableProperty(instance8, n) === void 0) { result.addError({ name: "required", argument: n, @@ -30617,16 +38306,16 @@ var require_attribute = __commonJS({ } return result; }; - validators.pattern = function validatePattern(instance, schema, options, ctx) { - if (!this.types.string(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); + validators.pattern = function validatePattern(instance8, schema, options, ctx) { + if (!this.types.string(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); var pattern = schema.pattern; try { var regexp = new RegExp(pattern, "u"); - } catch (_e) { + } catch (_e2) { regexp = new RegExp(pattern); } - if (!instance.match(regexp)) { + if (!instance8.match(regexp)) { result.addError({ name: "pattern", argument: schema.pattern, @@ -30635,10 +38324,10 @@ var require_attribute = __commonJS({ } return result; }; - validators.format = function validateFormat(instance, schema, options, ctx) { - if (instance === void 0) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (!result.disableFormat && !helpers.isFormat(instance, schema.format, this)) { + validators.format = function validateFormat(instance8, schema, options, ctx) { + if (instance8 === void 0) return; + var result = new ValidatorResult(instance8, schema, options, ctx); + if (!result.disableFormat && !helpers.isFormat(instance8, schema.format, this)) { result.addError({ name: "format", argument: schema.format, @@ -30647,11 +38336,11 @@ var require_attribute = __commonJS({ } return result; }; - validators.minLength = function validateMinLength(instance, schema, options, ctx) { - if (!this.types.string(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var hsp = instance.match(/[\uDC00-\uDFFF]/g); - var length = instance.length - (hsp ? hsp.length : 0); + validators.minLength = function validateMinLength(instance8, schema, options, ctx) { + if (!this.types.string(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); + var hsp = instance8.match(/[\uDC00-\uDFFF]/g); + var length = instance8.length - (hsp ? hsp.length : 0); if (!(length >= schema.minLength)) { result.addError({ name: "minLength", @@ -30661,11 +38350,11 @@ var require_attribute = __commonJS({ } return result; }; - validators.maxLength = function validateMaxLength(instance, schema, options, ctx) { - if (!this.types.string(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var hsp = instance.match(/[\uDC00-\uDFFF]/g); - var length = instance.length - (hsp ? hsp.length : 0); + validators.maxLength = function validateMaxLength(instance8, schema, options, ctx) { + if (!this.types.string(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); + var hsp = instance8.match(/[\uDC00-\uDFFF]/g); + var length = instance8.length - (hsp ? hsp.length : 0); if (!(length <= schema.maxLength)) { result.addError({ name: "maxLength", @@ -30675,10 +38364,10 @@ var require_attribute = __commonJS({ } return result; }; - validators.minItems = function validateMinItems(instance, schema, options, ctx) { - if (!this.types.array(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (!(instance.length >= schema.minItems)) { + validators.minItems = function validateMinItems(instance8, schema, options, ctx) { + if (!this.types.array(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); + if (!(instance8.length >= schema.minItems)) { result.addError({ name: "minItems", argument: schema.minItems, @@ -30687,10 +38376,10 @@ var require_attribute = __commonJS({ } return result; }; - validators.maxItems = function validateMaxItems(instance, schema, options, ctx) { - if (!this.types.array(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (!(instance.length <= schema.maxItems)) { + validators.maxItems = function validateMaxItems(instance8, schema, options, ctx) { + if (!this.types.array(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); + if (!(instance8.length <= schema.maxItems)) { result.addError({ name: "maxItems", argument: schema.maxItems, @@ -30708,11 +38397,11 @@ var require_attribute = __commonJS({ } return true; } - validators.uniqueItems = function validateUniqueItems(instance, schema, options, ctx) { + validators.uniqueItems = function validateUniqueItems(instance8, schema, options, ctx) { if (schema.uniqueItems !== true) return; - if (!this.types.array(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (!instance.every(testArrays)) { + if (!this.types.array(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); + if (!instance8.every(testArrays)) { result.addError({ name: "uniqueItems", message: "contains duplicate item" @@ -30720,11 +38409,11 @@ var require_attribute = __commonJS({ } return result; }; - validators.dependencies = function validateDependencies(instance, schema, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); + validators.dependencies = function validateDependencies(instance8, schema, options, ctx) { + if (!this.types.object(instance8)) return; + var result = new ValidatorResult(instance8, schema, options, ctx); for (var property in schema.dependencies) { - if (instance[property] === void 0) { + if (instance8[property] === void 0) { continue; } var dep = schema.dependencies[property]; @@ -30734,7 +38423,7 @@ var require_attribute = __commonJS({ } if (Array.isArray(dep)) { dep.forEach(function(prop) { - if (instance[prop] === void 0) { + if (instance8[prop] === void 0) { result.addError({ // FIXME there's two different "dependencies" errors here with slightly different outputs // Can we make these the same? Or should we create different error types? @@ -30745,7 +38434,7 @@ var require_attribute = __commonJS({ } }); } else { - var res = this.validateSchema(instance, dep, options, childContext); + var res = this.validateSchema(instance8, dep, options, childContext); if (result.instance !== res.instance) result.instance = res.instance; if (res && res.errors.length) { result.addError({ @@ -30759,15 +38448,15 @@ var require_attribute = __commonJS({ } return result; }; - validators["enum"] = function validateEnum(instance, schema, options, ctx) { - if (instance === void 0) { + validators["enum"] = function validateEnum(instance8, schema, options, ctx) { + if (instance8 === void 0) { return null; } if (!Array.isArray(schema["enum"])) { throw new SchemaError("enum expects an array", schema); } - var result = new ValidatorResult(instance, schema, options, ctx); - if (!schema["enum"].some(helpers.deepCompareStrict.bind(null, instance))) { + var result = new ValidatorResult(instance8, schema, options, ctx); + if (!schema["enum"].some(helpers.deepCompareStrict.bind(null, instance8))) { result.addError({ name: "enum", argument: schema["enum"], @@ -30776,12 +38465,12 @@ var require_attribute = __commonJS({ } return result; }; - validators["const"] = function validateEnum(instance, schema, options, ctx) { - if (instance === void 0) { + validators["const"] = function validateEnum(instance8, schema, options, ctx) { + if (instance8 === void 0) { return null; } - var result = new ValidatorResult(instance, schema, options, ctx); - if (!helpers.deepCompareStrict(schema["const"], instance)) { + var result = new ValidatorResult(instance8, schema, options, ctx); + if (!helpers.deepCompareStrict(schema["const"], instance8)) { result.addError({ name: "const", argument: schema["const"], @@ -30790,15 +38479,15 @@ var require_attribute = __commonJS({ } return result; }; - validators.not = validators.disallow = function validateNot(instance, schema, options, ctx) { + validators.not = validators.disallow = function validateNot(instance8, schema, options, ctx) { var self2 = this; - if (instance === void 0) return null; - var result = new ValidatorResult(instance, schema, options, ctx); + if (instance8 === void 0) return null; + var result = new ValidatorResult(instance8, schema, options, ctx); var notTypes = schema.not || schema.disallow; if (!notTypes) return null; if (!Array.isArray(notTypes)) notTypes = [notTypes]; notTypes.forEach(function(type) { - if (self2.testType(instance, schema, options, ctx, type)) { + if (self2.testType(instance8, schema, options, ctx, type)) { var id = type && (type.$id || type.id); var schemaId = id || type; result.addError({ @@ -30942,7 +38631,7 @@ var require_validator = __commonJS({ Validator3.prototype.getSchema = function getSchema(urn) { return this.schemas[urn]; }; - Validator3.prototype.validate = function validate2(instance, schema, options, ctx) { + Validator3.prototype.validate = function validate2(instance8, schema, options, ctx) { if (typeof schema !== "boolean" && typeof schema !== "object" || schema === null) { throw new SchemaError("Expected `schema` to be an object or boolean"); } @@ -30962,12 +38651,12 @@ var require_validator = __commonJS({ ctx.schemas[n] = sch; } } - if (options.required && instance === void 0) { - var result = new ValidatorResult(instance, schema, options, ctx); + if (options.required && instance8 === void 0) { + var result = new ValidatorResult(instance8, schema, options, ctx); result.addError("is required, but is undefined"); return result; } - var result = this.validateSchema(instance, schema, options, ctx); + var result = this.validateSchema(instance8, schema, options, ctx); if (!result) { throw new Error("Result undefined"); } else if (options.throwAll && result.errors.length) { @@ -30980,8 +38669,8 @@ var require_validator = __commonJS({ if (typeof ref == "string") return ref; return false; } - Validator3.prototype.validateSchema = function validateSchema2(instance, schema, options, ctx) { - var result = new ValidatorResult(instance, schema, options, ctx); + Validator3.prototype.validateSchema = function validateSchema2(instance8, schema, options, ctx) { + var result = new ValidatorResult(instance8, schema, options, ctx); if (typeof schema === "boolean") { if (schema === true) { schema = {}; @@ -31007,7 +38696,7 @@ var require_validator = __commonJS({ if (switchSchema) { var resolved = this.resolve(schema, switchSchema, ctx); var subctx = new SchemaContext(resolved.subschema, options, ctx.path, resolved.switchSchema, ctx.schemas); - return this.validateSchema(instance, resolved.subschema, options, subctx); + return this.validateSchema(instance8, resolved.subschema, options, subctx); } var skipAttributes = options && options.skipAttributes || []; for (var key in schema) { @@ -31015,7 +38704,7 @@ var require_validator = __commonJS({ var validatorErr = null; var validator = this.attributes[key]; if (validator) { - validatorErr = validator.call(this, instance, schema, options, ctx); + validatorErr = validator.call(this, instance8, schema, options, ctx); } else if (options.allowUnknownAttributes === false) { throw new SchemaError("Unsupported attribute: " + key, schema); } @@ -31025,7 +38714,7 @@ var require_validator = __commonJS({ } } if (typeof options.rewrite == "function") { - var value = options.rewrite.call(this, instance, schema, options, ctx); + var value = options.rewrite.call(this, instance8, schema, options, ctx); result.instance = value; } return result; @@ -31040,7 +38729,7 @@ var require_validator = __commonJS({ } return schema; }; - Validator3.prototype.resolve = function resolve14(schema, switchSchema, ctx) { + Validator3.prototype.resolve = function resolve15(schema, switchSchema, ctx) { switchSchema = ctx.resolve(switchSchema); if (ctx.schemas[switchSchema]) { return { subschema: ctx.schemas[switchSchema], switchSchema }; @@ -31057,48 +38746,48 @@ var require_validator = __commonJS({ } return { subschema, switchSchema }; }; - Validator3.prototype.testType = function validateType(instance, schema, options, ctx, type) { + Validator3.prototype.testType = function validateType(instance8, schema, options, ctx, type) { if (type === void 0) { return; } else if (type === null) { throw new SchemaError('Unexpected null in "type" keyword'); } if (typeof this.types[type] == "function") { - return this.types[type].call(this, instance); + return this.types[type].call(this, instance8); } if (type && typeof type == "object") { - var res = this.validateSchema(instance, type, options, ctx); + var res = this.validateSchema(instance8, type, options, ctx); return res === void 0 || !(res && res.errors.length); } return true; }; var types2 = Validator3.prototype.types = {}; - types2.string = function testString(instance) { - return typeof instance == "string"; + types2.string = function testString(instance8) { + return typeof instance8 == "string"; }; - types2.number = function testNumber(instance) { - return typeof instance == "number" && isFinite(instance); + types2.number = function testNumber(instance8) { + return typeof instance8 == "number" && isFinite(instance8); }; - types2.integer = function testInteger(instance) { - return typeof instance == "number" && instance % 1 === 0; + types2.integer = function testInteger(instance8) { + return typeof instance8 == "number" && instance8 % 1 === 0; }; - types2.boolean = function testBoolean(instance) { - return typeof instance == "boolean"; + types2.boolean = function testBoolean(instance8) { + return typeof instance8 == "boolean"; }; - types2.array = function testArray(instance) { - return Array.isArray(instance); + types2.array = function testArray(instance8) { + return Array.isArray(instance8); }; - types2["null"] = function testNull(instance) { - return instance === null; + types2["null"] = function testNull(instance8) { + return instance8 === null; }; - types2.date = function testDate(instance) { - return instance instanceof Date; + types2.date = function testDate(instance8) { + return instance8 instanceof Date; }; - types2.any = function testAny(instance) { + types2.any = function testAny(instance8) { return true; }; - types2.object = function testObject(instance) { - return instance && typeof instance === "object" && !Array.isArray(instance) && !(instance instanceof Date); + types2.object = function testObject(instance8) { + return instance8 && typeof instance8 === "object" && !Array.isArray(instance8) && !(instance8 instanceof Date); }; module2.exports = Validator3; } @@ -31115,9 +38804,9 @@ var require_lib2 = __commonJS({ module2.exports.SchemaError = require_helpers().SchemaError; module2.exports.SchemaScanResult = require_scan().SchemaScanResult; module2.exports.scan = require_scan().scan; - module2.exports.validate = function(instance, schema, options) { + module2.exports.validate = function(instance8, schema, options) { var v = new Validator3(); - return v.validate(instance, schema, options); + return v.validate(instance8, schema, options); }; } }); @@ -31316,7 +39005,7 @@ var require_internal_glob_options_helper = __commonJS({ })(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getOptions = getOptions; - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); function getOptions(copy) { const result = { followSymbolicLinks: true, @@ -31328,23 +39017,23 @@ var require_internal_glob_options_helper = __commonJS({ if (copy) { if (typeof copy.followSymbolicLinks === "boolean") { result.followSymbolicLinks = copy.followSymbolicLinks; - core31.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); + core29.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); } if (typeof copy.implicitDescendants === "boolean") { result.implicitDescendants = copy.implicitDescendants; - core31.debug(`implicitDescendants '${result.implicitDescendants}'`); + core29.debug(`implicitDescendants '${result.implicitDescendants}'`); } if (typeof copy.matchDirectories === "boolean") { result.matchDirectories = copy.matchDirectories; - core31.debug(`matchDirectories '${result.matchDirectories}'`); + core29.debug(`matchDirectories '${result.matchDirectories}'`); } if (typeof copy.omitBrokenSymbolicLinks === "boolean") { result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; - core31.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); + core29.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); } if (typeof copy.excludeHiddenFiles === "boolean") { result.excludeHiddenFiles = copy.excludeHiddenFiles; - core31.debug(`excludeHiddenFiles '${result.excludeHiddenFiles}'`); + core29.debug(`excludeHiddenFiles '${result.excludeHiddenFiles}'`); } } return result; @@ -31694,6 +39383,8 @@ var require_brace_expansion = __commonJS({ var escPeriod2 = "\0PERIOD" + Math.random() + "\0"; var EXPANSION_MAX2 = 1e5; var EXPANSION_MAX_LENGTH2 = 4e6; + var EXPANSION_MAX_DEPTH2 = 1e3; + var EXPANSION_MAX_REWRITES2 = 1e3; function numeric2(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } @@ -31703,25 +39394,36 @@ var require_brace_expansion = __commonJS({ function unescapeBraces2(str) { return str.split(escSlash2).join("\\").split(escOpen2).join("{").split(escClose2).join("}").split(escComma2).join(",").split(escPeriod2).join("."); } + function pushAll2(target, items) { + for (var i = 0; i < items.length; i++) { + target.push(items[i]); + } + } function parseCommaParts2(str) { - if (!str) - return [""]; var parts = []; - var m = balanced2("{", "}", 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 = parseCommaParts2(post); - if (post.length) { - p[p.length - 1] += postParts.shift(); - p.push.apply(p, postParts); - } - parts.push.apply(parts, p); - return parts; + var carry = ""; + for (; ; ) { + var m = balanced2("{", "}", str); + if (!m) { + var tail = str.split(","); + tail[0] = carry + tail[0]; + pushAll2(parts, tail); + return parts; + } + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(","); + p[0] = carry + p[0]; + p[p.length - 1] += "{" + body + "}"; + if (!post.length) { + pushAll2(parts, p); + return parts; + } + carry = p.pop(); + pushAll2(parts, p); + str = post; + } } function expandTop(str, options) { if (!str) @@ -31729,10 +39431,12 @@ var require_brace_expansion = __commonJS({ options = options || {}; var max = options.max == null ? EXPANSION_MAX2 : options.max; var maxLength = options.maxLength == null ? EXPANSION_MAX_LENGTH2 : options.maxLength; + var maxDepth = options.maxDepth == null ? EXPANSION_MAX_DEPTH2 : options.maxDepth; + var maxRewrites = options.maxRewrites == null ? EXPANSION_MAX_REWRITES2 : options.maxRewrites; if (str.substr(0, 2) === "{}") { str = "\\{\\}" + str.substr(2); } - return expand3(escapeBraces2(str), max, maxLength, true).map(unescapeBraces2); + return expand3(escapeBraces2(str), max, maxLength, maxDepth, 0, maxRewrites, true).map(unescapeBraces2); } function embrace2(str) { return "{" + str + "}"; @@ -31807,9 +39511,13 @@ var require_brace_expansion = __commonJS({ } return N; } - function expand3(str, max, maxLength, isTop) { + function expand3(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { + if (depth > maxDepth) { + return [str]; + } var acc = [""]; var accBase = [0]; + var rewrites = 0; var dropEmpties = false; var firstGroup = true; var nextBase; @@ -31827,7 +39535,8 @@ var require_brace_expansion = __commonJS({ var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { - if (m.post.match(/,(?!,).*\}/)) { + if (rewrites < maxRewrites && m.post.match(/,(?!,).*\}/)) { + rewrites++; str = m.pre + "{" + m.body + escClose2 + m.post; isTop = true; firstGroup = true; @@ -31859,7 +39568,7 @@ var require_brace_expansion = __commonJS({ } else { var n = parseCommaParts2(m.body); if (n.length === 1 && n[0] !== void 0) { - n = expand3(n[0], max, maxLength, false).map(embrace2); + n = expand3(n[0], max, maxLength, maxDepth, depth + 1, maxRewrites, false).map(embrace2); if (n.length === 1) { nextBase = []; acc = combine2( @@ -31887,7 +39596,7 @@ var require_brace_expansion = __commonJS({ values = []; var valuesLength = 0; outer: for (var j = 0; j < n.length; j++) { - var expanded = expand3(n[j], max, maxLength, false); + var expanded = expand3(n[j], max, maxLength, maxDepth, depth + 1, maxRewrites, false); for (var k = 0; k < expanded.length; k++) { var v = expanded[k]; if (dropsEmpties && !v) continue; @@ -32111,9 +39820,9 @@ var require_minimatch = __commonJS({ throw new TypeError("pattern is too long"); } }; - Minimatch2.prototype.parse = parse3; + Minimatch2.prototype.parse = parse4; var SUBPARSE = {}; - function parse3(pattern, isSub) { + function parse4(pattern, isSub) { assertValidPattern2(pattern); var options = this.options; if (pattern === "**") { @@ -32748,7 +40457,7 @@ var require_internal_pattern = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Pattern = void 0; - var os7 = __importStar2(require("os")); + var os8 = __importStar2(require("os")); var path30 = __importStar2(require("path")); var pathHelper = __importStar2(require_internal_path_helper()); var assert_1 = __importDefault2(require("assert")); @@ -32841,7 +40550,7 @@ var require_internal_pattern = __commonJS({ if (pattern === "." || pattern.startsWith(`.${path30.sep}`)) { pattern = _Pattern.globEscape(process.cwd()) + pattern.substr(1); } else if (pattern === "~" || pattern.startsWith(`~${path30.sep}`)) { - homedir2 = homedir2 || os7.homedir(); + homedir2 = homedir2 || os8.homedir(); (0, assert_1.default)(homedir2, "Unable to determine HOME directory"); (0, assert_1.default)(pathHelper.hasAbsoluteRoot(homedir2), `Expected HOME directory to be a rooted path. Actual '${homedir2}'`); pattern = _Pattern.globEscape(homedir2) + pattern.substr(1); @@ -32976,11 +40685,11 @@ var require_internal_globber = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -32996,7 +40705,7 @@ var require_internal_globber = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -33009,14 +40718,14 @@ var require_internal_globber = __commonJS({ }, i); function verb(n) { i[n] = o[n] && function(v) { - return new Promise(function(resolve14, reject) { - v = o[n](v), settle(resolve14, reject, v.done, v.value); + return new Promise(function(resolve15, reject) { + v = o[n](v), settle(resolve15, reject, v.done, v.value); }); }; } - function settle(resolve14, reject, d, v) { + function settle(resolve15, reject, d, v) { Promise.resolve(v).then(function(v2) { - resolve14({ value: v2, done: d }); + resolve15({ value: v2, done: d }); }, reject); } }; @@ -33066,8 +40775,8 @@ var require_internal_globber = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DefaultGlobber = void 0; - var core31 = __importStar2(require_core()); - var fs32 = __importStar2(require("fs")); + var core29 = __importStar2(require_core()); + var fs34 = __importStar2(require("fs")); var globOptionsHelper = __importStar2(require_internal_glob_options_helper()); var path30 = __importStar2(require("path")); var patternHelper = __importStar2(require_internal_pattern_helper()); @@ -33086,20 +40795,20 @@ var require_internal_globber = __commonJS({ } glob() { return __awaiter2(this, void 0, void 0, function* () { - var _a2, e_1, _b, _c; + var _a6, e_1, _b2, _c2; const result = []; try { - for (var _d = true, _e = __asyncValues2(this.globGenerator()), _f; _f = yield _e.next(), _a2 = _f.done, !_a2; _d = true) { - _c = _f.value; - _d = false; - const itemPath = _c; + for (var _d2 = true, _e2 = __asyncValues2(this.globGenerator()), _f2; _f2 = yield _e2.next(), _a6 = _f2.done, !_a6; _d2 = true) { + _c2 = _f2.value; + _d2 = false; + const itemPath = _c2; result.push(itemPath); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { - if (!_d && !_a2 && (_b = _e.return)) yield _b.call(_e); + if (!_d2 && !_a6 && (_b2 = _e2.return)) yield _b2.call(_e2); } finally { if (e_1) throw e_1.error; } @@ -33119,9 +40828,9 @@ var require_internal_globber = __commonJS({ } const stack = []; for (const searchPath of patternHelper.getSearchPaths(patterns)) { - core31.debug(`Search path '${searchPath}'`); + core29.debug(`Search path '${searchPath}'`); try { - yield __await2(fs32.promises.lstat(searchPath)); + yield __await2(fs34.promises.lstat(searchPath)); } catch (err) { if (err.code === "ENOENT") { continue; @@ -33155,7 +40864,7 @@ var require_internal_globber = __commonJS({ continue; } const childLevel = item.level + 1; - const childItems = (yield __await2(fs32.promises.readdir(item.path))).map((x) => new internal_search_state_1.SearchState(path30.join(item.path, x), childLevel)); + const childItems = (yield __await2(fs34.promises.readdir(item.path))).map((x) => new internal_search_state_1.SearchState(path30.join(item.path, x), childLevel)); stack.push(...childItems.reverse()); } else if (match2 & internal_match_kind_1.MatchKind.File) { yield yield __await2(item.path); @@ -33190,11 +40899,11 @@ var require_internal_globber = __commonJS({ let stats; if (options.followSymbolicLinks) { try { - stats = yield fs32.promises.stat(item.path); + stats = yield fs34.promises.stat(item.path); } catch (err) { if (err.code === "ENOENT") { if (options.omitBrokenSymbolicLinks) { - core31.debug(`Broken symlink '${item.path}'`); + core29.debug(`Broken symlink '${item.path}'`); return void 0; } throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); @@ -33202,15 +40911,15 @@ var require_internal_globber = __commonJS({ throw err; } } else { - stats = yield fs32.promises.lstat(item.path); + stats = yield fs34.promises.lstat(item.path); } if (stats.isDirectory() && options.followSymbolicLinks) { - const realPath = yield fs32.promises.realpath(item.path); + const realPath = yield fs34.promises.realpath(item.path); while (traversalChain.length >= item.level) { traversalChain.pop(); } if (traversalChain.some((x) => x === realPath)) { - core31.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); + core29.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); return void 0; } traversalChain.push(realPath); @@ -33266,11 +40975,11 @@ var require_internal_hash_files = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -33286,7 +40995,7 @@ var require_internal_hash_files = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -33299,51 +41008,51 @@ var require_internal_hash_files = __commonJS({ }, i); function verb(n) { i[n] = o[n] && function(v) { - return new Promise(function(resolve14, reject) { - v = o[n](v), settle(resolve14, reject, v.done, v.value); + return new Promise(function(resolve15, reject) { + v = o[n](v), settle(resolve15, reject, v.done, v.value); }); }; } - function settle(resolve14, reject, d, v) { + function settle(resolve15, reject, d, v) { Promise.resolve(v).then(function(v2) { - resolve14({ value: v2, done: d }); + resolve15({ value: v2, done: d }); }, reject); } }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.hashFiles = hashFiles2; var crypto3 = __importStar2(require("crypto")); - var core31 = __importStar2(require_core()); - var fs32 = __importStar2(require("fs")); + var core29 = __importStar2(require_core()); + var fs34 = __importStar2(require("fs")); var stream2 = __importStar2(require("stream")); - var util3 = __importStar2(require("util")); + var util4 = __importStar2(require("util")); var path30 = __importStar2(require("path")); function hashFiles2(globber_1, currentWorkspace_1) { return __awaiter2(this, arguments, void 0, function* (globber, currentWorkspace, verbose = false) { - var _a2, e_1, _b, _c; - var _d; - const writeDelegate = verbose ? core31.info : core31.debug; + var _a6, e_1, _b2, _c2; + var _d2; + const writeDelegate = verbose ? core29.info : core29.debug; let hasMatch = false; - const githubWorkspace = currentWorkspace ? currentWorkspace : (_d = process.env["GITHUB_WORKSPACE"]) !== null && _d !== void 0 ? _d : process.cwd(); + const githubWorkspace = currentWorkspace ? currentWorkspace : (_d2 = process.env["GITHUB_WORKSPACE"]) !== null && _d2 !== void 0 ? _d2 : process.cwd(); const result = crypto3.createHash("sha256"); let count = 0; try { - for (var _e = true, _f = __asyncValues2(globber.globGenerator()), _g; _g = yield _f.next(), _a2 = _g.done, !_a2; _e = true) { - _c = _g.value; - _e = false; - const file = _c; + for (var _e2 = true, _f2 = __asyncValues2(globber.globGenerator()), _g2; _g2 = yield _f2.next(), _a6 = _g2.done, !_a6; _e2 = true) { + _c2 = _g2.value; + _e2 = false; + const file = _c2; writeDelegate(file); if (!file.startsWith(`${githubWorkspace}${path30.sep}`)) { writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`); continue; } - if (fs32.statSync(file).isDirectory()) { + if (fs34.statSync(file).isDirectory()) { writeDelegate(`Skip directory '${file}'.`); continue; } const hash2 = crypto3.createHash("sha256"); - const pipeline2 = util3.promisify(stream2.pipeline); - yield pipeline2(fs32.createReadStream(file), hash2); + const pipeline2 = util4.promisify(stream2.pipeline); + yield pipeline2(fs34.createReadStream(file), hash2); result.write(hash2.digest()); count++; if (!hasMatch) { @@ -33354,7 +41063,7 @@ var require_internal_hash_files = __commonJS({ e_1 = { error: e_1_1 }; } finally { try { - if (!_e && !_a2 && (_b = _f.return)) yield _b.call(_f); + if (!_e2 && !_a6 && (_b2 = _f2.return)) yield _b2.call(_f2); } finally { if (e_1) throw e_1.error; } @@ -33378,11 +41087,11 @@ var require_glob = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -33398,7 +41107,7 @@ var require_glob = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -33563,8 +41272,8 @@ var require_semver3 = __commonJS({ } } var i; - exports2.parse = parse3; - function parse3(version, options) { + exports2.parse = parse4; + function parse4(version, options) { if (!options || typeof options !== "object") { options = { loose: !!options, @@ -33592,12 +41301,12 @@ var require_semver3 = __commonJS({ } exports2.valid = valid4; function valid4(version, options) { - var v = parse3(version, options); + var v = parse4(version, options); return v ? v.version : null; } exports2.clean = clean3; function clean3(version, options) { - var s = parse3(version.trim().replace(/^[=v]+/, ""), options); + var s = parse4(version.trim().replace(/^[=v]+/, ""), options); return s ? s.version : null; } exports2.SemVer = SemVer; @@ -33733,8 +41442,8 @@ var require_semver3 = __commonJS({ } } while (++i2); }; - SemVer.prototype.inc = function(release2, identifier) { - switch (release2) { + SemVer.prototype.inc = function(release3, identifier) { + switch (release3) { case "premajor": this.prerelease.length = 0; this.patch = 0; @@ -33810,20 +41519,20 @@ var require_semver3 = __commonJS({ } break; default: - throw new Error("invalid increment argument: " + release2); + throw new Error("invalid increment argument: " + release3); } this.format(); this.raw = this.version; return this; }; exports2.inc = inc; - function inc(version, release2, loose, identifier) { + function inc(version, release3, loose, identifier) { if (typeof loose === "string") { identifier = loose; loose = void 0; } try { - return new SemVer(version, loose).inc(release2, identifier).version; + return new SemVer(version, loose).inc(release3, identifier).version; } catch (er) { return null; } @@ -33833,8 +41542,8 @@ var require_semver3 = __commonJS({ if (eq(version1, version2)) { return null; } else { - var v1 = parse3(version1); - var v2 = parse3(version2); + var v1 = parse4(version1); + var v2 = parse4(version2); var prefix = ""; if (v1.prerelease.length || v2.prerelease.length) { prefix = "pre"; @@ -34540,7 +42249,7 @@ var require_semver3 = __commonJS({ } exports2.prerelease = prerelease; function prerelease(version, options) { - var parsed = parse3(version, options); + var parsed = parse4(version, options); return parsed && parsed.prerelease.length ? parsed.prerelease : null; } exports2.intersects = intersects; @@ -34549,8 +42258,8 @@ var require_semver3 = __commonJS({ r2 = new Range2(r2, options); return r1.intersects(r2); } - exports2.coerce = coerce3; - function coerce3(version, options) { + exports2.coerce = coerce4; + function coerce4(version, options) { if (version instanceof SemVer) { return version; } @@ -34577,7 +42286,7 @@ var require_semver3 = __commonJS({ if (match2 === null) { return null; } - return parse3(match2[2] + "." + (match2[3] || "0") + "." + (match2[4] || "0"), options); + return parse4(match2[2] + "." + (match2[3] || "0") + "." + (match2[4] || "0"), options); } } }); @@ -34659,11 +42368,11 @@ var require_cacheUtils = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -34679,7 +42388,7 @@ var require_cacheUtils = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -34692,14 +42401,14 @@ var require_cacheUtils = __commonJS({ }, i); function verb(n) { i[n] = o[n] && function(v) { - return new Promise(function(resolve14, reject) { - v = o[n](v), settle(resolve14, reject, v.done, v.value); + return new Promise(function(resolve15, reject) { + v = o[n](v), settle(resolve15, reject, v.done, v.value); }); }; } - function settle(resolve14, reject, d, v) { + function settle(resolve15, reject, d, v) { Promise.resolve(v).then(function(v2) { - resolve14({ value: v2, done: d }); + resolve15({ value: v2, done: d }); }, reject); } }; @@ -34714,15 +42423,15 @@ var require_cacheUtils = __commonJS({ exports2.assertDefined = assertDefined; exports2.getCacheVersion = getCacheVersion; exports2.getRuntimeToken = getRuntimeToken; - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); var exec3 = __importStar2(require_exec()); var glob2 = __importStar2(require_glob()); - var io9 = __importStar2(require_io()); + var io10 = __importStar2(require_io()); var crypto3 = __importStar2(require("crypto")); - var fs32 = __importStar2(require("fs")); + var fs34 = __importStar2(require("fs")); var path30 = __importStar2(require("path")); - var semver11 = __importStar2(require_semver3()); - var util3 = __importStar2(require("util")); + var semver13 = __importStar2(require_semver3()); + var util4 = __importStar2(require("util")); var constants_1 = require_constants7(); var versionSalt = "1.0"; function createTempDirectory() { @@ -34743,29 +42452,29 @@ var require_cacheUtils = __commonJS({ tempDirectory = path30.join(baseLocation, "actions", "temp"); } const dest = path30.join(tempDirectory, crypto3.randomUUID()); - yield io9.mkdirP(dest); + yield io10.mkdirP(dest); return dest; }); } function getArchiveFileSizeInBytes(filePath) { - return fs32.statSync(filePath).size; + return fs34.statSync(filePath).size; } function resolvePaths(patterns) { return __awaiter2(this, void 0, void 0, function* () { - var _a2, e_1, _b, _c; - var _d; + var _a6, e_1, _b2, _c2; + var _d2; const paths = []; - const workspace = (_d = process.env["GITHUB_WORKSPACE"]) !== null && _d !== void 0 ? _d : process.cwd(); + const workspace = (_d2 = process.env["GITHUB_WORKSPACE"]) !== null && _d2 !== void 0 ? _d2 : process.cwd(); const globber = yield glob2.create(patterns.join("\n"), { implicitDescendants: false }); try { - for (var _e = true, _f = __asyncValues2(globber.globGenerator()), _g; _g = yield _f.next(), _a2 = _g.done, !_a2; _e = true) { - _c = _g.value; - _e = false; - const file = _c; + for (var _e2 = true, _f2 = __asyncValues2(globber.globGenerator()), _g2; _g2 = yield _f2.next(), _a6 = _g2.done, !_a6; _e2 = true) { + _c2 = _g2.value; + _e2 = false; + const file = _c2; const relativeFile = path30.relative(workspace, file).replace(new RegExp(`\\${path30.sep}`, "g"), "/"); - core31.debug(`Matched: ${relativeFile}`); + core29.debug(`Matched: ${relativeFile}`); if (relativeFile === "") { paths.push("."); } else { @@ -34776,7 +42485,7 @@ var require_cacheUtils = __commonJS({ e_1 = { error: e_1_1 }; } finally { try { - if (!_e && !_a2 && (_b = _f.return)) yield _b.call(_f); + if (!_e2 && !_a6 && (_b2 = _f2.return)) yield _b2.call(_f2); } finally { if (e_1) throw e_1.error; } @@ -34786,14 +42495,14 @@ var require_cacheUtils = __commonJS({ } function unlinkFile(filePath) { return __awaiter2(this, void 0, void 0, function* () { - return util3.promisify(fs32.unlink)(filePath); + return util4.promisify(fs34.unlink)(filePath); }); } function getVersion(app_1) { return __awaiter2(this, arguments, void 0, function* (app, additionalArgs = []) { let versionOutput = ""; additionalArgs.push("--version"); - core31.debug(`Checking ${app} ${additionalArgs.join(" ")}`); + core29.debug(`Checking ${app} ${additionalArgs.join(" ")}`); try { yield exec3.exec(`${app}`, additionalArgs, { ignoreReturnCode: true, @@ -34804,18 +42513,18 @@ var require_cacheUtils = __commonJS({ } }); } catch (err) { - core31.debug(err.message); + core29.debug(err.message); } versionOutput = versionOutput.trim(); - core31.debug(versionOutput); + core29.debug(versionOutput); return versionOutput; }); } function getCompressionMethod() { return __awaiter2(this, void 0, void 0, function* () { const versionOutput = yield getVersion("zstd", ["--quiet"]); - const version = semver11.clean(versionOutput); - core31.debug(`zstd version: ${version}`); + const version = semver13.clean(versionOutput); + core29.debug(`zstd version: ${version}`); if (versionOutput === "") { return constants_1.CompressionMethod.Gzip; } else { @@ -34828,11 +42537,11 @@ var require_cacheUtils = __commonJS({ } function getGnuTarPathOnWindows() { return __awaiter2(this, void 0, void 0, function* () { - if (fs32.existsSync(constants_1.GnuTarPathOnWindows)) { + if (fs34.existsSync(constants_1.GnuTarPathOnWindows)) { return constants_1.GnuTarPathOnWindows; } const versionOutput = yield getVersion("tar"); - return versionOutput.toLowerCase().includes("gnu tar") ? io9.which("tar") : ""; + return versionOutput.toLowerCase().includes("gnu tar") ? io10.which("tar") : ""; }); } function assertDefined(name, value) { @@ -34862,570 +42571,172 @@ var require_cacheUtils = __commonJS({ } }); -// node_modules/tslib/tslib.es6.mjs -var tslib_es6_exports = {}; -__export(tslib_es6_exports, { - __addDisposableResource: () => __addDisposableResource, - __assign: () => __assign, - __asyncDelegator: () => __asyncDelegator, - __asyncGenerator: () => __asyncGenerator, - __asyncValues: () => __asyncValues, - __await: () => __await, - __awaiter: () => __awaiter, - __classPrivateFieldGet: () => __classPrivateFieldGet, - __classPrivateFieldIn: () => __classPrivateFieldIn, - __classPrivateFieldSet: () => __classPrivateFieldSet, - __createBinding: () => __createBinding, - __decorate: () => __decorate, - __disposeResources: () => __disposeResources, - __esDecorate: () => __esDecorate, - __exportStar: () => __exportStar, - __extends: () => __extends, - __generator: () => __generator, - __importDefault: () => __importDefault, - __importStar: () => __importStar, - __makeTemplateObject: () => __makeTemplateObject, - __metadata: () => __metadata, - __param: () => __param, - __propKey: () => __propKey, - __read: () => __read, - __rest: () => __rest, - __rewriteRelativeImportExtension: () => __rewriteRelativeImportExtension, - __runInitializers: () => __runInitializers, - __setFunctionName: () => __setFunctionName, - __spread: () => __spread, - __spreadArray: () => __spreadArray, - __spreadArrays: () => __spreadArrays, - __values: () => __values2, - default: () => tslib_es6_default -}); -function __extends(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 __()); -} -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} -function __param(paramIndex, decorator) { - return function(target, key) { - decorator(target, key, paramIndex); - }; -} -function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); - return f; - } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _2, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context5 = {}; - for (var p in contextIn) context5[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context5.access[p] = contextIn.access[p]; - context5.addInitializer = function(f) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f || null)); - }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context5); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_2 = accept(result.get)) descriptor.get = _2; - if (_2 = accept(result.set)) descriptor.set = _2; - if (_2 = accept(result.init)) initializers.unshift(_2); - } else if (_2 = accept(result)) { - if (kind === "field") initializers.unshift(_2); - else descriptor[key] = _2; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; -} -function __runInitializers(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; -} -function __propKey(x) { - return typeof x === "symbol" ? x : "".concat(x); -} -function __setFunctionName(f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); -} -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); - }); - } - return new (P || (P = Promise))(function(resolve14, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} -function __generator(thisArg, body) { - var _2 = { label: 0, sent: function() { - if (t[0] & 1) throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); - return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { - return this; - }), g; - function verb(n) { - return function(v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_2 = 0)), _2) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _2.label++; - return { value: op[1], done: false }; - case 5: - _2.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _2.ops.pop(); - _2.trys.pop(); - continue; - default: - if (!(t = _2.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _2 = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _2.label = op[1]; - break; - } - if (op[0] === 6 && _2.label < t[1]) { - _2.label = t[1]; - t = op; - break; - } - if (t && _2.label < t[2]) { - _2.label = t[2]; - _2.ops.push(op); - break; - } - if (t[2]) _2.ops.pop(); - _2.trys.pop(); - continue; - } - op = body.call(thisArg, _2); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } -} -function __exportStar(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); -} -function __values2(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function() { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error3) { - e = { error: error3 }; - } finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally { - if (e) throw e.error; - } - } - return ar; -} -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -} -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { - return this; - }, i; - function awaitReturn(f) { - return function(v) { - return Promise.resolve(v).then(f, reject); - }; - } - function verb(n, f) { - if (g[n]) { - i[n] = function(v) { - return new Promise(function(a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - if (f) i[n] = f(i[n]); - } - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } -} -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function(e) { - throw e; - }), verb("return"), i[Symbol.iterator] = function() { - return this; - }, i; - function verb(n, f) { - i[n] = o[n] ? function(v) { - return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; - } : f; - } -} -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve14, reject) { - v = o[n](v), settle(resolve14, reject, v.done, v.value); - }); - }; - } - function settle(resolve14, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve14({ value: v2, done: d }); - }, reject); - } -} -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { value: raw }); - } else { - cooked.raw = raw; - } - return cooked; -} -function __importStar(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; -} -function __importDefault(mod) { - return mod && mod.__esModule ? mod : { default: mod }; -} -function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} -function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldIn(state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); -} -function __addDisposableResource(env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; - } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; - } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { - try { - inner.call(this); - } catch (e) { - return Promise.reject(e); - } +// node_modules/@typespec/ts-http-runtime/dist/commonjs/abort-controller/AbortError.js +var require_AbortError = __commonJS({ + "node_modules/@typespec/ts-http-runtime/dist/commonjs/abort-controller/AbortError.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); }; - env.stack.push({ value, dispose, async }); - } else if (async) { - env.stack.push({ async: true }); - } - return value; -} -function __disposeResources(env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { - fail(e); - return next(); - }); - } else s |= 1; - } catch (e) { - fail(e); + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; - } - return next(); -} -function __rewriteRelativeImportExtension(path30, preserveJsx) { - if (typeof path30 === "string" && /^\.\.?\//.test(path30)) { - return path30.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext2, cm) { - return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext2 || !cm) ? m : d + ext2 + "." + cm.toLowerCase() + "js"; - }); - } - return path30; -} -var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys, _SuppressedError, tslib_es6_default; -var init_tslib_es6 = __esm({ - "node_modules/tslib/tslib.es6.mjs"() { - extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { - d2.__proto__ = b2; - } || function(d2, b2) { - for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; - }; - return extendStatics(d, b); - }; - __assign = function() { - __assign = Object.assign || function __assign2(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); + return to; }; - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) 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 === void 0) k2 = k; - o[k2] = m[k]; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var AbortError_exports = {}; + __export2(AbortError_exports, { + AbortError: () => AbortError2 }); - __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error3, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error3, e.suppressed = suppressed, e; - }; - tslib_es6_default = { - __extends, - __assign, - __rest, - __decorate, - __param, - __esDecorate, - __runInitializers, - __propKey, - __setFunctionName, - __metadata, - __awaiter, - __generator, - __createBinding, - __exportStar, - __values: __values2, - __read, - __spread, - __spreadArrays, - __spreadArray, - __await, - __asyncGenerator, - __asyncDelegator, - __asyncValues, - __makeTemplateObject, - __importStar, - __importDefault, - __classPrivateFieldGet, - __classPrivateFieldSet, - __classPrivateFieldIn, - __addDisposableResource, - __disposeResources, - __rewriteRelativeImportExtension - }; - } -}); - -// node_modules/@typespec/ts-http-runtime/dist/commonjs/abort-controller/AbortError.js -var require_AbortError = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/abort-controller/AbortError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { + module2.exports = __toCommonJS2(AbortError_exports); + var AbortError2 = class extends Error { constructor(message) { super(message); this.name = "AbortError"; } }; - exports2.AbortError = AbortError; } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/logger/log.js var require_log = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/logger/log.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.log = log; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var node_os_1 = require("node:os"); - var node_util_1 = tslib_1.__importDefault(require("node:util")); - var node_process_1 = tslib_1.__importDefault(require("node:process")); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/logger/log.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var log_exports = {}; + __export2(log_exports, { + log: () => log + }); + module2.exports = __toCommonJS2(log_exports); + var import_node_os = require("node:os"); + var import_node_util = __toESM2(require("node:util")); + var import_node_process = __toESM2(require("node:process")); function log(message, ...args) { - node_process_1.default.stderr.write(`${node_util_1.default.format(message, ...args)}${node_os_1.EOL}`); + import_node_process.default.stderr.write(`${import_node_util.default.format(message, ...args)}${import_node_os.EOL}`); } } }); +// node_modules/@typespec/ts-http-runtime/dist/commonjs/env.js +var require_env = __commonJS({ + "node_modules/@typespec/ts-http-runtime/dist/commonjs/env.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var env_exports = {}; + __export2(env_exports, { + emitNodeWarning: () => emitNodeWarning, + getEnvironmentVariable: () => getEnvironmentVariable, + isBrowser: () => isBrowser2, + isBun: () => isBun2, + isDeno: () => isDeno2, + isNodeLike: () => isNodeLike2, + isNodeRuntime: () => isNodeRuntime2, + isReactNative: () => isReactNative2, + isWebWorker: () => isWebWorker2 + }); + module2.exports = __toCommonJS2(env_exports); + var import_node_process = __toESM2(require("node:process")); + function getEnvironmentVariable(name) { + return import_node_process.default.env[name]; + } + function emitNodeWarning(warning14) { + import_node_process.default.emitWarning(warning14); + } + var isBrowser2 = false; + var isWebWorker2 = false; + var isDeno2 = typeof import_node_process.default.versions.deno === "string" && import_node_process.default.versions.deno.length > 0; + var isBun2 = typeof import_node_process.default.versions.bun === "string" && import_node_process.default.versions.bun.length > 0; + var isNodeLike2 = true; + var isNodeRuntime2 = !isBun2 && !isDeno2; + var isReactNative2 = false; + } +}); + // node_modules/@typespec/ts-http-runtime/dist/commonjs/logger/debug.js var require_debug2 = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/logger/debug.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var log_js_1 = require_log(); - var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; + "node_modules/@typespec/ts-http-runtime/dist/commonjs/logger/debug.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var debug_exports = {}; + __export2(debug_exports, { + default: () => debug_default + }); + module2.exports = __toCommonJS2(debug_exports); + var import_log = require_log(); + var import_env = require_env(); + var debugEnvVariable = (0, import_env.getEnvironmentVariable)("DEBUG"); var enabledString; var enabledNamespaces = []; var skippedNamespaces = []; @@ -35433,14 +42744,17 @@ var require_debug2 = __commonJS({ if (debugEnvVariable) { enable(debugEnvVariable); } - var debugObj = Object.assign((namespace) => { - return createDebugger(namespace); - }, { - enable, - enabled, - disable, - log: log_js_1.log - }); + var debugObj = Object.assign( + (namespace) => { + return createDebugger(namespace); + }, + { + enable, + enabled, + disable, + log: import_log.log + } + ); function enable(namespaces) { enabledString = namespaces; enabledNamespaces = []; @@ -35453,8 +42767,8 @@ var require_debug2 = __commonJS({ enabledNamespaces.push(ns); } } - for (const instance of debuggers) { - instance.enabled = enabled(instance.namespace); + for (const instance8 of debuggers) { + instance8.enabled = enabled(instance8.namespace); } } function enabled(namespace) { @@ -35580,22 +42894,51 @@ var require_debug2 = __commonJS({ newDebugger.log = this.log; return newDebugger; } - exports2.default = debugObj; + var debug_default = debugObj; } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/logger/logger.js var require_logger = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/logger/logger.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TypeSpecRuntimeLogger = void 0; - exports2.createLoggerContext = createLoggerContext; - exports2.setLogLevel = setLogLevel; - exports2.getLogLevel = getLogLevel; - exports2.createClientLogger = createClientLogger; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var debug_js_1 = tslib_1.__importDefault(require_debug2()); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/logger/logger.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var logger_exports = {}; + __export2(logger_exports, { + TypeSpecRuntimeLogger: () => TypeSpecRuntimeLogger2, + createClientLogger: () => createClientLogger2, + createLoggerContext: () => createLoggerContext2, + getLogLevel: () => getLogLevel2, + setLogLevel: () => setLogLevel2 + }); + module2.exports = __toCommonJS2(logger_exports); + var import_debug = __toESM2(require_debug2()); + var import_env = require_env(); var TYPESPEC_RUNTIME_LOG_LEVELS = ["verbose", "info", "warning", "error"]; var levelMap = { verbose: 400, @@ -35611,48 +42954,54 @@ var require_logger = __commonJS({ function isTypeSpecRuntimeLogLevel(level) { return TYPESPEC_RUNTIME_LOG_LEVELS.includes(level); } - function createLoggerContext(options) { + function createLoggerContext2(options) { const registeredLoggers = /* @__PURE__ */ new Set(); - const logLevelFromEnv = typeof process !== "undefined" && process.env && process.env[options.logLevelEnvVarName] || void 0; + const logLevelFromEnv = (0, import_env.getEnvironmentVariable)(options.logLevelEnvVarName); let logLevel; - const clientLogger = (0, debug_js_1.default)(options.namespace); + const clientLogger = (0, import_debug.default)(options.namespace); clientLogger.log = (...args) => { - debug_js_1.default.log(...args); + import_debug.default.log(...args); }; function contextSetLogLevel(level) { if (level && !isTypeSpecRuntimeLogLevel(level)) { - throw new Error(`Unknown log level '${level}'. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(",")}`); + throw new Error( + `Unknown log level '${level}'. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(",")}` + ); } logLevel = level; const enabledNamespaces = []; - for (const logger of registeredLoggers) { - if (shouldEnable(logger)) { - enabledNamespaces.push(logger.namespace); + for (const logger2 of registeredLoggers) { + if (shouldEnable(logger2)) { + enabledNamespaces.push(logger2.namespace); } } - debug_js_1.default.enable(enabledNamespaces.join(",")); + import_debug.default.enable(enabledNamespaces.join(",")); } if (logLevelFromEnv) { if (isTypeSpecRuntimeLogLevel(logLevelFromEnv)) { contextSetLogLevel(logLevelFromEnv); } else { - console.error(`${options.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(", ")}.`); + console.error( + `${options.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join( + ", " + )}.` + ); } } - function shouldEnable(logger) { - return Boolean(logLevel && levelMap[logger.level] <= levelMap[logLevel]); + function shouldEnable(logger2) { + return Boolean(logLevel && levelMap[logger2.level] <= levelMap[logLevel]); } function createLogger2(parent, level) { - const logger = Object.assign(parent.extend(level), { + const logger2 = Object.assign(parent.extend(level), { level }); - patchLogMethod(parent, logger); - if (shouldEnable(logger)) { - const enabledNamespaces = debug_js_1.default.disable(); - debug_js_1.default.enable(enabledNamespaces + "," + logger.namespace); + patchLogMethod(parent, logger2); + if (shouldEnable(logger2)) { + const enabledNamespaces = import_debug.default.disable(); + import_debug.default.enable(enabledNamespaces + "," + logger2.namespace); } - registeredLoggers.add(logger); - return logger; + registeredLoggers.add(logger2); + return logger2; } function contextGetLogLevel() { return logLevel; @@ -35674,18 +43023,18 @@ var require_logger = __commonJS({ logger: clientLogger }; } - var context5 = createLoggerContext({ + var context5 = createLoggerContext2({ logLevelEnvVarName: "TYPESPEC_RUNTIME_LOG_LEVEL", namespace: "typeSpecRuntime" }); - exports2.TypeSpecRuntimeLogger = context5.logger; - function setLogLevel(logLevel) { + var TypeSpecRuntimeLogger2 = context5.logger; + function setLogLevel2(logLevel) { context5.setLogLevel(logLevel); } - function getLogLevel() { + function getLogLevel2() { return context5.getLogLevel(); } - function createClientLogger(namespace) { + function createClientLogger2(namespace) { return context5.createClientLogger(namespace); } } @@ -35693,13 +43042,35 @@ var require_logger = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/httpHeaders.js var require_httpHeaders = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/httpHeaders.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createHttpHeaders = createHttpHeaders; + "node_modules/@typespec/ts-http-runtime/dist/commonjs/httpHeaders.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var httpHeaders_exports = {}; + __export2(httpHeaders_exports, { + createHttpHeaders: () => createHttpHeaders2 + }); + module2.exports = __toCommonJS2(httpHeaders_exports); function normalizeName(name) { return name.toLowerCase(); } + function normalizeValue(value) { + return String(value).trim().replace(/[\r\n]/g, ""); + } function* headerIterator(map) { for (const entry of map.values()) { yield [entry.name, entry.value]; @@ -35722,7 +43093,7 @@ var require_httpHeaders = __commonJS({ * @param value - The value of the header to set. */ set(name, value) { - this._headersMap.set(normalizeName(name), { name, value: String(value).trim() }); + this._headersMap.set(normalizeName(name), { name, value: normalizeValue(value) }); } /** * Get the header value for the provided header name, or undefined if no header exists in this @@ -35775,48 +43146,70 @@ var require_httpHeaders = __commonJS({ return headerIterator(this._headersMap); } }; - function createHttpHeaders(rawHeaders) { + function createHttpHeaders2(rawHeaders) { return new HttpHeadersImpl(rawHeaders); } } }); -// node_modules/@typespec/ts-http-runtime/dist/commonjs/auth/schemes.js -var require_schemes = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/auth/schemes.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@typespec/ts-http-runtime/dist/commonjs/auth/oauth2Flows.js -var require_oauth2Flows = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/auth/oauth2Flows.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - // node_modules/@typespec/ts-http-runtime/dist/commonjs/util/uuidUtils.js var require_uuidUtils = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/uuidUtils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.randomUUID = randomUUID; - function randomUUID() { - return crypto.randomUUID(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/uuidUtils.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var uuidUtils_exports = {}; + __export2(uuidUtils_exports, { + randomUUID: () => randomUUID2 + }); + module2.exports = __toCommonJS2(uuidUtils_exports); + function randomUUID2() { + return globalThis.crypto.randomUUID(); } } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/pipelineRequest.js var require_pipelineRequest = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/pipelineRequest.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createPipelineRequest = createPipelineRequest; - var httpHeaders_js_1 = require_httpHeaders(); - var uuidUtils_js_1 = require_uuidUtils(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/pipelineRequest.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var pipelineRequest_exports = {}; + __export2(pipelineRequest_exports, { + createPipelineRequest: () => createPipelineRequest2 + }); + module2.exports = __toCommonJS2(pipelineRequest_exports); + var import_httpHeaders = require_httpHeaders(); + var import_uuid2 = require_uuidUtils(); var PipelineRequestImpl = class { url; method; @@ -35840,7 +43233,7 @@ var require_pipelineRequest = __commonJS({ constructor(options) { this.url = options.url; this.body = options.body; - this.headers = options.headers ?? (0, httpHeaders_js_1.createHttpHeaders)(); + this.headers = options.headers ?? (0, import_httpHeaders.createHttpHeaders)(); this.method = options.method ?? "GET"; this.timeout = options.timeout ?? 0; this.multipartBody = options.multipartBody; @@ -35852,14 +43245,14 @@ var require_pipelineRequest = __commonJS({ this.abortSignal = options.abortSignal; this.onUploadProgress = options.onUploadProgress; this.onDownloadProgress = options.onDownloadProgress; - this.requestId = options.requestId || (0, uuidUtils_js_1.randomUUID)(); + this.requestId = options.requestId || (0, import_uuid2.randomUUID)(); this.allowInsecureConnection = options.allowInsecureConnection ?? false; this.enableBrowserStreams = options.enableBrowserStreams ?? false; this.requestOverrides = options.requestOverrides; this.authSchemes = options.authSchemes; } }; - function createPipelineRequest(options) { + function createPipelineRequest2(options) { return new PipelineRequestImpl(options); } } @@ -35867,10 +43260,29 @@ var require_pipelineRequest = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/pipeline.js var require_pipeline = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/pipeline.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createEmptyPipeline = createEmptyPipeline; + "node_modules/@typespec/ts-http-runtime/dist/commonjs/pipeline.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var pipeline_exports = {}; + __export2(pipeline_exports, { + createEmptyPipeline: () => createEmptyPipeline2 + }); + module2.exports = __toCommonJS2(pipeline_exports); var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); var HttpPipeline = class _HttpPipeline { _policies = []; @@ -35910,11 +43322,14 @@ var require_pipeline = __commonJS({ } sendRequest(httpClient, request3) { const policies = this.getOrderedPolicies(); - const pipeline2 = policies.reduceRight((next, policy) => { - return (req) => { - return policy.sendRequest(req, next); - }; - }, (req) => httpClient.sendRequest(req)); + const pipeline2 = policies.reduceRight( + (next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, + (req) => httpClient.sendRequest(req) + ); return pipeline2(request3); } getOrderedPolicies() { @@ -36047,7 +43462,7 @@ var require_pipeline = __commonJS({ return result; } }; - function createEmptyPipeline() { + function createEmptyPipeline2() { return HttpPipeline.create(); } } @@ -36055,11 +43470,30 @@ var require_pipeline = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/util/object.js var require_object = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/object.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isObject = isObject2; - function isObject2(input) { + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/object.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var object_exports = {}; + __export2(object_exports, { + isObject: () => isObject4 + }); + module2.exports = __toCommonJS2(object_exports); + function isObject4(input) { return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); } } @@ -36067,13 +43501,32 @@ var require_object = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/util/error.js var require_error = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isError = isError; - var object_js_1 = require_object(); - function isError(e) { - if ((0, object_js_1.isObject)(e)) { + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/error.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var error_exports = {}; + __export2(error_exports, { + isError: () => isError2 + }); + module2.exports = __toCommonJS2(error_exports); + var import_object = require_object(); + function isError2(e) { + if ((0, import_object.isObject)(e)) { const hasName = typeof e.name === "string"; const hasMessage = typeof e.message === "string"; return hasName && hasMessage; @@ -36085,22 +43538,60 @@ var require_error = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/util/inspect.js var require_inspect = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/inspect.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.custom = void 0; - var node_util_1 = require("node:util"); - exports2.custom = node_util_1.inspect.custom; + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/inspect.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var inspect_exports = {}; + __export2(inspect_exports, { + custom: () => custom + }); + module2.exports = __toCommonJS2(inspect_exports); + var import_node_util = require("node:util"); + var custom = import_node_util.inspect.custom; } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/util/sanitizer.js var require_sanitizer = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/sanitizer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Sanitizer = void 0; - var object_js_1 = require_object(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/sanitizer.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var sanitizer_exports = {}; + __export2(sanitizer_exports, { + Sanitizer: () => Sanitizer2 + }); + module2.exports = __toCommonJS2(sanitizer_exports); + var import_object = require_object(); var RedactedString = "REDACTED"; var defaultAllowedHeaderNames = [ "x-ms-client-request-id", @@ -36144,10 +43635,13 @@ var require_sanitizer = __commonJS({ "WWW-Authenticate" ]; var defaultAllowedQueryParameters = ["api-version"]; - var Sanitizer = class { + var Sanitizer2 = class { allowedHeaderNames; allowedQueryParameters; - constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { + constructor({ + additionalAllowedHeaderNames: allowedHeaderNames = [], + additionalAllowedQueryParameters: allowedQueryParameters = [] + } = {}) { allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); @@ -36160,34 +43654,38 @@ var require_sanitizer = __commonJS({ */ sanitize(obj) { const seen = /* @__PURE__ */ new Set(); - return JSON.stringify(obj, (key, value) => { - if (value instanceof Error) { - return { - ...value, - name: value.name, - message: value.message - }; - } - if (key === "headers") { - return this.sanitizeHeaders(value); - } else if (key === "url") { - return this.sanitizeUrl(value); - } else if (key === "query") { - return this.sanitizeQuery(value); - } else if (key === "body") { - return void 0; - } else if (key === "response") { - return void 0; - } else if (key === "operationSpec") { - return void 0; - } else if (Array.isArray(value) || (0, object_js_1.isObject)(value)) { - if (seen.has(value)) { - return "[Circular]"; + return JSON.stringify( + obj, + (key, value) => { + if (value instanceof Error) { + return { + ...value, + name: value.name, + message: value.message + }; } - seen.add(value); - } - return value; - }, 2); + if (key === "headers" && (0, import_object.isObject)(value)) { + return this.sanitizeHeaders(value); + } else if (key === "url" && typeof value === "string") { + return this.sanitizeUrl(value); + } else if (key === "query" && (0, import_object.isObject)(value)) { + return this.sanitizeQuery(value); + } else if (key === "body") { + return void 0; + } else if (key === "response") { + return void 0; + } else if (key === "operationSpec") { + return void 0; + } else if (Array.isArray(value) || (0, import_object.isObject)(value)) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); + } + return value; + }, + 2 + ); } /** * Sanitizes a URL for logging. @@ -36235,22 +43733,40 @@ var require_sanitizer = __commonJS({ return sanitized; } }; - exports2.Sanitizer = Sanitizer; } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/restError.js var require_restError = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/restError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RestError = void 0; - exports2.isRestError = isRestError; - var error_js_1 = require_error(); - var inspect_js_1 = require_inspect(); - var sanitizer_js_1 = require_sanitizer(); - var errorSanitizer = new sanitizer_js_1.Sanitizer(); - var RestError = class _RestError extends Error { + "node_modules/@typespec/ts-http-runtime/dist/commonjs/restError.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var restError_exports = {}; + __export2(restError_exports, { + RestError: () => RestError2, + isRestError: () => isRestError2 + }); + module2.exports = __toCommonJS2(restError_exports); + var import_error2 = require_error(); + var import_inspect = require_inspect(); + var import_sanitizer = require_sanitizer(); + var errorSanitizer = new import_sanitizer.Sanitizer(); + var RestError2 = class _RestError extends Error { /** * Something went wrong when making the request. * This means the actual request failed for some reason, @@ -36295,7 +43811,7 @@ var require_restError = __commonJS({ maxFreeSockets: this.request.agent.maxFreeSockets, maxSockets: this.request.agent.maxSockets } : void 0; - Object.defineProperty(this, inspect_js_1.custom, { + Object.defineProperty(this, import_inspect.custom, { value: () => { return `RestError: ${this.message} ${errorSanitizer.sanitize({ @@ -36309,27 +43825,45 @@ var require_restError = __commonJS({ Object.setPrototypeOf(this, _RestError.prototype); } }; - exports2.RestError = RestError; - function isRestError(e) { - if (e instanceof RestError) { + function isRestError2(e) { + if (e instanceof RestError2) { return true; } - return (0, error_js_1.isError)(e) && e.name === "RestError"; + return (0, import_error2.isError)(e) && e.name === "RestError"; } } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/util/bytesEncoding.js var require_bytesEncoding = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/bytesEncoding.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.uint8ArrayToString = uint8ArrayToString; - exports2.stringToUint8Array = stringToUint8Array; - function uint8ArrayToString(bytes, format) { + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/bytesEncoding.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var bytesEncoding_exports = {}; + __export2(bytesEncoding_exports, { + stringToUint8Array: () => stringToUint8Array2, + uint8ArrayToString: () => uint8ArrayToString2 + }); + module2.exports = __toCommonJS2(bytesEncoding_exports); + function uint8ArrayToString2(bytes, format) { return Buffer.from(bytes).toString(format); } - function stringToUint8Array(value, format) { + function stringToUint8Array2(value, format) { return Buffer.from(value, format); } } @@ -36337,32 +43871,79 @@ var require_bytesEncoding = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/log.js var require_log2 = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/log.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = void 0; - var logger_js_1 = require_logger(); - exports2.logger = (0, logger_js_1.createClientLogger)("ts-http-runtime"); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/log.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var log_exports = {}; + __export2(log_exports, { + logger: () => logger2 + }); + module2.exports = __toCommonJS2(log_exports); + var import_logger = require_logger(); + var logger2 = (0, import_logger.createClientLogger)("ts-http-runtime"); } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/nodeHttpClient.js var require_nodeHttpClient = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/nodeHttpClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getBodyLength = getBodyLength; - exports2.createNodeHttpClient = createNodeHttpClient; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var node_http_1 = tslib_1.__importDefault(require("node:http")); - var node_https_1 = tslib_1.__importDefault(require("node:https")); - var node_zlib_1 = tslib_1.__importDefault(require("node:zlib")); - var node_stream_1 = require("node:stream"); - var AbortError_js_1 = require_AbortError(); - var httpHeaders_js_1 = require_httpHeaders(); - var restError_js_1 = require_restError(); - var log_js_1 = require_log2(); - var sanitizer_js_1 = require_sanitizer(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/nodeHttpClient.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var nodeHttpClient_exports = {}; + __export2(nodeHttpClient_exports, { + createNodeHttpClient: () => createNodeHttpClient, + getBodyLength: () => getBodyLength + }); + module2.exports = __toCommonJS2(nodeHttpClient_exports); + var import_node_http = __toESM2(require("node:http")); + var import_node_https = __toESM2(require("node:https")); + var import_node_zlib = __toESM2(require("node:zlib")); + var import_node_stream5 = require("node:stream"); + var import_AbortError = require_AbortError(); + var import_httpHeaders = require_httpHeaders(); + var import_restError = require_restError(); + var import_log = require_log2(); + var import_sanitizer = require_sanitizer(); var DEFAULT_TLS_SETTINGS = {}; function isReadableStream(body) { return body && typeof body.pipe === "function"; @@ -36371,9 +43952,9 @@ var require_nodeHttpClient = __commonJS({ if (stream2.readable === false) { return Promise.resolve(); } - return new Promise((resolve14) => { + return new Promise((resolve15) => { const handler2 = () => { - resolve14(); + resolve15(); stream2.removeListener("close", handler2); stream2.removeListener("end", handler2); stream2.removeListener("error", handler2); @@ -36386,7 +43967,7 @@ var require_nodeHttpClient = __commonJS({ function isArrayBuffer(body) { return body && typeof body.byteLength === "number"; } - var ReportTransform = class extends node_stream_1.Transform { + var ReportTransform = class extends import_node_stream5.Transform { loadedBytes = 0; progressCallback; // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type @@ -36417,7 +43998,7 @@ var require_nodeHttpClient = __commonJS({ let abortListener; if (request3.abortSignal) { if (request3.abortSignal.aborted) { - throw new AbortError_js_1.AbortError("The operation was aborted. Request has already been canceled."); + throw new import_AbortError.AbortError("The operation was aborted. Request has already been canceled."); } abortListener = (event) => { if (event.type === "abort") { @@ -36429,8 +44010,8 @@ var require_nodeHttpClient = __commonJS({ let timeoutId; if (request3.timeout > 0) { timeoutId = setTimeout(() => { - const sanitizer = new sanitizer_js_1.Sanitizer(); - log_js_1.logger.info(`request to '${sanitizer.sanitizeUrl(request3.url)}' timed out. canceling...`); + const sanitizer = new import_sanitizer.Sanitizer(); + import_log.logger.info(`request to '${sanitizer.sanitizeUrl(request3.url)}' timed out. canceling...`); abortController.abort(); }, request3.timeout); } @@ -36449,7 +44030,7 @@ var require_nodeHttpClient = __commonJS({ const onUploadProgress = request3.onUploadProgress; const uploadReportStream = new ReportTransform(onUploadProgress); uploadReportStream.on("error", (e) => { - log_js_1.logger.error("Error in upload progress", e); + import_log.logger.error("Error in upload progress", e); }); if (isReadableStream(body)) { body.pipe(uploadReportStream); @@ -36459,9 +44040,6 @@ var require_nodeHttpClient = __commonJS({ body = uploadReportStream; } const res = await this.makeRequest(request3, abortController, body); - if (timeoutId !== void 0) { - clearTimeout(timeoutId); - } const headers = getResponseHeaders(res); const status = res.statusCode ?? 0; const response = { @@ -36478,7 +44056,7 @@ var require_nodeHttpClient = __commonJS({ if (onDownloadProgress) { const downloadReportStream = new ReportTransform(onDownloadProgress); downloadReportStream.on("error", (e) => { - log_js_1.logger.error("Error in download progress", e); + import_log.logger.error("Error in download progress", e); }); responseStream.pipe(downloadReportStream); responseStream = downloadReportStream; @@ -36493,6 +44071,9 @@ var require_nodeHttpClient = __commonJS({ } return response; } finally { + if (timeoutId !== void 0) { + clearTimeout(timeoutId); + } if (request3.abortSignal && abortListener) { let uploadStreamDone = Promise.resolve(); if (isReadableStream(body)) { @@ -36507,7 +44088,7 @@ var require_nodeHttpClient = __commonJS({ request3.abortSignal?.removeEventListener("abort", abortListener); } }).catch((e) => { - log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e); + import_log.logger.warning("Error when cleaning up abortListener on httpRequest", e); }); } } @@ -36528,13 +44109,17 @@ var require_nodeHttpClient = __commonJS({ headers: request3.headers.toJSON({ preserveCase: true }), ...request3.requestOverrides }; - return new Promise((resolve14, reject) => { - const req = isInsecure ? node_http_1.default.request(options, resolve14) : node_https_1.default.request(options, resolve14); + return new Promise((resolve15, reject) => { + const req = isInsecure ? import_node_http.default.request(options, resolve15) : import_node_https.default.request(options, resolve15); req.once("error", (err) => { - reject(new restError_js_1.RestError(err.message, { code: err.code ?? restError_js_1.RestError.REQUEST_SEND_ERROR, request: request3 })); + reject( + new import_restError.RestError(err.message, { code: err.code ?? import_restError.RestError.REQUEST_SEND_ERROR, request: request3 }) + ); }); abortController.signal.addEventListener("abort", () => { - const abortError = new AbortError_js_1.AbortError("The operation was aborted. Rejecting from abort signal callback while making request."); + const abortError = new import_AbortError.AbortError( + "The operation was aborted. Rejecting from abort signal callback while making request." + ); req.destroy(abortError); reject(abortError); }); @@ -36544,10 +44129,12 @@ var require_nodeHttpClient = __commonJS({ if (typeof body === "string" || Buffer.isBuffer(body)) { req.end(body); } else if (isArrayBuffer(body)) { - req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body)); + req.end( + ArrayBuffer.isView(body) ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : Buffer.from(body) + ); } else { - log_js_1.logger.error("Unrecognized body type", body); - reject(new restError_js_1.RestError("Unrecognized body type")); + import_log.logger.error("Unrecognized body type", body); + reject(new import_restError.RestError("Unrecognized body type")); } } else { req.end(); @@ -36558,23 +44145,23 @@ var require_nodeHttpClient = __commonJS({ const disableKeepAlive = request3.disableKeepAlive; if (isInsecure) { if (disableKeepAlive) { - return node_http_1.default.globalAgent; + return import_node_http.default.globalAgent; } if (!this.cachedHttpAgent) { - this.cachedHttpAgent = new node_http_1.default.Agent({ keepAlive: true }); + this.cachedHttpAgent = new import_node_http.default.Agent({ keepAlive: true }); } return this.cachedHttpAgent; } else { if (disableKeepAlive && !request3.tlsSettings) { - return node_https_1.default.globalAgent; + return import_node_https.default.globalAgent; } const tlsSettings = request3.tlsSettings ?? DEFAULT_TLS_SETTINGS; let agent = this.cachedHttpsAgents.get(tlsSettings); if (agent && agent.options.keepAlive === !disableKeepAlive) { return agent; } - log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent"); - agent = new node_https_1.default.Agent({ + import_log.logger.info("No cached TLS Agent exist, creating a new Agent"); + agent = new import_node_https.default.Agent({ // keepAlive is true if disableKeepAlive is false. keepAlive: !disableKeepAlive, // Since we are spreading, if no tslSettings were provided, nothing is added to the agent options. @@ -36586,7 +44173,7 @@ var require_nodeHttpClient = __commonJS({ } }; function getResponseHeaders(res) { - const headers = (0, httpHeaders_js_1.createHttpHeaders)(); + const headers = (0, import_httpHeaders.createHttpHeaders)(); for (const header of Object.keys(res.headers)) { const value = res.headers[header]; if (Array.isArray(value)) { @@ -36602,18 +44189,18 @@ var require_nodeHttpClient = __commonJS({ function getDecodedResponseStream(stream2, headers) { const contentEncoding = headers.get("Content-Encoding"); if (contentEncoding === "gzip") { - const unzip = node_zlib_1.default.createGunzip(); + const unzip = import_node_zlib.default.createGunzip(); stream2.pipe(unzip); return unzip; } else if (contentEncoding === "deflate") { - const inflate = node_zlib_1.default.createInflate(); + const inflate = import_node_zlib.default.createInflate(); stream2.pipe(inflate); return inflate; } return stream2; } function streamToText(stream2) { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { const buffer = []; stream2.on("data", (chunk) => { if (Buffer.isBuffer(chunk)) { @@ -36623,15 +44210,17 @@ var require_nodeHttpClient = __commonJS({ } }); stream2.on("end", () => { - resolve14(Buffer.concat(buffer).toString("utf8")); + resolve15(Buffer.concat(buffer).toString("utf8")); }); stream2.on("error", (e) => { if (e && e?.name === "AbortError") { reject(e); } else { - reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, { - code: restError_js_1.RestError.PARSE_ERROR - })); + reject( + new import_restError.RestError(`Error reading response as text: ${e.message}`, { + code: import_restError.RestError.PARSE_ERROR + }) + ); } }); }); @@ -36659,43 +44248,81 @@ var require_nodeHttpClient = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/defaultHttpClient.js var require_defaultHttpClient = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/defaultHttpClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createDefaultHttpClient = createDefaultHttpClient; - var nodeHttpClient_js_1 = require_nodeHttpClient(); - function createDefaultHttpClient() { - return (0, nodeHttpClient_js_1.createNodeHttpClient)(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/defaultHttpClient.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var defaultHttpClient_exports = {}; + __export2(defaultHttpClient_exports, { + createDefaultHttpClient: () => createDefaultHttpClient2 + }); + module2.exports = __toCommonJS2(defaultHttpClient_exports); + var import_nodeHttpClient = require_nodeHttpClient(); + function createDefaultHttpClient2() { + return (0, import_nodeHttpClient.createNodeHttpClient)(); } } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/logPolicy.js var require_logPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/logPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logPolicyName = void 0; - exports2.logPolicy = logPolicy; - var log_js_1 = require_log2(); - var sanitizer_js_1 = require_sanitizer(); - exports2.logPolicyName = "logPolicy"; - function logPolicy(options = {}) { - const logger = options.logger ?? log_js_1.logger.info; - const sanitizer = new sanitizer_js_1.Sanitizer({ + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/logPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var logPolicy_exports = {}; + __export2(logPolicy_exports, { + logPolicy: () => logPolicy2, + logPolicyName: () => logPolicyName2 + }); + module2.exports = __toCommonJS2(logPolicy_exports); + var import_log = require_log2(); + var import_sanitizer = require_sanitizer(); + var logPolicyName2 = "logPolicy"; + function logPolicy2(options = {}) { + const logger2 = options.logger ?? import_log.logger.info; + const sanitizer = new import_sanitizer.Sanitizer({ additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, additionalAllowedQueryParameters: options.additionalAllowedQueryParameters }); return { - name: exports2.logPolicyName, + name: logPolicyName2, async sendRequest(request3, next) { - if (!logger.enabled) { + if (!logger2.enabled) { return next(request3); } - logger(`Request: ${sanitizer.sanitize(request3)}`); + logger2(`Request: ${sanitizer.sanitize(request3)}`); const response = await next(request3); - logger(`Response status code: ${response.status}`); - logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + logger2(`Response status code: ${response.status}`); + logger2(`Headers: ${sanitizer.sanitize({ headers: response.headers })}`); return response; } }; @@ -36703,68 +44330,56 @@ var require_logPolicy = __commonJS({ } }); -// node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/redirectPolicy.js -var require_redirectPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/redirectPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.redirectPolicyName = void 0; - exports2.redirectPolicy = redirectPolicy; - exports2.redirectPolicyName = "redirectPolicy"; - var allowedRedirect = ["GET", "HEAD"]; - function redirectPolicy(options = {}) { - const { maxRetries = 20 } = options; - return { - name: exports2.redirectPolicyName, - async sendRequest(request3, next) { - const response = await next(request3); - return handleRedirect(next, response, maxRetries); - } - }; - } - async function handleRedirect(next, response, maxRetries, currentRetries = 0) { - const { request: request3, status, headers } = response; - const locationHeader = headers.get("location"); - if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request3.method) || status === 302 && allowedRedirect.includes(request3.method) || status === 303 && request3.method === "POST" || status === 307) && currentRetries < maxRetries) { - const url2 = new URL(locationHeader, request3.url); - request3.url = url2.toString(); - if (status === 303) { - request3.method = "GET"; - request3.headers.delete("Content-Length"); - delete request3.body; - } - request3.headers.delete("Authorization"); - const res = await next(request3); - return handleRedirect(next, res, maxRetries, currentRetries + 1); - } - return response; - } - } -}); - // node_modules/@typespec/ts-http-runtime/dist/commonjs/util/userAgentPlatform.js var require_userAgentPlatform = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/userAgentPlatform.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getHeaderName = getHeaderName; - exports2.setPlatformSpecificData = setPlatformSpecificData; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var node_os_1 = tslib_1.__importDefault(require("node:os")); - var node_process_1 = tslib_1.__importDefault(require("node:process")); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/userAgentPlatform.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var userAgentPlatform_exports = {}; + __export2(userAgentPlatform_exports, { + getHeaderName: () => getHeaderName, + setPlatformSpecificData: () => setPlatformSpecificData2 + }); + module2.exports = __toCommonJS2(userAgentPlatform_exports); + var import_node_os = __toESM2(require("node:os")); + var import_node_process = __toESM2(require("node:process")); function getHeaderName() { return "User-Agent"; } - async function setPlatformSpecificData(map) { - if (node_process_1.default && node_process_1.default.versions) { - const osInfo = `${node_os_1.default.type()} ${node_os_1.default.release()}; ${node_os_1.default.arch()}`; - const versions = node_process_1.default.versions; - if (versions.bun) { - map.set("Bun", `${versions.bun} (${osInfo})`); - } else if (versions.deno) { - map.set("Deno", `${versions.deno} (${osInfo})`); - } else if (versions.node) { - map.set("Node", `${versions.node} (${osInfo})`); + async function setPlatformSpecificData2(map) { + if (import_node_process.default && import_node_process.default.versions) { + const osInfo = `${import_node_os.default.type()} ${import_node_os.default.release()}; ${import_node_os.default.arch()}`; + if (import_node_process.default.versions.bun) { + map.set("Bun", `${import_node_process.default.versions.bun} (${osInfo})`); + } else if (import_node_process.default.versions.deno) { + map.set("Deno", `${import_node_process.default.versions.deno} (${osInfo})`); + } else if (import_node_process.default.versions.node) { + map.set("Node", `${import_node_process.default.versions.node} (${osInfo})`); } } } @@ -36773,24 +44388,64 @@ var require_userAgentPlatform = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/constants.js var require_constants8 = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/constants.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DEFAULT_RETRY_POLICY_COUNT = exports2.SDK_VERSION = void 0; - exports2.SDK_VERSION = "0.3.2"; - exports2.DEFAULT_RETRY_POLICY_COUNT = 3; + "node_modules/@typespec/ts-http-runtime/dist/commonjs/constants.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var constants_exports = {}; + __export2(constants_exports, { + DEFAULT_RETRY_POLICY_COUNT: () => DEFAULT_RETRY_POLICY_COUNT, + SDK_VERSION: () => SDK_VERSION + }); + module2.exports = __toCommonJS2(constants_exports); + var SDK_VERSION = "0.3.9"; + var DEFAULT_RETRY_POLICY_COUNT = 3; } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/util/userAgent.js var require_userAgent = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/userAgent.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getUserAgentHeaderName = getUserAgentHeaderName; - exports2.getUserAgentValue = getUserAgentValue; - var userAgentPlatform_js_1 = require_userAgentPlatform(); - var constants_js_1 = require_constants8(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/userAgent.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var userAgent_exports = {}; + __export2(userAgent_exports, { + getUserAgentHeaderName: () => getUserAgentHeaderName, + getUserAgentValue: () => getUserAgentValue, + setPlatformSpecificData: () => import_userAgent.setPlatformSpecificData + }); + module2.exports = __toCommonJS2(userAgent_exports); + var import_userAgent = require_userAgentPlatform(); + var import_constants5 = require_constants8(); function getUserAgentString(telemetryInfo) { const parts = []; for (const [key, value] of telemetryInfo) { @@ -36800,12 +44455,12 @@ var require_userAgent = __commonJS({ return parts.join(" "); } function getUserAgentHeaderName() { - return (0, userAgentPlatform_js_1.getHeaderName)(); + return (0, import_userAgent.getHeaderName)(); } async function getUserAgentValue(prefix) { const runtimeInfo = /* @__PURE__ */ new Map(); - runtimeInfo.set("ts-http-runtime", constants_js_1.SDK_VERSION); - await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo); + runtimeInfo.set("ts-http-runtime", import_constants5.SDK_VERSION); + await (0, import_userAgent.setPlatformSpecificData)(runtimeInfo); const defaultAgent = getUserAgentString(runtimeInfo); const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent; return userAgentValue; @@ -36815,18 +44470,37 @@ var require_userAgent = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/userAgentPolicy.js var require_userAgentPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/userAgentPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.userAgentPolicyName = void 0; - exports2.userAgentPolicy = userAgentPolicy; - var userAgent_js_1 = require_userAgent(); - var UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)(); - exports2.userAgentPolicyName = "userAgentPolicy"; - function userAgentPolicy(options = {}) { - const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/userAgentPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var userAgentPolicy_exports = {}; + __export2(userAgentPolicy_exports, { + userAgentPolicy: () => userAgentPolicy2, + userAgentPolicyName: () => userAgentPolicyName2 + }); + module2.exports = __toCommonJS2(userAgentPolicy_exports); + var import_userAgent = require_userAgent(); + var UserAgentHeaderName = (0, import_userAgent.getUserAgentHeaderName)(); + var userAgentPolicyName2 = "userAgentPolicy"; + function userAgentPolicy2(options = {}) { + const userAgentValue = (0, import_userAgent.getUserAgentValue)(options.userAgentPrefix); return { - name: exports2.userAgentPolicyName, + name: userAgentPolicyName2, async sendRequest(request3, next) { if (!request3.headers.has(UserAgentHeaderName)) { request3.headers.set(UserAgentHeaderName, await userAgentValue); @@ -36838,35 +44512,32 @@ var require_userAgentPolicy = __commonJS({ } }); -// node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/decompressResponsePolicy.js -var require_decompressResponsePolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/decompressResponsePolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.decompressResponsePolicyName = void 0; - exports2.decompressResponsePolicy = decompressResponsePolicy; - exports2.decompressResponsePolicyName = "decompressResponsePolicy"; - function decompressResponsePolicy() { - return { - name: exports2.decompressResponsePolicyName, - async sendRequest(request3, next) { - if (request3.method !== "HEAD") { - request3.headers.set("Accept-Encoding", "gzip,deflate"); - } - return next(request3); - } - }; - } - } -}); - // node_modules/@typespec/ts-http-runtime/dist/commonjs/util/random.js var require_random = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/random.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; - function getRandomIntegerInclusive(min, max) { + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/random.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var random_exports = {}; + __export2(random_exports, { + getRandomIntegerInclusive: () => getRandomIntegerInclusive2 + }); + module2.exports = __toCommonJS2(random_exports); + function getRandomIntegerInclusive2(min, max) { min = Math.ceil(min); max = Math.floor(max); const offset = Math.floor(Math.random() * (max - min + 1)); @@ -36877,15 +44548,34 @@ var require_random = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/util/delay.js var require_delay = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/delay.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.calculateRetryDelay = calculateRetryDelay; - var random_js_1 = require_random(); - function calculateRetryDelay(retryAttempt, config) { + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/delay.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var delay_exports = {}; + __export2(delay_exports, { + calculateRetryDelay: () => calculateRetryDelay2 + }); + module2.exports = __toCommonJS2(delay_exports); + var import_random = require_random(); + function calculateRetryDelay2(retryAttempt, config) { const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); - const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); + const retryAfterInMs = clampedDelay / 2 + (0, import_random.getRandomIntegerInclusive)(0, clampedDelay / 2); return { retryAfterInMs }; } } @@ -36893,19 +44583,40 @@ var require_delay = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/util/helpers.js var require_helpers2 = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/helpers.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay2; - exports2.parseHeaderValueAsNumber = parseHeaderValueAsNumber; - var AbortError_js_1 = require_AbortError(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/helpers.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var helpers_exports = {}; + __export2(helpers_exports, { + delay: () => delay2, + parseHeaderValueAsNumber: () => parseHeaderValueAsNumber + }); + module2.exports = __toCommonJS2(helpers_exports); + var import_AbortError = require_AbortError(); var StandardAbortMessage = "The operation was aborted."; function delay2(delayInMs, value, options) { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { let timer = void 0; let onAborted = void 0; const rejectOnAbort = () => { - return reject(new AbortError_js_1.AbortError(options?.abortErrorMsg ? options?.abortErrorMsg : StandardAbortMessage)); + return reject( + new import_AbortError.AbortError(options?.abortErrorMsg ? options?.abortErrorMsg : StandardAbortMessage) + ); }; const removeListeners = () => { if (options?.abortSignal && onAborted) { @@ -36924,7 +44635,7 @@ var require_helpers2 = __commonJS({ } timer = setTimeout(() => { removeListeners(); - resolve14(value); + resolve15(value); }, delayInMs); if (options?.abortSignal) { options.abortSignal.addEventListener("abort", onAborted); @@ -36933,11 +44644,9 @@ var require_helpers2 = __commonJS({ } function parseHeaderValueAsNumber(response, headerName) { const value = response.headers.get(headerName); - if (!value) - return; + if (!value) return; const valueAsNum = Number(value); - if (Number.isNaN(valueAsNum)) - return; + if (Number.isNaN(valueAsNum)) return; return valueAsNum; } } @@ -36945,28 +44654,45 @@ var require_helpers2 = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/retryStrategies/throttlingRetryStrategy.js var require_throttlingRetryStrategy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/retryStrategies/throttlingRetryStrategy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isThrottlingRetryResponse = isThrottlingRetryResponse; - exports2.throttlingRetryStrategy = throttlingRetryStrategy; - var helpers_js_1 = require_helpers2(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/retryStrategies/throttlingRetryStrategy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var throttlingRetryStrategy_exports = {}; + __export2(throttlingRetryStrategy_exports, { + isThrottlingRetryResponse: () => isThrottlingRetryResponse, + throttlingRetryStrategy: () => throttlingRetryStrategy + }); + module2.exports = __toCommonJS2(throttlingRetryStrategy_exports); + var import_helpers = require_helpers2(); var RetryAfterHeader = "Retry-After"; var AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; function getRetryAfterInMs(response) { - if (!(response && [429, 503].includes(response.status))) - return void 0; + if (!(response && [429, 503].includes(response.status))) return void 0; try { for (const header of AllRetryAfterHeaders) { - const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header); + const retryAfterValue = (0, import_helpers.parseHeaderValueAsNumber)(response, header); if (retryAfterValue === 0 || retryAfterValue) { const multiplyingFactor = header === RetryAfterHeader ? 1e3 : 1; return retryAfterValue * multiplyingFactor; } } const retryAfterHeader = response.headers.get(RetryAfterHeader); - if (!retryAfterHeader) - return; + if (!retryAfterHeader) return; const date = Date.parse(retryAfterHeader); const diff = date - Date.now(); return Number.isFinite(diff) ? Math.max(0, diff) : void 0; @@ -36996,14 +44722,33 @@ var require_throttlingRetryStrategy = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/retryStrategies/exponentialRetryStrategy.js var require_exponentialRetryStrategy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/retryStrategies/exponentialRetryStrategy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exponentialRetryStrategy = exponentialRetryStrategy; - exports2.isExponentialRetryResponse = isExponentialRetryResponse; - exports2.isSystemError = isSystemError; - var delay_js_1 = require_delay(); - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/retryStrategies/exponentialRetryStrategy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var exponentialRetryStrategy_exports = {}; + __export2(exponentialRetryStrategy_exports, { + exponentialRetryStrategy: () => exponentialRetryStrategy, + isExponentialRetryResponse: () => isExponentialRetryResponse, + isSystemError: () => isSystemError + }); + module2.exports = __toCommonJS2(exponentialRetryStrategy_exports); + var import_delay = require_delay(); + var import_throttlingRetryStrategy = require_throttlingRetryStrategy(); var DEFAULT_CLIENT_RETRY_INTERVAL = 1e3; var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1e3 * 64; function exponentialRetryStrategy(options = {}) { @@ -37016,14 +44761,14 @@ var require_exponentialRetryStrategy = __commonJS({ const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; const isExponential = isExponentialRetryResponse(response); const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; - const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential); + const unknownResponse = response && ((0, import_throttlingRetryStrategy.isThrottlingRetryResponse)(response) || !isExponential); if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { return { skipStrategy: true }; } if (responseError && !matchedSystemError && !isExponential) { return { errorToThrow: responseError }; } - return (0, delay_js_1.calculateRetryDelay)(retryCount, { + return (0, import_delay.calculateRetryDelay)(retryCount, { retryDelayInMs: retryInterval, maxRetryDelayInMs: maxRetryInterval }); @@ -37031,7 +44776,9 @@ var require_exponentialRetryStrategy = __commonJS({ }; } function isExponentialRetryResponse(response) { - return Boolean(response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505); + return Boolean( + response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505 + ); } function isSystemError(err) { if (!err) { @@ -37044,18 +44791,38 @@ var require_exponentialRetryStrategy = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/retryPolicy.js var require_retryPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/retryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.retryPolicy = retryPolicy; - var helpers_js_1 = require_helpers2(); - var AbortError_js_1 = require_AbortError(); - var logger_js_1 = require_logger(); - var constants_js_1 = require_constants8(); - var retryPolicyLogger = (0, logger_js_1.createClientLogger)("ts-http-runtime retryPolicy"); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/retryPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var retryPolicy_exports = {}; + __export2(retryPolicy_exports, { + retryPolicy: () => retryPolicy2 + }); + module2.exports = __toCommonJS2(retryPolicy_exports); + var import_helpers = require_helpers2(); + var import_restError = require_restError(); + var import_AbortError = require_AbortError(); + var import_logger = require_logger(); + var import_constants5 = require_constants8(); + var retryPolicyLogger = (0, import_logger.createClientLogger)("ts-http-runtime retryPolicy"); var retryPolicyName = "retryPolicy"; - function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) { - const logger = options.logger || retryPolicyLogger; + function retryPolicy2(strategies, options = { maxRetries: import_constants5.DEFAULT_RETRY_POLICY_COUNT }) { + const logger2 = options.logger || retryPolicyLogger; return { name: retryPolicyName, async sendRequest(request3, next) { @@ -37064,27 +44831,28 @@ var require_retryPolicy = __commonJS({ let retryCount = -1; retryRequest: while (true) { retryCount += 1; - response = void 0; responseError = void 0; try { - logger.info(`Retry ${retryCount}: Attempting to send request`, request3.requestId); + logger2.info(`Retry ${retryCount}: Attempting to send request`, request3.requestId); response = await next(request3); - logger.info(`Retry ${retryCount}: Received a response from request`, request3.requestId); + logger2.info(`Retry ${retryCount}: Received a response from request`, request3.requestId); } catch (e) { - logger.error(`Retry ${retryCount}: Received an error from request`, request3.requestId); - responseError = e; - if (!e || responseError.name !== "RestError") { + logger2.error(`Retry ${retryCount}: Received an error from request`, request3.requestId); + if (!(0, import_restError.isRestError)(e)) { throw e; } - response = responseError.response; + responseError = e; + response = e.response; } if (request3.abortSignal?.aborted) { - logger.error(`Retry ${retryCount}: Request aborted.`); - const abortError = new AbortError_js_1.AbortError(); + logger2.error(`Retry ${retryCount}: Request aborted.`); + const abortError = new import_AbortError.AbortError(); throw abortError; } - if (retryCount >= (options.maxRetries ?? constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) { - logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); + if (retryCount >= (options.maxRetries ?? import_constants5.DEFAULT_RETRY_POLICY_COUNT)) { + logger2.info( + `Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.` + ); if (responseError) { throw responseError; } else if (response) { @@ -37093,9 +44861,9 @@ var require_retryPolicy = __commonJS({ throw new Error("Maximum retries reached with no response or error to throw"); } } - logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); + logger2.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); strategiesLoop: for (const strategy of strategies) { - const strategyLogger = strategy.logger || logger; + const strategyLogger = strategy.logger || logger2; strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); const modifiers = strategy.retry({ retryCount, @@ -37108,26 +44876,37 @@ var require_retryPolicy = __commonJS({ } const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; if (errorToThrow) { - strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); + strategyLogger.error( + `Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, + errorToThrow + ); throw errorToThrow; } if (retryAfterInMs || retryAfterInMs === 0) { - strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); - await (0, helpers_js_1.delay)(retryAfterInMs, void 0, { abortSignal: request3.abortSignal }); + strategyLogger.info( + `Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}` + ); + await (0, import_helpers.delay)(retryAfterInMs, void 0, { abortSignal: request3.abortSignal }); continue retryRequest; } if (redirectTo) { - strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); + strategyLogger.info( + `Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}` + ); request3.url = redirectTo; continue retryRequest; } } if (responseError) { - logger.info(`None of the retry strategies could work with the received error. Throwing it.`); + logger2.info( + `None of the retry strategies could work with the received error. Throwing it.` + ); throw responseError; } if (response) { - logger.info(`None of the retry strategies could work with the received response. Returning it.`); + logger2.info( + `None of the retry strategies could work with the received response. Returning it.` + ); return response; } } @@ -37139,68 +44918,126 @@ var require_retryPolicy = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/defaultRetryPolicy.js var require_defaultRetryPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/defaultRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.defaultRetryPolicyName = void 0; - exports2.defaultRetryPolicy = defaultRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.defaultRetryPolicyName = "defaultRetryPolicy"; - function defaultRetryPolicy(options = {}) { + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/defaultRetryPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var defaultRetryPolicy_exports = {}; + __export2(defaultRetryPolicy_exports, { + defaultRetryPolicy: () => defaultRetryPolicy2, + defaultRetryPolicyName: () => defaultRetryPolicyName2 + }); + module2.exports = __toCommonJS2(defaultRetryPolicy_exports); + var import_exponentialRetryStrategy = require_exponentialRetryStrategy(); + var import_throttlingRetryStrategy = require_throttlingRetryStrategy(); + var import_retryPolicy = require_retryPolicy(); + var import_constants5 = require_constants8(); + var defaultRetryPolicyName2 = "defaultRetryPolicy"; + function defaultRetryPolicy2(options = {}) { return { - name: exports2.defaultRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], { - maxRetries: options.maxRetries ?? constants_js_1.DEFAULT_RETRY_POLICY_COUNT + name: defaultRetryPolicyName2, + sendRequest: (0, import_retryPolicy.retryPolicy)([(0, import_throttlingRetryStrategy.throttlingRetryStrategy)(), (0, import_exponentialRetryStrategy.exponentialRetryStrategy)(options)], { + maxRetries: options.maxRetries ?? import_constants5.DEFAULT_RETRY_POLICY_COUNT }).sendRequest }; } } }); -// node_modules/@typespec/ts-http-runtime/dist/commonjs/util/checkEnvironment.js -var require_checkEnvironment = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/checkEnvironment.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isReactNative = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; - exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; - exports2.isWebWorker = typeof self === "object" && typeof self?.importScripts === "function" && (self.constructor?.name === "DedicatedWorkerGlobalScope" || self.constructor?.name === "ServiceWorkerGlobalScope" || self.constructor?.name === "SharedWorkerGlobalScope"); - exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; - exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; - exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean(globalThis.process.versions?.node); - exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; - exports2.isReactNative = typeof navigator !== "undefined" && navigator?.product === "ReactNative"; +// node_modules/@typespec/ts-http-runtime/dist/commonjs/formData.js +var require_formData = __commonJS({ + "node_modules/@typespec/ts-http-runtime/dist/commonjs/formData.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var formData_exports = {}; + __export2(formData_exports, { + convertBodyToFormDataMap: () => convertBodyToFormDataMap + }); + module2.exports = __toCommonJS2(formData_exports); + function convertBodyToFormDataMap(body) { + if (typeof FormData !== "undefined" && body instanceof FormData) { + const formDataMap = {}; + for (const [key, value] of body.entries()) { + const existing = formDataMap[key]; + if (Array.isArray(existing)) { + existing.push(value); + } else { + formDataMap[key] = existing !== void 0 ? [existing, value] : [value]; + } + } + return formDataMap; + } + return void 0; + } } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/formDataPolicy.js var require_formDataPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/formDataPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.formDataPolicyName = void 0; - exports2.formDataPolicy = formDataPolicy; - var bytesEncoding_js_1 = require_bytesEncoding(); - var checkEnvironment_js_1 = require_checkEnvironment(); - var httpHeaders_js_1 = require_httpHeaders(); - exports2.formDataPolicyName = "formDataPolicy"; - function formDataToFormDataMap(formData) { - const formDataMap = {}; - for (const [key, value] of formData.entries()) { - formDataMap[key] ??= []; - formDataMap[key].push(value); - } - return formDataMap; - } - function formDataPolicy() { + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/formDataPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var formDataPolicy_exports = {}; + __export2(formDataPolicy_exports, { + formDataPolicy: () => formDataPolicy2, + formDataPolicyName: () => formDataPolicyName2 + }); + module2.exports = __toCommonJS2(formDataPolicy_exports); + var import_bytesEncoding = require_bytesEncoding(); + var import_formData = require_formData(); + var import_httpHeaders = require_httpHeaders(); + var formDataPolicyName2 = "formDataPolicy"; + function formDataPolicy2() { return { - name: exports2.formDataPolicyName, + name: formDataPolicyName2, async sendRequest(request3, next) { - if (checkEnvironment_js_1.isNodeLike && typeof FormData !== "undefined" && request3.body instanceof FormData) { - request3.formData = formDataToFormDataMap(request3.body); + const converted = (0, import_formData.convertBodyToFormDataMap)(request3.body); + if (converted) { + request3.formData = converted; request3.body = void 0; } if (request3.formData) { @@ -37240,17 +45077,22 @@ var require_formDataPolicy = __commonJS({ for (const value of Array.isArray(values) ? values : [values]) { if (typeof value === "string") { parts.push({ - headers: (0, httpHeaders_js_1.createHttpHeaders)({ + headers: (0, import_httpHeaders.createHttpHeaders)({ "Content-Disposition": `form-data; name="${fieldName}"` }), - body: (0, bytesEncoding_js_1.stringToUint8Array)(value, "utf-8") + body: (0, import_bytesEncoding.stringToUint8Array)(value, "utf-8") }); } else if (value === void 0 || value === null || typeof value !== "object") { - throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`); + throw new Error( + `Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.` + ); } else { const fileName = value.name || "blob"; - const headers = (0, httpHeaders_js_1.createHttpHeaders)(); - headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`); + const headers = (0, import_httpHeaders.createHttpHeaders)(); + headers.set( + "Content-Disposition", + `form-data; name="${fieldName}"; filename="${fileName}"` + ); headers.set("Content-Type", value.type || "application/octet-stream"); parts.push({ headers, @@ -37264,6 +45106,88 @@ var require_formDataPolicy = __commonJS({ } }); +// node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/agentPolicy.js +var require_agentPolicy = __commonJS({ + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/agentPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var agentPolicy_exports = {}; + __export2(agentPolicy_exports, { + agentPolicy: () => agentPolicy2, + agentPolicyName: () => agentPolicyName2 + }); + module2.exports = __toCommonJS2(agentPolicy_exports); + var agentPolicyName2 = "agentPolicy"; + function agentPolicy2(agent) { + return { + name: agentPolicyName2, + sendRequest: async (req, next) => { + if (!req.agent) { + req.agent = agent; + } + return next(req); + } + }; + } + } +}); + +// node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/tlsPolicy.js +var require_tlsPolicy = __commonJS({ + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/tlsPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var tlsPolicy_exports = {}; + __export2(tlsPolicy_exports, { + tlsPolicy: () => tlsPolicy2, + tlsPolicyName: () => tlsPolicyName2 + }); + module2.exports = __toCommonJS2(tlsPolicy_exports); + var tlsPolicyName2 = "tlsPolicy"; + function tlsPolicy2(tlsSettings) { + return { + name: tlsPolicyName2, + sendRequest: async (req, next) => { + if (!req.tlsSettings) { + req.tlsSettings = tlsSettings; + } + return next(req); + } + }; + } + } +}); + // node_modules/ms/index.js var require_ms = __commonJS({ "node_modules/ms/index.js"(exports2, module2) { @@ -37277,7 +45201,7 @@ var require_ms = __commonJS({ options = options || {}; var type = typeof val; if (type === "string" && val.length > 0) { - return parse3(val); + return parse4(val); } else if (type === "number" && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } @@ -37285,7 +45209,7 @@ var require_ms = __commonJS({ "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) ); }; - function parse3(str) { + function parse4(str) { str = String(str); if (str.length > 100) { return; @@ -37386,7 +45310,7 @@ var require_common = __commonJS({ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; - createDebug.coerce = coerce3; + createDebug.coerce = coerce4; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; @@ -37541,7 +45465,7 @@ var require_common = __commonJS({ } return false; } - function coerce3(val) { + function coerce4(val) { if (val instanceof Error) { return val.stack || val.message; } @@ -37744,7 +45668,7 @@ var require_has_flag = __commonJS({ var require_supports_color = __commonJS({ "node_modules/supports-color/index.js"(exports2, module2) { "use strict"; - var os7 = require("os"); + var os8 = require("os"); var tty = require("tty"); var hasFlag = require_has_flag(); var { env } = process; @@ -37792,7 +45716,7 @@ var require_supports_color = __commonJS({ return min; } if (process.platform === "win32") { - const osRelease = os7.release().split("."); + const osRelease = os8.release().split("."); if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } @@ -37846,14 +45770,14 @@ var require_supports_color = __commonJS({ var require_node = __commonJS({ "node_modules/debug/src/node.js"(exports2, module2) { var tty = require("tty"); - var util3 = require("util"); + var util4 = require("util"); exports2.init = init2; exports2.log = log; exports2.formatArgs = formatArgs; exports2.save = save; exports2.load = load2; exports2.useColors = useColors; - exports2.destroy = util3.deprecate( + exports2.destroy = util4.deprecate( () => { }, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." @@ -37974,17 +45898,17 @@ var require_node = __commonJS({ args[0] = prefix + args[0].split("\n").join("\n" + prefix); args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); } else { - args[0] = getDate() + name + " " + args[0]; + args[0] = getDate2() + name + " " + args[0]; } } - function getDate() { + function getDate2() { if (exports2.inspectOpts.hideDate) { return ""; } return (/* @__PURE__ */ new Date()).toISOString() + " "; } function log(...args) { - return process.stderr.write(util3.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); + return process.stderr.write(util4.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); } function save(namespaces) { if (namespaces) { @@ -38007,11 +45931,11 @@ var require_node = __commonJS({ var { formatters } = module2.exports; formatters.o = function(v) { this.inspectOpts.colors = this.useColors; - return util3.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); + return util4.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); }; formatters.O = function(v) { this.inspectOpts.colors = this.useColors; - return util3.inspect(v, this.inspectOpts); + return util4.inspect(v, this.inspectOpts); }; } }); @@ -38087,8 +46011,8 @@ var require_helpers3 = __commonJS({ function req(url2, opts = {}) { const href = typeof url2 === "string" ? url2 : url2.href; const req2 = (href.startsWith("https:") ? https3 : http).request(url2, opts); - const promise = new Promise((resolve14, reject) => { - req2.once("response", resolve14).once("error", reject).end(); + const promise = new Promise((resolve15, reject) => { + req2.once("response", resolve15).once("error", reject).end(); }); req2.then = promise.then.bind(promise); return req2; @@ -38098,7 +46022,7 @@ var require_helpers3 = __commonJS({ }); // node_modules/agent-base/dist/index.js -var require_dist2 = __commonJS({ +var require_dist = __commonJS({ "node_modules/agent-base/dist/index.js"(exports2) { "use strict"; var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { @@ -38265,7 +46189,7 @@ var require_parse_proxy_response = __commonJS({ var debug_1 = __importDefault2(require_src()); var debug6 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); function parseProxyResponse(socket) { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { let buffersLength = 0; const buffers = []; function read() { @@ -38331,7 +46255,7 @@ var require_parse_proxy_response = __commonJS({ } debug6("got proxy server response: %o %o", firstLine, headers); cleanup(); - resolve14({ + resolve15({ connect: { statusCode, statusText, @@ -38350,7 +46274,7 @@ var require_parse_proxy_response = __commonJS({ }); // node_modules/https-proxy-agent/dist/index.js -var require_dist3 = __commonJS({ +var require_dist2 = __commonJS({ "node_modules/https-proxy-agent/dist/index.js"(exports2) { "use strict"; var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { @@ -38389,7 +46313,7 @@ var require_dist3 = __commonJS({ var tls = __importStar2(require("tls")); var assert_1 = __importDefault2(require("assert")); var debug_1 = __importDefault2(require_src()); - var agent_base_1 = require_dist2(); + var agent_base_1 = require_dist(); var url_1 = require("url"); var parse_proxy_response_1 = require_parse_proxy_response(); var debug6 = (0, debug_1.default)("https-proxy-agent"); @@ -38500,7 +46424,7 @@ var require_dist3 = __commonJS({ }); // node_modules/http-proxy-agent/dist/index.js -var require_dist4 = __commonJS({ +var require_dist3 = __commonJS({ "node_modules/http-proxy-agent/dist/index.js"(exports2) { "use strict"; var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { @@ -38539,7 +46463,7 @@ var require_dist4 = __commonJS({ var tls = __importStar2(require("tls")); var debug_1 = __importDefault2(require_src()); var events_1 = require("events"); - var agent_base_1 = require_dist2(); + var agent_base_1 = require_dist(); var url_1 = require("url"); var debug6 = (0, debug_1.default)("http-proxy-agent"); var HttpProxyAgent = class extends agent_base_1.Agent { @@ -38631,22 +46555,42 @@ var require_dist4 = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/proxyPolicy.js var require_proxyPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/proxyPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.globalNoProxyList = exports2.proxyPolicyName = void 0; - exports2.loadNoProxy = loadNoProxy; - exports2.getDefaultProxySettings = getDefaultProxySettings; - exports2.proxyPolicy = proxyPolicy; - var https_proxy_agent_1 = require_dist3(); - var http_proxy_agent_1 = require_dist4(); - var log_js_1 = require_log2(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/proxyPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var proxyPolicy_exports = {}; + __export2(proxyPolicy_exports, { + getDefaultProxySettings: () => getDefaultProxySettings2, + globalNoProxyList: () => globalNoProxyList, + loadNoProxy: () => loadNoProxy, + proxyPolicy: () => proxyPolicy2, + proxyPolicyName: () => proxyPolicyName2 + }); + module2.exports = __toCommonJS2(proxyPolicy_exports); + var import_https_proxy_agent2 = require_dist2(); + var import_http_proxy_agent = require_dist3(); + var import_log = require_log2(); var HTTPS_PROXY = "HTTPS_PROXY"; var HTTP_PROXY = "HTTP_PROXY"; var ALL_PROXY = "ALL_PROXY"; var NO_PROXY = "NO_PROXY"; - exports2.proxyPolicyName = "proxyPolicy"; - exports2.globalNoProxyList = []; + var proxyPolicyName2 = "proxyPolicy"; + var globalNoProxyList = []; var noProxyListLoaded = false; var globalBypassedMap = /* @__PURE__ */ new Map(); function getEnvironmentValue(name) { @@ -38701,7 +46645,7 @@ var require_proxyPolicy = __commonJS({ } return []; } - function getDefaultProxySettings(proxyUrl) { + function getDefaultProxySettings2(proxyUrl) { if (!proxyUrl) { proxyUrl = loadEnvironmentProxyValue(); if (!proxyUrl) { @@ -38726,7 +46670,9 @@ var require_proxyPolicy = __commonJS({ try { parsedProxyUrl = new URL(settings.host); } catch { - throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); + throw new Error( + `Expecting a valid host string in proxy settings, but found "${settings.host}".` + ); } parsedProxyUrl.port = String(settings.port); if (settings.username) { @@ -38744,34 +46690,43 @@ var require_proxyPolicy = __commonJS({ const url2 = new URL(request3.url); const isInsecure = url2.protocol !== "https:"; if (request3.tlsSettings) { - log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); + import_log.logger.warning( + "TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored." + ); } - const headers = request3.headers.toJSON(); if (isInsecure) { if (!cachedAgents.httpProxyAgent) { - cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers }); + cachedAgents.httpProxyAgent = new import_http_proxy_agent.HttpProxyAgent(proxyUrl); } request3.agent = cachedAgents.httpProxyAgent; } else { if (!cachedAgents.httpsProxyAgent) { - cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers }); + cachedAgents.httpsProxyAgent = new import_https_proxy_agent2.HttpsProxyAgent(proxyUrl); } request3.agent = cachedAgents.httpsProxyAgent; } } - function proxyPolicy(proxySettings, options) { + function proxyPolicy2(proxySettings, options) { if (!noProxyListLoaded) { - exports2.globalNoProxyList.push(...loadNoProxy()); + globalNoProxyList.push(...loadNoProxy()); } const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal(); const cachedAgents = {}; return { - name: exports2.proxyPolicyName, + name: proxyPolicyName2, async sendRequest(request3, next) { - if (!request3.proxySettings && defaultProxy && !isBypassed(request3.url, options?.customNoProxyList ?? exports2.globalNoProxyList, options?.customNoProxyList ? void 0 : globalBypassedMap)) { + if (!request3.proxySettings && defaultProxy && !isBypassed( + request3.url, + options?.customNoProxyList ?? globalNoProxyList, + options?.customNoProxyList ? void 0 : globalBypassedMap + )) { setProxyAgentOnRequest(request3, cachedAgents, defaultProxy); } else if (request3.proxySettings) { - setProxyAgentOnRequest(request3, cachedAgents, getUrlFromProxySettings(request3.proxySettings)); + setProxyAgentOnRequest( + request3, + cachedAgents, + getUrlFromProxySettings(request3.proxySettings) + ); } return next(request3); } @@ -38780,86 +46735,264 @@ var require_proxyPolicy = __commonJS({ } }); -// node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/agentPolicy.js -var require_agentPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/agentPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.agentPolicyName = void 0; - exports2.agentPolicy = agentPolicy; - exports2.agentPolicyName = "agentPolicy"; - function agentPolicy(agent) { +// node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/decompressResponsePolicy.js +var require_decompressResponsePolicy = __commonJS({ + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/decompressResponsePolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var decompressResponsePolicy_exports = {}; + __export2(decompressResponsePolicy_exports, { + decompressResponsePolicy: () => decompressResponsePolicy2, + decompressResponsePolicyName: () => decompressResponsePolicyName2 + }); + module2.exports = __toCommonJS2(decompressResponsePolicy_exports); + var decompressResponsePolicyName2 = "decompressResponsePolicy"; + function decompressResponsePolicy2() { return { - name: exports2.agentPolicyName, - sendRequest: async (req, next) => { - if (!req.agent) { - req.agent = agent; + name: decompressResponsePolicyName2, + async sendRequest(request3, next) { + if (request3.method !== "HEAD") { + request3.headers.set("Accept-Encoding", "gzip,deflate"); } - return next(req); + return next(request3); } }; } } }); -// node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/tlsPolicy.js -var require_tlsPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/tlsPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.tlsPolicyName = void 0; - exports2.tlsPolicy = tlsPolicy; - exports2.tlsPolicyName = "tlsPolicy"; - function tlsPolicy(tlsSettings) { +// node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/redirectPolicy.js +var require_redirectPolicy = __commonJS({ + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/redirectPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var redirectPolicy_exports = {}; + __export2(redirectPolicy_exports, { + redirectPolicy: () => redirectPolicy2, + redirectPolicyName: () => redirectPolicyName2 + }); + module2.exports = __toCommonJS2(redirectPolicy_exports); + var import_log = require_log2(); + var redirectPolicyName2 = "redirectPolicy"; + var allowedRedirect = ["GET", "HEAD"]; + function redirectPolicy2(options = {}) { + const { maxRetries = 20, allowCrossOriginRedirects = false } = options; return { - name: exports2.tlsPolicyName, - sendRequest: async (req, next) => { - if (!req.tlsSettings) { - req.tlsSettings = tlsSettings; - } - return next(req); + name: redirectPolicyName2, + async sendRequest(request3, next) { + const response = await next(request3); + return handleRedirect(next, response, maxRetries, allowCrossOriginRedirects); } }; } + async function handleRedirect(next, response, maxRetries, allowCrossOriginRedirects, currentRetries = 0) { + const { request: request3, status, headers } = response; + const locationHeader = headers.get("location"); + if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request3.method) || status === 302 && allowedRedirect.includes(request3.method) || status === 303 && request3.method === "POST" || status === 307) && currentRetries < maxRetries) { + const url2 = new URL(locationHeader, request3.url); + if (!allowCrossOriginRedirects) { + const originalUrl = new URL(request3.url); + if (url2.origin !== originalUrl.origin) { + import_log.logger.verbose( + `Skipping cross-origin redirect from ${originalUrl.origin} to ${url2.origin}.` + ); + return response; + } + } + request3.url = url2.toString(); + if (status === 303) { + request3.method = "GET"; + request3.headers.delete("Content-Length"); + delete request3.body; + } + request3.headers.delete("Authorization"); + const res = await next(request3); + return handleRedirect(next, res, maxRetries, allowCrossOriginRedirects, currentRetries + 1); + } + return response; + } } }); -// node_modules/@typespec/ts-http-runtime/dist/commonjs/util/typeGuards.js -var require_typeGuards = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/typeGuards.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isNodeReadableStream = isNodeReadableStream; - exports2.isWebReadableStream = isWebReadableStream; - exports2.isBinaryBody = isBinaryBody; - exports2.isReadableStream = isReadableStream; - exports2.isBlob = isBlob; - function isNodeReadableStream(x) { - return Boolean(x && typeof x["pipe"] === "function"); +// node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/platformPolicies.js +var require_platformPolicies = __commonJS({ + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/platformPolicies.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var platformPolicies_exports = {}; + __export2(platformPolicies_exports, { + addPlatformPolicies: () => addPlatformPolicies + }); + module2.exports = __toCommonJS2(platformPolicies_exports); + var import_agentPolicy = require_agentPolicy(); + var import_tlsPolicy = require_tlsPolicy(); + var import_proxy = require_proxyPolicy(); + var import_decompress = require_decompressResponsePolicy(); + var import_redirectPolicy = require_redirectPolicy(); + function addPlatformPolicies(pipeline2, options) { + if (options.agent) { + pipeline2.addPolicy((0, import_agentPolicy.agentPolicy)(options.agent)); + } + if (options.tlsOptions) { + pipeline2.addPolicy((0, import_tlsPolicy.tlsPolicy)(options.tlsOptions)); + } + pipeline2.addPolicy((0, import_proxy.proxyPolicy)(options.proxyOptions)); + pipeline2.addPolicy((0, import_decompress.decompressResponsePolicy)()); + pipeline2.addPolicy((0, import_redirectPolicy.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" }); } - function isWebReadableStream(x) { - return Boolean(x && typeof x.getReader === "function" && typeof x.tee === "function"); + } +}); + +// node_modules/@typespec/ts-http-runtime/dist/commonjs/util/typeGuards-node.js +var require_typeGuards_node = __commonJS({ + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/typeGuards-node.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var typeGuards_node_exports = {}; + __export2(typeGuards_node_exports, { + isNodeReadableStream: () => isNodeReadableStream2, + isWebReadableStream: () => isWebReadableStream2 + }); + module2.exports = __toCommonJS2(typeGuards_node_exports); + var import_stream10 = require("stream"); + function isNodeReadableStream2(x) { + return x instanceof import_stream10.Readable; } + function isWebReadableStream2(x) { + return x instanceof ReadableStream; + } + } +}); + +// node_modules/@typespec/ts-http-runtime/dist/commonjs/util/typeGuards.js +var require_typeGuards = __commonJS({ + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/typeGuards.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var typeGuards_exports = {}; + __export2(typeGuards_exports, { + isBinaryBody: () => isBinaryBody, + isBlob: () => isBlob, + isNodeReadableStream: () => import_typeGuards.isNodeReadableStream, + isReadableStream: () => isReadableStream, + isWebReadableStream: () => import_typeGuards.isWebReadableStream + }); + module2.exports = __toCommonJS2(typeGuards_exports); + var import_typeGuards = require_typeGuards_node(); function isBinaryBody(body) { return body !== void 0 && (body instanceof Uint8Array || isReadableStream(body) || typeof body === "function" || body instanceof Blob); } function isReadableStream(x) { - return isNodeReadableStream(x) || isWebReadableStream(x); + return (0, import_typeGuards.isNodeReadableStream)(x) || (0, import_typeGuards.isWebReadableStream)(x); } function isBlob(x) { - return typeof x.stream === "function"; + return x instanceof Blob; } } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/util/concat.js var require_concat = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/concat.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.concat = concat; - var stream_1 = require("stream"); - var typeGuards_js_1 = require_typeGuards(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/concat.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var concat_exports = {}; + __export2(concat_exports, { + concat: () => concat + }); + module2.exports = __toCommonJS2(concat_exports); + var import_stream10 = require("stream"); + var import_typeGuards = require_typeGuards(); async function* streamAsyncIterator() { const reader = this.getReader(); try { @@ -38885,15 +47018,15 @@ var require_concat = __commonJS({ function ensureNodeStream(stream2) { if (stream2 instanceof ReadableStream) { makeAsyncIterable(stream2); - return stream_1.Readable.fromWeb(stream2); + return import_stream10.Readable.fromWeb(stream2); } else { return stream2; } } function toStream(source) { if (source instanceof Uint8Array) { - return stream_1.Readable.from(Buffer.from(source)); - } else if ((0, typeGuards_js_1.isBlob)(source)) { + return import_stream10.Readable.from(Buffer.from(source)); + } else if ((0, import_typeGuards.isBlob)(source)) { return ensureNodeStream(source.stream()); } else { return ensureNodeStream(source); @@ -38902,13 +47035,15 @@ var require_concat = __commonJS({ async function concat(sources) { return function() { const streams = sources.map((x) => typeof x === "function" ? x() : x).map(toStream); - return stream_1.Readable.from((async function* () { - for (const stream2 of streams) { - for await (const chunk of stream2) { - yield chunk; + return import_stream10.Readable.from( + (async function* () { + for (const stream2 of streams) { + for await (const chunk of stream2) { + yield chunk; + } } - } - })()); + })() + ); }; } } @@ -38916,17 +47051,36 @@ var require_concat = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/multipartPolicy.js var require_multipartPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/multipartPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.multipartPolicyName = void 0; - exports2.multipartPolicy = multipartPolicy; - var bytesEncoding_js_1 = require_bytesEncoding(); - var typeGuards_js_1 = require_typeGuards(); - var uuidUtils_js_1 = require_uuidUtils(); - var concat_js_1 = require_concat(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/multipartPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var multipartPolicy_exports = {}; + __export2(multipartPolicy_exports, { + multipartPolicy: () => multipartPolicy2, + multipartPolicyName: () => multipartPolicyName2 + }); + module2.exports = __toCommonJS2(multipartPolicy_exports); + var import_bytesEncoding = require_bytesEncoding(); + var import_typeGuards = require_typeGuards(); + var import_uuid2 = require_uuidUtils(); + var import_concat = require_concat(); function generateBoundary() { - return `----AzSDKFormBoundary${(0, uuidUtils_js_1.randomUUID)()}`; + return `----AzSDKFormBoundary${(0, import_uuid2.randomUUID)()}`; } function encodeHeaders(headers) { let result = ""; @@ -38939,7 +47093,7 @@ var require_multipartPolicy = __commonJS({ function getLength(source) { if (source instanceof Uint8Array) { return source.byteLength; - } else if ((0, typeGuards_js_1.isBlob)(source)) { + } else if ((0, import_typeGuards.isBlob)(source)) { return source.size === -1 ? void 0 : source.size; } else { return void 0; @@ -38959,26 +47113,28 @@ var require_multipartPolicy = __commonJS({ } async function buildRequestBody(request3, parts, boundary) { const sources = [ - (0, bytesEncoding_js_1.stringToUint8Array)(`--${boundary}`, "utf-8"), + (0, import_bytesEncoding.stringToUint8Array)(`--${boundary}`, "utf-8"), ...parts.flatMap((part) => [ - (0, bytesEncoding_js_1.stringToUint8Array)("\r\n", "utf-8"), - (0, bytesEncoding_js_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"), - (0, bytesEncoding_js_1.stringToUint8Array)("\r\n", "utf-8"), + (0, import_bytesEncoding.stringToUint8Array)("\r\n", "utf-8"), + (0, import_bytesEncoding.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"), + (0, import_bytesEncoding.stringToUint8Array)("\r\n", "utf-8"), part.body, - (0, bytesEncoding_js_1.stringToUint8Array)(`\r + (0, import_bytesEncoding.stringToUint8Array)(`\r --${boundary}`, "utf-8") ]), - (0, bytesEncoding_js_1.stringToUint8Array)("--\r\n\r\n", "utf-8") + (0, import_bytesEncoding.stringToUint8Array)("--\r\n\r\n", "utf-8") ]; const contentLength = getTotalLength(sources); if (contentLength) { request3.headers.set("Content-Length", contentLength); } - request3.body = await (0, concat_js_1.concat)(sources); + request3.body = await (0, import_concat.concat)(sources); } - exports2.multipartPolicyName = "multipartPolicy"; + var multipartPolicyName2 = "multipartPolicy"; var maxBoundaryLength = 70; - var validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`); + var validBoundaryCharacters = new Set( + `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?` + ); function assertValidBoundary(boundary) { if (boundary.length > maxBoundaryLength) { throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`); @@ -38987,9 +47143,9 @@ var require_multipartPolicy = __commonJS({ throw new Error(`Multipart boundary "${boundary}" contains invalid characters`); } } - function multipartPolicy() { + function multipartPolicy2() { return { - name: exports2.multipartPolicyName, + name: multipartPolicyName2, async sendRequest(request3, next) { if (!request3.multipartBody) { return next(request3); @@ -39001,11 +47157,15 @@ var require_multipartPolicy = __commonJS({ const contentTypeHeader = request3.headers.get("Content-Type") ?? "multipart/mixed"; const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); if (!parsedHeader) { - throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); + throw new Error( + `Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}` + ); } const [, contentType, parsedBoundary] = parsedHeader; if (parsedBoundary && boundary && parsedBoundary !== boundary) { - throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); + throw new Error( + `Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body` + ); } boundary ??= parsedBoundary; if (boundary) { @@ -39025,42 +47185,44 @@ var require_multipartPolicy = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/createPipelineFromOptions.js var require_createPipelineFromOptions = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/createPipelineFromOptions.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createPipelineFromOptions = createPipelineFromOptions; - var logPolicy_js_1 = require_logPolicy(); - var pipeline_js_1 = require_pipeline(); - var redirectPolicy_js_1 = require_redirectPolicy(); - var userAgentPolicy_js_1 = require_userAgentPolicy(); - var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); - var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); - var formDataPolicy_js_1 = require_formDataPolicy(); - var checkEnvironment_js_1 = require_checkEnvironment(); - var proxyPolicy_js_1 = require_proxyPolicy(); - var agentPolicy_js_1 = require_agentPolicy(); - var tlsPolicy_js_1 = require_tlsPolicy(); - var multipartPolicy_js_1 = require_multipartPolicy(); - function createPipelineFromOptions(options) { - const pipeline2 = (0, pipeline_js_1.createEmptyPipeline)(); - if (checkEnvironment_js_1.isNodeLike) { - if (options.agent) { - pipeline2.addPolicy((0, agentPolicy_js_1.agentPolicy)(options.agent)); - } - if (options.tlsOptions) { - pipeline2.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions)); - } - pipeline2.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions)); - pipeline2.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)()); - } - pipeline2.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] }); - pipeline2.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions)); - pipeline2.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" }); - pipeline2.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); - if (checkEnvironment_js_1.isNodeLike) { - pipeline2.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" }); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/createPipelineFromOptions.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - pipeline2.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" }); + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var createPipelineFromOptions_exports = {}; + __export2(createPipelineFromOptions_exports, { + createPipelineFromOptions: () => createPipelineFromOptions2 + }); + module2.exports = __toCommonJS2(createPipelineFromOptions_exports); + var import_logPolicy = require_logPolicy(); + var import_pipeline = require_pipeline(); + var import_userAgentPolicy = require_userAgentPolicy(); + var import_defaultRetryPolicy = require_defaultRetryPolicy(); + var import_formDataPolicy = require_formDataPolicy(); + var import_policies = require_platformPolicies(); + var import_multipartPolicy = require_multipartPolicy(); + function createPipelineFromOptions2(options) { + const pipeline2 = (0, import_pipeline.createEmptyPipeline)(); + (0, import_policies.addPlatformPolicies)(pipeline2, options); + pipeline2.addPolicy((0, import_formDataPolicy.formDataPolicy)(), { beforePolicies: [import_multipartPolicy.multipartPolicyName] }); + pipeline2.addPolicy((0, import_userAgentPolicy.userAgentPolicy)(options.userAgentOptions)); + pipeline2.addPolicy((0, import_multipartPolicy.multipartPolicy)(), { afterPhase: "Deserialize" }); + pipeline2.addPolicy((0, import_defaultRetryPolicy.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); + pipeline2.addPolicy((0, import_logPolicy.logPolicy)(options.loggingOptions), { afterPhase: "Sign" }); return pipeline2; } } @@ -39068,15 +47230,34 @@ var require_createPipelineFromOptions = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/client/apiVersionPolicy.js var require_apiVersionPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/apiVersionPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.apiVersionPolicyName = void 0; - exports2.apiVersionPolicy = apiVersionPolicy; - exports2.apiVersionPolicyName = "ApiVersionPolicy"; + "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/apiVersionPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var apiVersionPolicy_exports = {}; + __export2(apiVersionPolicy_exports, { + apiVersionPolicy: () => apiVersionPolicy, + apiVersionPolicyName: () => apiVersionPolicyName + }); + module2.exports = __toCommonJS2(apiVersionPolicy_exports); + var apiVersionPolicyName = "ApiVersionPolicy"; function apiVersionPolicy(options) { return { - name: exports2.apiVersionPolicyName, + name: apiVersionPolicyName, sendRequest: (req, next) => { const url2 = new URL(req.url); if (!url2.searchParams.get("api-version") && options.apiVersion) { @@ -39091,13 +47272,32 @@ var require_apiVersionPolicy = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/auth/credentials.js var require_credentials = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/auth/credentials.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isOAuth2TokenCredential = isOAuth2TokenCredential; - exports2.isBearerTokenCredential = isBearerTokenCredential; - exports2.isBasicCredential = isBasicCredential; - exports2.isApiKeyCredential = isApiKeyCredential; + "node_modules/@typespec/ts-http-runtime/dist/commonjs/auth/credentials.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var credentials_exports = {}; + __export2(credentials_exports, { + isApiKeyCredential: () => isApiKeyCredential, + isBasicCredential: () => isBasicCredential, + isBearerTokenCredential: () => isBearerTokenCredential, + isOAuth2TokenCredential: () => isOAuth2TokenCredential + }); + module2.exports = __toCommonJS2(credentials_exports); function isOAuth2TokenCredential(credential) { return "getOAuth2Token" in credential; } @@ -39115,11 +47315,31 @@ var require_credentials = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/checkInsecureConnection.js var require_checkInsecureConnection = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/checkInsecureConnection.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ensureSecureConnection = ensureSecureConnection; - var log_js_1 = require_log2(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/checkInsecureConnection.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var checkInsecureConnection_exports = {}; + __export2(checkInsecureConnection_exports, { + ensureSecureConnection: () => ensureSecureConnection + }); + module2.exports = __toCommonJS2(checkInsecureConnection_exports); + var import_log = require_log2(); + var import_env = require_env(); var insecureConnectionWarningEmmitted = false; function allowInsecureConnection(request3, options) { if (options.allowInsecureConnection && request3.allowInsecureConnection) { @@ -39132,10 +47352,10 @@ var require_checkInsecureConnection = __commonJS({ } function emitInsecureConnectionWarning() { const warning14 = "Sending token over insecure transport. Assume any token issued is compromised."; - log_js_1.logger.warning(warning14); - if (typeof process?.emitWarning === "function" && !insecureConnectionWarningEmmitted) { + import_log.logger.warning(warning14); + if (!insecureConnectionWarningEmmitted) { insecureConnectionWarningEmmitted = true; - process.emitWarning(warning14); + (0, import_env.emitNodeWarning)(warning14); } } function ensureSecureConnection(request3, options) { @@ -39143,7 +47363,9 @@ var require_checkInsecureConnection = __commonJS({ if (allowInsecureConnection(request3, options)) { emitInsecureConnectionWarning(); } else { - throw new Error("Authentication is not permitted for non-TLS protected (non-https) URLs when allowInsecureConnection is false."); + throw new Error( + "Authentication is not permitted for non-TLS protected (non-https) URLs when allowInsecureConnection is false." + ); } } } @@ -39152,18 +47374,37 @@ var require_checkInsecureConnection = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/apiKeyAuthenticationPolicy.js var require_apiKeyAuthenticationPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/apiKeyAuthenticationPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.apiKeyAuthenticationPolicyName = void 0; - exports2.apiKeyAuthenticationPolicy = apiKeyAuthenticationPolicy; - var checkInsecureConnection_js_1 = require_checkInsecureConnection(); - exports2.apiKeyAuthenticationPolicyName = "apiKeyAuthenticationPolicy"; + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/apiKeyAuthenticationPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var apiKeyAuthenticationPolicy_exports = {}; + __export2(apiKeyAuthenticationPolicy_exports, { + apiKeyAuthenticationPolicy: () => apiKeyAuthenticationPolicy, + apiKeyAuthenticationPolicyName: () => apiKeyAuthenticationPolicyName + }); + module2.exports = __toCommonJS2(apiKeyAuthenticationPolicy_exports); + var import_checkInsecureConnection = require_checkInsecureConnection(); + var apiKeyAuthenticationPolicyName = "apiKeyAuthenticationPolicy"; function apiKeyAuthenticationPolicy(options) { return { - name: exports2.apiKeyAuthenticationPolicyName, + name: apiKeyAuthenticationPolicyName, async sendRequest(request3, next) { - (0, checkInsecureConnection_js_1.ensureSecureConnection)(request3, options); + (0, import_checkInsecureConnection.ensureSecureConnection)(request3, options); const scheme = (request3.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "apiKey"); if (!scheme) { return next(request3); @@ -39181,25 +47422,49 @@ var require_apiKeyAuthenticationPolicy = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/basicAuthenticationPolicy.js var require_basicAuthenticationPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/basicAuthenticationPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.basicAuthenticationPolicyName = void 0; - exports2.basicAuthenticationPolicy = basicAuthenticationPolicy; - var bytesEncoding_js_1 = require_bytesEncoding(); - var checkInsecureConnection_js_1 = require_checkInsecureConnection(); - exports2.basicAuthenticationPolicyName = "bearerAuthenticationPolicy"; + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/basicAuthenticationPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var basicAuthenticationPolicy_exports = {}; + __export2(basicAuthenticationPolicy_exports, { + basicAuthenticationPolicy: () => basicAuthenticationPolicy, + basicAuthenticationPolicyName: () => basicAuthenticationPolicyName + }); + module2.exports = __toCommonJS2(basicAuthenticationPolicy_exports); + var import_bytesEncoding = require_bytesEncoding(); + var import_checkInsecureConnection = require_checkInsecureConnection(); + var basicAuthenticationPolicyName = "bearerAuthenticationPolicy"; function basicAuthenticationPolicy(options) { return { - name: exports2.basicAuthenticationPolicyName, + name: basicAuthenticationPolicyName, async sendRequest(request3, next) { - (0, checkInsecureConnection_js_1.ensureSecureConnection)(request3, options); - const scheme = (request3.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "http" && x.scheme === "basic"); + (0, import_checkInsecureConnection.ensureSecureConnection)(request3, options); + const scheme = (request3.authSchemes ?? options.authSchemes)?.find( + (x) => x.kind === "http" && x.scheme === "basic" + ); if (!scheme) { return next(request3); } const { username, password } = options.credential; - const headerValue = (0, bytesEncoding_js_1.uint8ArrayToString)((0, bytesEncoding_js_1.stringToUint8Array)(`${username}:${password}`, "utf-8"), "base64"); + const headerValue = (0, import_bytesEncoding.uint8ArrayToString)( + (0, import_bytesEncoding.stringToUint8Array)(`${username}:${password}`, "utf-8"), + "base64" + ); request3.headers.set("Authorization", `Basic ${headerValue}`); return next(request3); } @@ -39210,19 +47475,40 @@ var require_basicAuthenticationPolicy = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/bearerAuthenticationPolicy.js var require_bearerAuthenticationPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/bearerAuthenticationPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.bearerAuthenticationPolicyName = void 0; - exports2.bearerAuthenticationPolicy = bearerAuthenticationPolicy; - var checkInsecureConnection_js_1 = require_checkInsecureConnection(); - exports2.bearerAuthenticationPolicyName = "bearerAuthenticationPolicy"; + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/bearerAuthenticationPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var bearerAuthenticationPolicy_exports = {}; + __export2(bearerAuthenticationPolicy_exports, { + bearerAuthenticationPolicy: () => bearerAuthenticationPolicy, + bearerAuthenticationPolicyName: () => bearerAuthenticationPolicyName + }); + module2.exports = __toCommonJS2(bearerAuthenticationPolicy_exports); + var import_checkInsecureConnection = require_checkInsecureConnection(); + var bearerAuthenticationPolicyName = "bearerAuthenticationPolicy"; function bearerAuthenticationPolicy(options) { return { - name: exports2.bearerAuthenticationPolicyName, + name: bearerAuthenticationPolicyName, async sendRequest(request3, next) { - (0, checkInsecureConnection_js_1.ensureSecureConnection)(request3, options); - const scheme = (request3.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "http" && x.scheme === "bearer"); + (0, import_checkInsecureConnection.ensureSecureConnection)(request3, options); + const scheme = (request3.authSchemes ?? options.authSchemes)?.find( + (x) => x.kind === "http" && x.scheme === "bearer" + ); if (!scheme) { return next(request3); } @@ -39239,18 +47525,37 @@ var require_bearerAuthenticationPolicy = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/oauth2AuthenticationPolicy.js var require_oauth2AuthenticationPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/oauth2AuthenticationPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.oauth2AuthenticationPolicyName = void 0; - exports2.oauth2AuthenticationPolicy = oauth2AuthenticationPolicy; - var checkInsecureConnection_js_1 = require_checkInsecureConnection(); - exports2.oauth2AuthenticationPolicyName = "oauth2AuthenticationPolicy"; + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/auth/oauth2AuthenticationPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var oauth2AuthenticationPolicy_exports = {}; + __export2(oauth2AuthenticationPolicy_exports, { + oauth2AuthenticationPolicy: () => oauth2AuthenticationPolicy, + oauth2AuthenticationPolicyName: () => oauth2AuthenticationPolicyName + }); + module2.exports = __toCommonJS2(oauth2AuthenticationPolicy_exports); + var import_checkInsecureConnection = require_checkInsecureConnection(); + var oauth2AuthenticationPolicyName = "oauth2AuthenticationPolicy"; function oauth2AuthenticationPolicy(options) { return { - name: exports2.oauth2AuthenticationPolicyName, + name: oauth2AuthenticationPolicyName, async sendRequest(request3, next) { - (0, checkInsecureConnection_js_1.ensureSecureConnection)(request3, options); + (0, import_checkInsecureConnection.ensureSecureConnection)(request3, options); const scheme = (request3.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "oauth2"); if (!scheme) { return next(request3); @@ -39268,40 +47573,67 @@ var require_oauth2AuthenticationPolicy = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/client/clientHelpers.js var require_clientHelpers = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/clientHelpers.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createDefaultPipeline = createDefaultPipeline; - exports2.getCachedDefaultHttpsClient = getCachedDefaultHttpsClient; - var defaultHttpClient_js_1 = require_defaultHttpClient(); - var createPipelineFromOptions_js_1 = require_createPipelineFromOptions(); - var apiVersionPolicy_js_1 = require_apiVersionPolicy(); - var credentials_js_1 = require_credentials(); - var apiKeyAuthenticationPolicy_js_1 = require_apiKeyAuthenticationPolicy(); - var basicAuthenticationPolicy_js_1 = require_basicAuthenticationPolicy(); - var bearerAuthenticationPolicy_js_1 = require_bearerAuthenticationPolicy(); - var oauth2AuthenticationPolicy_js_1 = require_oauth2AuthenticationPolicy(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/clientHelpers.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var clientHelpers_exports = {}; + __export2(clientHelpers_exports, { + createDefaultPipeline: () => createDefaultPipeline, + getCachedDefaultHttpsClient: () => getCachedDefaultHttpsClient + }); + module2.exports = __toCommonJS2(clientHelpers_exports); + var import_httpClient = require_defaultHttpClient(); + var import_createPipelineFromOptions = require_createPipelineFromOptions(); + var import_apiVersionPolicy = require_apiVersionPolicy(); + var import_credentials = require_credentials(); + var import_apiKeyAuthenticationPolicy = require_apiKeyAuthenticationPolicy(); + var import_basicAuthenticationPolicy = require_basicAuthenticationPolicy(); + var import_bearerAuthenticationPolicy = require_bearerAuthenticationPolicy(); + var import_oauth2AuthenticationPolicy = require_oauth2AuthenticationPolicy(); var cachedHttpClient; function createDefaultPipeline(options = {}) { - const pipeline2 = (0, createPipelineFromOptions_js_1.createPipelineFromOptions)(options); - pipeline2.addPolicy((0, apiVersionPolicy_js_1.apiVersionPolicy)(options)); + const pipeline2 = (0, import_createPipelineFromOptions.createPipelineFromOptions)(options); + pipeline2.addPolicy((0, import_apiVersionPolicy.apiVersionPolicy)(options)); const { credential, authSchemes, allowInsecureConnection } = options; if (credential) { - if ((0, credentials_js_1.isApiKeyCredential)(credential)) { - pipeline2.addPolicy((0, apiKeyAuthenticationPolicy_js_1.apiKeyAuthenticationPolicy)({ authSchemes, credential, allowInsecureConnection })); - } else if ((0, credentials_js_1.isBasicCredential)(credential)) { - pipeline2.addPolicy((0, basicAuthenticationPolicy_js_1.basicAuthenticationPolicy)({ authSchemes, credential, allowInsecureConnection })); - } else if ((0, credentials_js_1.isBearerTokenCredential)(credential)) { - pipeline2.addPolicy((0, bearerAuthenticationPolicy_js_1.bearerAuthenticationPolicy)({ authSchemes, credential, allowInsecureConnection })); - } else if ((0, credentials_js_1.isOAuth2TokenCredential)(credential)) { - pipeline2.addPolicy((0, oauth2AuthenticationPolicy_js_1.oauth2AuthenticationPolicy)({ authSchemes, credential, allowInsecureConnection })); + if ((0, import_credentials.isApiKeyCredential)(credential)) { + pipeline2.addPolicy( + (0, import_apiKeyAuthenticationPolicy.apiKeyAuthenticationPolicy)({ authSchemes, credential, allowInsecureConnection }) + ); + } else if ((0, import_credentials.isBasicCredential)(credential)) { + pipeline2.addPolicy( + (0, import_basicAuthenticationPolicy.basicAuthenticationPolicy)({ authSchemes, credential, allowInsecureConnection }) + ); + } else if ((0, import_credentials.isBearerTokenCredential)(credential)) { + pipeline2.addPolicy( + (0, import_bearerAuthenticationPolicy.bearerAuthenticationPolicy)({ authSchemes, credential, allowInsecureConnection }) + ); + } else if ((0, import_credentials.isOAuth2TokenCredential)(credential)) { + pipeline2.addPolicy( + (0, import_oauth2AuthenticationPolicy.oauth2AuthenticationPolicy)({ authSchemes, credential, allowInsecureConnection }) + ); } } return pipeline2; } function getCachedDefaultHttpsClient() { if (!cachedHttpClient) { - cachedHttpClient = (0, defaultHttpClient_js_1.createDefaultHttpClient)(); + cachedHttpClient = (0, import_httpClient.createDefaultHttpClient)(); } return cachedHttpClient; } @@ -39310,18 +47642,39 @@ var require_clientHelpers = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/client/multipart.js var require_multipart = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/multipart.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.buildBodyPart = buildBodyPart; - exports2.buildMultipartBody = buildMultipartBody; - var restError_js_1 = require_restError(); - var httpHeaders_js_1 = require_httpHeaders(); - var bytesEncoding_js_1 = require_bytesEncoding(); - var typeGuards_js_1 = require_typeGuards(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/multipart.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var multipart_exports = {}; + __export2(multipart_exports, { + buildBodyPart: () => buildBodyPart, + buildMultipartBody: () => buildMultipartBody + }); + module2.exports = __toCommonJS2(multipart_exports); + var import_restError = require_restError(); + var import_httpHeaders = require_httpHeaders(); + var import_bytesEncoding = require_bytesEncoding(); + var import_typeGuards = require_typeGuards(); function getHeaderValue(descriptor, headerName) { if (descriptor.headers) { - const actualHeaderName = Object.keys(descriptor.headers).find((x) => x.toLowerCase() === headerName.toLowerCase()); + const actualHeaderName = Object.keys(descriptor.headers).find( + (x) => x.toLowerCase() === headerName.toLowerCase() + ); if (actualHeaderName) { return descriptor.headers[actualHeaderName]; } @@ -39349,7 +47702,7 @@ var require_multipart = __commonJS({ if (body instanceof Blob) { return body.type || "application/octet-stream"; } - if ((0, typeGuards_js_1.isBinaryBody)(body)) { + if ((0, import_typeGuards.isBinaryBody)(body)) { return "application/octet-stream"; } return "application/json"; @@ -39388,21 +47741,21 @@ var require_multipart = __commonJS({ if (body === void 0) { return new Uint8Array([]); } - if ((0, typeGuards_js_1.isBinaryBody)(body)) { + if ((0, import_typeGuards.isBinaryBody)(body)) { return body; } if (typeof body === "string" || typeof body === "number" || typeof body === "boolean") { - return (0, bytesEncoding_js_1.stringToUint8Array)(String(body), "utf-8"); + return (0, import_bytesEncoding.stringToUint8Array)(String(body), "utf-8"); } if (contentType && /application\/(.+\+)?json(;.+)?/i.test(String(contentType))) { - return (0, bytesEncoding_js_1.stringToUint8Array)(JSON.stringify(body), "utf-8"); + return (0, import_bytesEncoding.stringToUint8Array)(JSON.stringify(body), "utf-8"); } - throw new restError_js_1.RestError(`Unsupported body/content-type combination: ${body}, ${contentType}`); + throw new import_restError.RestError(`Unsupported body/content-type combination: ${body}, ${contentType}`); } function buildBodyPart(descriptor) { const contentType = getPartContentType(descriptor); const contentDisposition = getContentDisposition(descriptor); - const headers = (0, httpHeaders_js_1.createHttpHeaders)(descriptor.headers ?? {}); + const headers = (0, import_httpHeaders.createHttpHeaders)(descriptor.headers ?? {}); if (contentType) { headers.set("content-type", contentType); } @@ -39423,18 +47776,38 @@ var require_multipart = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/client/sendRequest.js var require_sendRequest = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/sendRequest.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.sendRequest = sendRequest; - var restError_js_1 = require_restError(); - var httpHeaders_js_1 = require_httpHeaders(); - var pipelineRequest_js_1 = require_pipelineRequest(); - var clientHelpers_js_1 = require_clientHelpers(); - var typeGuards_js_1 = require_typeGuards(); - var multipart_js_1 = require_multipart(); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/sendRequest.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var sendRequest_exports = {}; + __export2(sendRequest_exports, { + getRequestBody: () => getRequestBody, + sendRequest: () => sendRequest + }); + module2.exports = __toCommonJS2(sendRequest_exports); + var import_restError = require_restError(); + var import_httpHeaders = require_httpHeaders(); + var import_pipelineRequest = require_pipelineRequest(); + var import_clientHelpers = require_clientHelpers(); + var import_typeGuards = require_typeGuards(); + var import_multipart = require_multipart(); async function sendRequest(method, url2, pipeline2, options = {}, customHttpClient) { - const httpClient = customHttpClient ?? (0, clientHelpers_js_1.getCachedDefaultHttpsClient)(); + const httpClient = customHttpClient ?? (0, import_clientHelpers.getCachedDefaultHttpsClient)(); const request3 = buildPipelineRequest(method, url2, options); try { const response = await pipeline2.sendRequest(httpClient, request3); @@ -39452,7 +47825,7 @@ var require_sendRequest = __commonJS({ body }; } catch (e) { - if ((0, restError_js_1.isRestError)(e) && e.response && options.onResponse) { + if ((0, import_restError.isRestError)(e) && e.response && options.onResponse) { const { response } = e; const rawHeaders = response.headers.toJSON(); options?.onResponse({ ...response, request: request3, rawHeaders }, e); @@ -39461,12 +47834,25 @@ var require_sendRequest = __commonJS({ } } function getRequestContentType(options = {}) { - return options.contentType ?? options.headers?.["content-type"] ?? getContentType(options.body); + if (options.contentType) { + return options.contentType; + } + const headerContentType = options.headers?.["content-type"]; + if (typeof headerContentType === "string") { + return headerContentType; + } + return getContentType(options.body); } function getContentType(body) { + if (body === void 0) { + return void 0; + } if (ArrayBuffer.isView(body)) { return "application/octet-stream"; } + if ((0, import_typeGuards.isBlob)(body) && body.type) { + return body.type; + } if (typeof body === "string") { try { JSON.parse(body); @@ -39480,28 +47866,45 @@ var require_sendRequest = __commonJS({ function buildPipelineRequest(method, url2, options = {}) { const requestContentType = getRequestContentType(options); const { body, multipartBody } = getRequestBody(options.body, requestContentType); - const hasContent = body !== void 0 || multipartBody !== void 0; - const headers = (0, httpHeaders_js_1.createHttpHeaders)({ + const accept = options.accept ?? options.headers?.accept ?? (options.noDefaultAcceptHeader ? void 0 : "application/json"); + const headers = (0, import_httpHeaders.createHttpHeaders)({ ...options.headers ? options.headers : {}, - accept: options.accept ?? options.headers?.accept ?? "application/json", - ...hasContent && requestContentType && { + ...accept !== void 0 && { accept }, + ...requestContentType && { "content-type": requestContentType } }); - return (0, pipelineRequest_js_1.createPipelineRequest)({ + const { + allowInsecureConnection, + abortSignal, + onUploadProgress, + onDownloadProgress, + timeout, + responseAsStream, + noDefaultAcceptHeader: _noDefaultAcceptHeader, + url: _url, + method: _method, + body: _body, + multipartBody: _multiBody, + headers: _headers, + ...rest + } = options; + const request3 = (0, import_pipelineRequest.createPipelineRequest)({ url: url2, method, body, multipartBody, headers, - allowInsecureConnection: options.allowInsecureConnection, - abortSignal: options.abortSignal, - onUploadProgress: options.onUploadProgress, - onDownloadProgress: options.onDownloadProgress, - timeout: options.timeout, + allowInsecureConnection, + abortSignal, + onUploadProgress, + onDownloadProgress, + timeout, enableBrowserStreams: true, - streamResponseStatusCodes: options.responseAsStream ? /* @__PURE__ */ new Set([Number.POSITIVE_INFINITY]) : void 0 + streamResponseStatusCodes: responseAsStream ? /* @__PURE__ */ new Set([Number.POSITIVE_INFINITY]) : void 0 }); + Object.assign(request3, rest); + return request3; } function getRequestBody(body, contentType = "") { if (body === void 0) { @@ -39510,11 +47913,19 @@ var require_sendRequest = __commonJS({ if (typeof FormData !== "undefined" && body instanceof FormData) { return { body }; } - if ((0, typeGuards_js_1.isReadableStream)(body)) { + if ((0, import_typeGuards.isBlob)(body)) { + return { body }; + } + if ((0, import_typeGuards.isReadableStream)(body)) { + return { body }; + } + if (typeof body === "function") { return { body }; } if (ArrayBuffer.isView(body)) { - return { body: body instanceof Uint8Array ? body : JSON.stringify(body) }; + return { + body: body instanceof Uint8Array ? body : JSON.stringify(body) + }; } const firstType = contentType.split(";")[0]; switch (firstType) { @@ -39522,7 +47933,7 @@ var require_sendRequest = __commonJS({ return { body: JSON.stringify(body) }; case "multipart/form-data": if (Array.isArray(body)) { - return { multipartBody: (0, multipart_js_1.buildMultipartBody)(body) }; + return { multipartBody: (0, import_multipart.buildMultipartBody)(body) }; } return { body: JSON.stringify(body) }; case "text/plain": @@ -39552,8 +47963,8 @@ var require_sendRequest = __commonJS({ } function createParseError(response, err) { const msg = `Error "${err}" occurred while parsing the response body - ${response.bodyAsText}.`; - const errCode = err.code ?? restError_js_1.RestError.PARSE_ERROR; - return new restError_js_1.RestError(msg, { + const errCode = err.code ?? import_restError.RestError.PARSE_ERROR; + return new import_restError.RestError(msg, { code: errCode, statusCode: response.status, request: response.request, @@ -39565,25 +47976,69 @@ var require_sendRequest = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/client/urlHelpers.js var require_urlHelpers = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/urlHelpers.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.buildRequestUrl = buildRequestUrl; - exports2.buildBaseUrl = buildBaseUrl; - exports2.replaceAll = replaceAll; + "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/urlHelpers.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var urlHelpers_exports = {}; + __export2(urlHelpers_exports, { + appendQueryParams: () => appendQueryParams, + buildBaseUrl: () => buildBaseUrl, + buildRequestUrl: () => buildRequestUrl, + replaceAll: () => replaceAll + }); + module2.exports = __toCommonJS2(urlHelpers_exports); function isQueryParameterWithOptions(x) { + if (typeof x !== "object" || x === null || !Object.hasOwn(x, "value")) { + return false; + } const value = x.value; - return value !== void 0 && value.toString !== void 0 && typeof value.toString === "function"; + return typeof value?.toString === "function"; } function buildRequestUrl(endpoint2, routePath, pathParameters, options = {}) { if (routePath.startsWith("https://") || routePath.startsWith("http://")) { return routePath; } endpoint2 = buildBaseUrl(endpoint2, options); - routePath = buildRoutePath(routePath, pathParameters, options); - const requestUrl = appendQueryParams(`${endpoint2}/${routePath}`, options); + const updatedRoutePath = buildRoutePath(routePath, pathParameters, options); + const requestUrl = appendQueryParams(appendPath(endpoint2, updatedRoutePath), options); const url2 = new URL(requestUrl); - return url2.toString().replace(/([^:]\/)\/+/g, "$1"); + return url2.toString(); + } + function appendPath(endpoint2, pathToAppend) { + const endpointSearchStart = endpoint2.indexOf("?"); + const pathSearchStart = pathToAppend.indexOf("?"); + const endpointParts = endpointSearchStart !== -1 ? [endpoint2.substring(0, endpointSearchStart), endpoint2.substring(endpointSearchStart + 1)] : [endpoint2, ""]; + const pathParts = pathSearchStart !== -1 ? [pathToAppend.substring(0, pathSearchStart), pathToAppend.substring(pathSearchStart + 1)] : [pathToAppend, ""]; + const combinedSearch = [endpointParts[1], pathParts[1].replaceAll("?", "&")].filter(Boolean).join("&"); + const baseEndpoint = endpointParts[0].replace(/(^[^:]+:\/\/[^/]+)\/\/+/, "$1/"); + const basePathToAppend = pathParts[0]; + let combinedUrl = baseEndpoint; + if (!baseEndpoint.endsWith("/") && !basePathToAppend.startsWith("/") && basePathToAppend !== "") { + combinedUrl += `/${basePathToAppend}`; + } else if (baseEndpoint.endsWith("/") && basePathToAppend.startsWith("/")) { + combinedUrl += basePathToAppend.substring(1); + } else { + combinedUrl += basePathToAppend; + } + if (combinedSearch) { + combinedUrl += `?${combinedSearch}`; + } + return combinedUrl; } function getQueryParamValue(key, allowReserved, style, param) { let separator; @@ -39614,13 +48069,38 @@ var require_urlHelpers = __commonJS({ }).join(separator); return `${allowReserved ? key : encodeURIComponent(key)}=${value}`; } + function simpleParseQueryParams(queryString) { + const result = /* @__PURE__ */ new Map(); + if (!queryString || queryString[0] !== "?") { + return result; + } + queryString = queryString.slice(1); + const pairs = queryString.split("&"); + for (const pair of pairs) { + const eqIndex = pair.indexOf("="); + const name = eqIndex === -1 ? pair : pair.substring(0, eqIndex); + const value = eqIndex === -1 ? "" : pair.substring(eqIndex + 1); + const existingValue = result.get(name); + if (existingValue !== void 0) { + if (Array.isArray(existingValue)) { + existingValue.push(value); + } else { + result.set(name, [existingValue, value]); + } + } else { + result.set(name, value); + } + } + return result; + } function appendQueryParams(url2, options = {}) { if (!options.queryParameters) { return url2; } const parsedUrl = new URL(url2); const queryParams = options.queryParameters; - const paramStrings = []; + const existingParams = simpleParseQueryParams(parsedUrl.search); + const newParamStrings = []; for (const key of Object.keys(queryParams)) { const param = queryParams[key]; if (param === void 0 || param === null) { @@ -39633,23 +48113,53 @@ var require_urlHelpers = __commonJS({ if (explode) { if (Array.isArray(rawValue)) { for (const item of rawValue) { - paramStrings.push(getQueryParamValue(key, options.skipUrlEncoding ?? false, style, item)); + newParamStrings.push( + getQueryParamValue(key, options.skipUrlEncoding ?? false, style, item) + ); } - } else if (typeof rawValue === "object") { + } else if (rawValue !== null && typeof rawValue === "object") { for (const [actualKey, value] of Object.entries(rawValue)) { - paramStrings.push(getQueryParamValue(actualKey, options.skipUrlEncoding ?? false, style, value)); + newParamStrings.push( + getQueryParamValue(actualKey, options.skipUrlEncoding ?? false, style, value) + ); } } else { throw new Error("explode can only be set to true for objects and arrays"); } } else { - paramStrings.push(getQueryParamValue(key, options.skipUrlEncoding ?? false, style, rawValue)); + newParamStrings.push( + getQueryParamValue(key, options.skipUrlEncoding ?? false, style, rawValue) + ); + } + } + for (const paramString of newParamStrings) { + const eqIndex = paramString.indexOf("="); + const name = paramString.substring(0, eqIndex); + const value = paramString.substring(eqIndex + 1); + const existingValue = existingParams.get(name); + if (existingValue !== void 0) { + if (Array.isArray(existingValue)) { + if (!existingValue.includes(value)) { + existingValue.push(value); + } + } else if (existingValue !== value) { + existingParams.set(name, [existingValue, value]); + } + } else { + existingParams.set(name, value); } } - if (parsedUrl.search !== "") { - parsedUrl.search += "&"; + const searchPieces = []; + for (const [name, value] of existingParams) { + if (Array.isArray(value)) { + for (const subValue of value) { + searchPieces.push(`${name}=${subValue}`); + } + } else { + searchPieces.push(`${name}=${value}`); + } } - parsedUrl.search += paramStrings.join("&"); + parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; return parsedUrl.toString(); } function buildBaseUrl(endpoint2, options) { @@ -39691,16 +48201,35 @@ var require_urlHelpers = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/client/getClient.js var require_getClient = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/getClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getClient = getClient; - var clientHelpers_js_1 = require_clientHelpers(); - var sendRequest_js_1 = require_sendRequest(); - var urlHelpers_js_1 = require_urlHelpers(); - var checkEnvironment_js_1 = require_checkEnvironment(); - function getClient(endpoint2, clientOptions = {}) { - const pipeline2 = clientOptions.pipeline ?? (0, clientHelpers_js_1.createDefaultPipeline)(clientOptions); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/getClient.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var getClient_exports = {}; + __export2(getClient_exports, { + getClient: () => getClient2 + }); + module2.exports = __toCommonJS2(getClient_exports); + var import_clientHelpers = require_clientHelpers(); + var import_sendRequest = require_sendRequest(); + var import_urlHelpers = require_urlHelpers(); + var import_env = require_env(); + function getClient2(endpoint2, clientOptions = {}) { + const pipeline2 = clientOptions.pipeline ?? (0, import_clientHelpers.createDefaultPipeline)(clientOptions); if (clientOptions.additionalPolicies?.length) { for (const { policy, position } of clientOptions.additionalPolicies) { const afterPhase = position === "perRetry" ? "Sign" : void 0; @@ -39709,34 +48238,99 @@ var require_getClient = __commonJS({ }); } } + const noDefaultAcceptHeader = clientOptions.internal?.noDefaultAcceptHeader ?? false; const { allowInsecureConnection, httpClient } = clientOptions; const endpointUrl = clientOptions.endpoint ?? endpoint2; const client = (path30, ...args) => { - const getUrl = (requestOptions) => (0, urlHelpers_js_1.buildRequestUrl)(endpointUrl, path30, args, { allowInsecureConnection, ...requestOptions }); + const getUrl = (requestOptions) => (0, import_urlHelpers.buildRequestUrl)(endpointUrl, path30, args, { allowInsecureConnection, ...requestOptions }); return { get: (requestOptions = {}) => { - return buildOperation("GET", getUrl(requestOptions), pipeline2, requestOptions, allowInsecureConnection, httpClient); + return buildOperation( + "GET", + getUrl(requestOptions), + pipeline2, + requestOptions, + allowInsecureConnection, + httpClient, + noDefaultAcceptHeader + ); }, post: (requestOptions = {}) => { - return buildOperation("POST", getUrl(requestOptions), pipeline2, requestOptions, allowInsecureConnection, httpClient); + return buildOperation( + "POST", + getUrl(requestOptions), + pipeline2, + requestOptions, + allowInsecureConnection, + httpClient, + noDefaultAcceptHeader + ); }, put: (requestOptions = {}) => { - return buildOperation("PUT", getUrl(requestOptions), pipeline2, requestOptions, allowInsecureConnection, httpClient); + return buildOperation( + "PUT", + getUrl(requestOptions), + pipeline2, + requestOptions, + allowInsecureConnection, + httpClient, + noDefaultAcceptHeader + ); }, patch: (requestOptions = {}) => { - return buildOperation("PATCH", getUrl(requestOptions), pipeline2, requestOptions, allowInsecureConnection, httpClient); + return buildOperation( + "PATCH", + getUrl(requestOptions), + pipeline2, + requestOptions, + allowInsecureConnection, + httpClient, + noDefaultAcceptHeader + ); }, delete: (requestOptions = {}) => { - return buildOperation("DELETE", getUrl(requestOptions), pipeline2, requestOptions, allowInsecureConnection, httpClient); + return buildOperation( + "DELETE", + getUrl(requestOptions), + pipeline2, + requestOptions, + allowInsecureConnection, + httpClient, + noDefaultAcceptHeader + ); }, head: (requestOptions = {}) => { - return buildOperation("HEAD", getUrl(requestOptions), pipeline2, requestOptions, allowInsecureConnection, httpClient); + return buildOperation( + "HEAD", + getUrl(requestOptions), + pipeline2, + requestOptions, + allowInsecureConnection, + httpClient, + noDefaultAcceptHeader + ); }, options: (requestOptions = {}) => { - return buildOperation("OPTIONS", getUrl(requestOptions), pipeline2, requestOptions, allowInsecureConnection, httpClient); + return buildOperation( + "OPTIONS", + getUrl(requestOptions), + pipeline2, + requestOptions, + allowInsecureConnection, + httpClient, + noDefaultAcceptHeader + ); }, trace: (requestOptions = {}) => { - return buildOperation("TRACE", getUrl(requestOptions), pipeline2, requestOptions, allowInsecureConnection, httpClient); + return buildOperation( + "TRACE", + getUrl(requestOptions), + pipeline2, + requestOptions, + allowInsecureConnection, + httpClient, + noDefaultAcceptHeader + ); } }; }; @@ -39746,24 +48340,46 @@ var require_getClient = __commonJS({ pipeline: pipeline2 }; } - function buildOperation(method, url2, pipeline2, options, allowInsecureConnection, httpClient) { + function buildOperation(method, url2, pipeline2, options, allowInsecureConnection, httpClient, noDefaultAcceptHeader = false) { allowInsecureConnection = options.allowInsecureConnection ?? allowInsecureConnection; return { then: function(onFulfilled, onrejected) { - return (0, sendRequest_js_1.sendRequest)(method, url2, pipeline2, { ...options, allowInsecureConnection }, httpClient).then(onFulfilled, onrejected); + return (0, import_sendRequest.sendRequest)( + method, + url2, + pipeline2, + { ...options, allowInsecureConnection, noDefaultAcceptHeader }, + httpClient + ).then(onFulfilled, onrejected); }, async asBrowserStream() { - if (checkEnvironment_js_1.isNodeLike) { - throw new Error("`asBrowserStream` is supported only in the browser environment. Use `asNodeStream` instead to obtain the response body stream. If you require a Web stream of the response in Node, consider using `Readable.toWeb` on the result of `asNodeStream`."); + if (import_env.isNodeLike) { + throw new Error( + "`asBrowserStream` is supported only in the browser environment. Use `asNodeStream` instead to obtain the response body stream. If you require a Web stream of the response in Node, consider using `Readable.toWeb` on the result of `asNodeStream`." + ); } else { - return (0, sendRequest_js_1.sendRequest)(method, url2, pipeline2, { ...options, allowInsecureConnection, responseAsStream: true }, httpClient); + return (0, import_sendRequest.sendRequest)( + method, + url2, + pipeline2, + { ...options, allowInsecureConnection, noDefaultAcceptHeader, responseAsStream: true }, + httpClient + ); } }, async asNodeStream() { - if (checkEnvironment_js_1.isNodeLike) { - return (0, sendRequest_js_1.sendRequest)(method, url2, pipeline2, { ...options, allowInsecureConnection, responseAsStream: true }, httpClient); + if (import_env.isNodeLike) { + return (0, import_sendRequest.sendRequest)( + method, + url2, + pipeline2, + { ...options, allowInsecureConnection, noDefaultAcceptHeader, responseAsStream: true }, + httpClient + ); } else { - throw new Error("`isNodeStream` is not supported in the browser environment. Use `asBrowserStream` to obtain the response body stream."); + throw new Error( + "`isNodeStream` is not supported in the browser environment. Use `asBrowserStream` to obtain the response body stream." + ); } } }; @@ -39773,11 +48389,30 @@ var require_getClient = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/client/operationOptionHelpers.js var require_operationOptionHelpers = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/operationOptionHelpers.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.operationOptionsToRequestParameters = operationOptionsToRequestParameters; - function operationOptionsToRequestParameters(options) { + "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/operationOptionHelpers.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var operationOptionHelpers_exports = {}; + __export2(operationOptionHelpers_exports, { + operationOptionsToRequestParameters: () => operationOptionsToRequestParameters2 + }); + module2.exports = __toCommonJS2(operationOptionHelpers_exports); + function operationOptionsToRequestParameters2(options) { return { allowInsecureConnection: options.requestOptions?.allowInsecureConnection, timeout: options.requestOptions?.timeout, @@ -39794,28 +48429,48 @@ var require_operationOptionHelpers = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/client/restError.js var require_restError2 = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/restError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createRestError = createRestError; - var restError_js_1 = require_restError(); - var httpHeaders_js_1 = require_httpHeaders(); - function createRestError(messageOrResponse, response) { + "node_modules/@typespec/ts-http-runtime/dist/commonjs/client/restError.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var restError_exports = {}; + __export2(restError_exports, { + createRestError: () => createRestError2 + }); + module2.exports = __toCommonJS2(restError_exports); + var import_restError = require_restError(); + var import_httpHeaders = require_httpHeaders(); + function createRestError2(messageOrResponse, response) { const resp = typeof messageOrResponse === "string" ? response : messageOrResponse; const internalError = resp.body?.error ?? resp.body; const message = typeof messageOrResponse === "string" ? messageOrResponse : internalError?.message ?? `Unexpected status code: ${resp.status}`; - return new restError_js_1.RestError(message, { + return new import_restError.RestError(message, { statusCode: statusCodeToNumber(resp.status), code: internalError?.code, request: resp.request, response: toPipelineResponse(resp) }); } - function toPipelineResponse(response) { + function toPipelineResponse(errorResponse) { return { - headers: (0, httpHeaders_js_1.createHttpHeaders)(response.headers), - request: response.request, - status: statusCodeToNumber(response.status) ?? -1 + headers: (0, import_httpHeaders.createHttpHeaders)(errorResponse.headers), + request: errorResponse.request, + status: statusCodeToNumber(errorResponse.status) ?? -1, + ...typeof errorResponse.body === "string" ? { bodyAsText: errorResponse.body } : {} }; } function statusCodeToNumber(statusCode) { @@ -39827,98 +48482,116 @@ var require_restError2 = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/index.js var require_commonjs = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createRestError = exports2.operationOptionsToRequestParameters = exports2.getClient = exports2.createDefaultHttpClient = exports2.uint8ArrayToString = exports2.stringToUint8Array = exports2.isRestError = exports2.RestError = exports2.createEmptyPipeline = exports2.createPipelineRequest = exports2.createHttpHeaders = exports2.TypeSpecRuntimeLogger = exports2.setLogLevel = exports2.getLogLevel = exports2.createClientLogger = exports2.AbortError = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var AbortError_js_1 = require_AbortError(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); - var logger_js_1 = require_logger(); - Object.defineProperty(exports2, "createClientLogger", { enumerable: true, get: function() { - return logger_js_1.createClientLogger; - } }); - Object.defineProperty(exports2, "getLogLevel", { enumerable: true, get: function() { - return logger_js_1.getLogLevel; - } }); - Object.defineProperty(exports2, "setLogLevel", { enumerable: true, get: function() { - return logger_js_1.setLogLevel; - } }); - Object.defineProperty(exports2, "TypeSpecRuntimeLogger", { enumerable: true, get: function() { - return logger_js_1.TypeSpecRuntimeLogger; - } }); - var httpHeaders_js_1 = require_httpHeaders(); - Object.defineProperty(exports2, "createHttpHeaders", { enumerable: true, get: function() { - return httpHeaders_js_1.createHttpHeaders; - } }); - tslib_1.__exportStar(require_schemes(), exports2); - tslib_1.__exportStar(require_oauth2Flows(), exports2); - var pipelineRequest_js_1 = require_pipelineRequest(); - Object.defineProperty(exports2, "createPipelineRequest", { enumerable: true, get: function() { - return pipelineRequest_js_1.createPipelineRequest; - } }); - var pipeline_js_1 = require_pipeline(); - Object.defineProperty(exports2, "createEmptyPipeline", { enumerable: true, get: function() { - return pipeline_js_1.createEmptyPipeline; - } }); - var restError_js_1 = require_restError(); - Object.defineProperty(exports2, "RestError", { enumerable: true, get: function() { - return restError_js_1.RestError; - } }); - Object.defineProperty(exports2, "isRestError", { enumerable: true, get: function() { - return restError_js_1.isRestError; - } }); - var bytesEncoding_js_1 = require_bytesEncoding(); - Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { - return bytesEncoding_js_1.stringToUint8Array; - } }); - Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { - return bytesEncoding_js_1.uint8ArrayToString; - } }); - var defaultHttpClient_js_1 = require_defaultHttpClient(); - Object.defineProperty(exports2, "createDefaultHttpClient", { enumerable: true, get: function() { - return defaultHttpClient_js_1.createDefaultHttpClient; - } }); - var getClient_js_1 = require_getClient(); - Object.defineProperty(exports2, "getClient", { enumerable: true, get: function() { - return getClient_js_1.getClient; - } }); - var operationOptionHelpers_js_1 = require_operationOptionHelpers(); - Object.defineProperty(exports2, "operationOptionsToRequestParameters", { enumerable: true, get: function() { - return operationOptionHelpers_js_1.operationOptionsToRequestParameters; - } }); - var restError_js_2 = require_restError2(); - Object.defineProperty(exports2, "createRestError", { enumerable: true, get: function() { - return restError_js_2.createRestError; - } }); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/index.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var src_exports = {}; + __export2(src_exports, { + AbortError: () => import_AbortError.AbortError, + RestError: () => import_restError.RestError, + TypeSpecRuntimeLogger: () => import_logger.TypeSpecRuntimeLogger, + createClientLogger: () => import_logger.createClientLogger, + createDefaultHttpClient: () => import_httpClient.createDefaultHttpClient, + createEmptyPipeline: () => import_pipeline.createEmptyPipeline, + createHttpHeaders: () => import_httpHeaders.createHttpHeaders, + createPipelineRequest: () => import_pipelineRequest.createPipelineRequest, + createRestError: () => import_restError2.createRestError, + getClient: () => import_getClient.getClient, + getLogLevel: () => import_logger.getLogLevel, + isRestError: () => import_restError.isRestError, + operationOptionsToRequestParameters: () => import_operationOptionHelpers.operationOptionsToRequestParameters, + setLogLevel: () => import_logger.setLogLevel, + stringToUint8Array: () => import_bytesEncoding.stringToUint8Array, + uint8ArrayToString: () => import_bytesEncoding.uint8ArrayToString + }); + module2.exports = __toCommonJS2(src_exports); + var import_AbortError = require_AbortError(); + var import_logger = require_logger(); + var import_httpHeaders = require_httpHeaders(); + var import_pipelineRequest = require_pipelineRequest(); + var import_pipeline = require_pipeline(); + var import_restError = require_restError(); + var import_bytesEncoding = require_bytesEncoding(); + var import_httpClient = require_defaultHttpClient(); + var import_getClient = require_getClient(); + var import_operationOptionHelpers = require_operationOptionHelpers(); + var import_restError2 = require_restError2(); } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js var require_pipeline2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createEmptyPipeline = createEmptyPipeline; - var ts_http_runtime_1 = require_commonjs(); - function createEmptyPipeline() { - return (0, ts_http_runtime_1.createEmptyPipeline)(); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var pipeline_exports = {}; + __export2(pipeline_exports, { + createEmptyPipeline: () => createEmptyPipeline2 + }); + module2.exports = __toCommonJS2(pipeline_exports); + var import_ts_http_runtime = require_commonjs(); + function createEmptyPipeline2() { + return (0, import_ts_http_runtime.createEmptyPipeline)(); } } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/logger/internal.js var require_internal = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/logger/internal.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createLoggerContext = void 0; - var logger_js_1 = require_logger(); - Object.defineProperty(exports2, "createLoggerContext", { enumerable: true, get: function() { - return logger_js_1.createLoggerContext; - } }); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/logger/internal.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export2(internal_exports, { + createLoggerContext: () => import_logger.createLoggerContext + }); + module2.exports = __toCommonJS2(internal_exports); + var import_logger = require_logger(); } }); @@ -39928,22 +48601,22 @@ var require_commonjs2 = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.AzureLogger = void 0; - exports2.setLogLevel = setLogLevel; - exports2.getLogLevel = getLogLevel; - exports2.createClientLogger = createClientLogger; + exports2.setLogLevel = setLogLevel2; + exports2.getLogLevel = getLogLevel2; + exports2.createClientLogger = createClientLogger2; var logger_1 = require_internal(); var context5 = (0, logger_1.createLoggerContext)({ logLevelEnvVarName: "AZURE_LOG_LEVEL", namespace: "azure" }); exports2.AzureLogger = context5.logger; - function setLogLevel(level) { + function setLogLevel2(level) { context5.setLogLevel(level); } - function getLogLevel() { + function getLogLevel2() { return context5.getLogLevel(); } - function createClientLogger(namespace) { + function createClientLogger2(namespace) { return context5.createClientLogger(namespace); } } @@ -39951,61 +48624,124 @@ var require_commonjs2 = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js var require_log3 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = void 0; - var logger_1 = require_commonjs2(); - exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var log_exports = {}; + __export2(log_exports, { + logger: () => logger2 + }); + module2.exports = __toCommonJS2(log_exports); + var import_logger = require_commonjs2(); + var logger2 = (0, import_logger.createClientLogger)("core-rest-pipeline"); } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/exponentialRetryPolicy.js var require_exponentialRetryPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exponentialRetryPolicyName = void 0; - exports2.exponentialRetryPolicy = exponentialRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.exponentialRetryPolicyName = "exponentialRetryPolicy"; - function exponentialRetryPolicy(options = {}) { - return (0, retryPolicy_js_1.retryPolicy)([ - (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)({ - ...options, - ignoreSystemErrors: true - }) - ], { - maxRetries: options.maxRetries ?? constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var exponentialRetryPolicy_exports = {}; + __export2(exponentialRetryPolicy_exports, { + exponentialRetryPolicy: () => exponentialRetryPolicy2, + exponentialRetryPolicyName: () => exponentialRetryPolicyName2 + }); + module2.exports = __toCommonJS2(exponentialRetryPolicy_exports); + var import_exponentialRetryStrategy = require_exponentialRetryStrategy(); + var import_retryPolicy = require_retryPolicy(); + var import_constants5 = require_constants8(); + var exponentialRetryPolicyName2 = "exponentialRetryPolicy"; + function exponentialRetryPolicy2(options = {}) { + return (0, import_retryPolicy.retryPolicy)( + [ + (0, import_exponentialRetryStrategy.exponentialRetryStrategy)({ + ...options, + ignoreSystemErrors: true + }) + ], + { + maxRetries: options.maxRetries ?? import_constants5.DEFAULT_RETRY_POLICY_COUNT + } + ); } } }); // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/systemErrorRetryPolicy.js var require_systemErrorRetryPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.systemErrorRetryPolicyName = void 0; - exports2.systemErrorRetryPolicy = systemErrorRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.systemErrorRetryPolicyName = "systemErrorRetryPolicy"; - function systemErrorRetryPolicy(options = {}) { + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var systemErrorRetryPolicy_exports = {}; + __export2(systemErrorRetryPolicy_exports, { + systemErrorRetryPolicy: () => systemErrorRetryPolicy2, + systemErrorRetryPolicyName: () => systemErrorRetryPolicyName2 + }); + module2.exports = __toCommonJS2(systemErrorRetryPolicy_exports); + var import_exponentialRetryStrategy = require_exponentialRetryStrategy(); + var import_retryPolicy = require_retryPolicy(); + var import_constants5 = require_constants8(); + var systemErrorRetryPolicyName2 = "systemErrorRetryPolicy"; + function systemErrorRetryPolicy2(options = {}) { return { - name: exports2.systemErrorRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([ - (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)({ - ...options, - ignoreHttpStatusCodes: true - }) - ], { - maxRetries: options.maxRetries ?? constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }).sendRequest + name: systemErrorRetryPolicyName2, + sendRequest: (0, import_retryPolicy.retryPolicy)( + [ + (0, import_exponentialRetryStrategy.exponentialRetryStrategy)({ + ...options, + ignoreHttpStatusCodes: true + }) + ], + { + maxRetries: options.maxRetries ?? import_constants5.DEFAULT_RETRY_POLICY_COUNT + } + ).sendRequest }; } } @@ -40013,20 +48749,39 @@ var require_systemErrorRetryPolicy = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/throttlingRetryPolicy.js var require_throttlingRetryPolicy = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.throttlingRetryPolicyName = void 0; - exports2.throttlingRetryPolicy = throttlingRetryPolicy; - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.throttlingRetryPolicyName = "throttlingRetryPolicy"; - function throttlingRetryPolicy(options = {}) { + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var throttlingRetryPolicy_exports = {}; + __export2(throttlingRetryPolicy_exports, { + throttlingRetryPolicy: () => throttlingRetryPolicy2, + throttlingRetryPolicyName: () => throttlingRetryPolicyName2 + }); + module2.exports = __toCommonJS2(throttlingRetryPolicy_exports); + var import_throttlingRetryStrategy = require_throttlingRetryStrategy(); + var import_retryPolicy = require_retryPolicy(); + var import_constants5 = require_constants8(); + var throttlingRetryPolicyName2 = "throttlingRetryPolicy"; + function throttlingRetryPolicy2(options = {}) { return { - name: exports2.throttlingRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], { - maxRetries: options.maxRetries ?? constants_js_1.DEFAULT_RETRY_POLICY_COUNT + name: throttlingRetryPolicyName2, + sendRequest: (0, import_retryPolicy.retryPolicy)([(0, import_throttlingRetryStrategy.throttlingRetryStrategy)()], { + maxRetries: options.maxRetries ?? import_constants5.DEFAULT_RETRY_POLICY_COUNT }).sendRequest }; } @@ -40035,124 +48790,105 @@ var require_throttlingRetryPolicy = __commonJS({ // node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/internal.js var require_internal2 = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/internal.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.userAgentPolicyName = exports2.userAgentPolicy = exports2.tlsPolicyName = exports2.tlsPolicy = exports2.redirectPolicyName = exports2.redirectPolicy = exports2.getDefaultProxySettings = exports2.proxyPolicyName = exports2.proxyPolicy = exports2.multipartPolicyName = exports2.multipartPolicy = exports2.logPolicyName = exports2.logPolicy = exports2.formDataPolicyName = exports2.formDataPolicy = exports2.throttlingRetryPolicyName = exports2.throttlingRetryPolicy = exports2.systemErrorRetryPolicyName = exports2.systemErrorRetryPolicy = exports2.retryPolicy = exports2.exponentialRetryPolicyName = exports2.exponentialRetryPolicy = exports2.defaultRetryPolicyName = exports2.defaultRetryPolicy = exports2.decompressResponsePolicyName = exports2.decompressResponsePolicy = exports2.agentPolicyName = exports2.agentPolicy = void 0; - var agentPolicy_js_1 = require_agentPolicy(); - Object.defineProperty(exports2, "agentPolicy", { enumerable: true, get: function() { - return agentPolicy_js_1.agentPolicy; - } }); - Object.defineProperty(exports2, "agentPolicyName", { enumerable: true, get: function() { - return agentPolicy_js_1.agentPolicyName; - } }); - var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); - Object.defineProperty(exports2, "decompressResponsePolicy", { enumerable: true, get: function() { - return decompressResponsePolicy_js_1.decompressResponsePolicy; - } }); - Object.defineProperty(exports2, "decompressResponsePolicyName", { enumerable: true, get: function() { - return decompressResponsePolicy_js_1.decompressResponsePolicyName; - } }); - var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); - Object.defineProperty(exports2, "defaultRetryPolicy", { enumerable: true, get: function() { - return defaultRetryPolicy_js_1.defaultRetryPolicy; - } }); - Object.defineProperty(exports2, "defaultRetryPolicyName", { enumerable: true, get: function() { - return defaultRetryPolicy_js_1.defaultRetryPolicyName; - } }); - var exponentialRetryPolicy_js_1 = require_exponentialRetryPolicy(); - Object.defineProperty(exports2, "exponentialRetryPolicy", { enumerable: true, get: function() { - return exponentialRetryPolicy_js_1.exponentialRetryPolicy; - } }); - Object.defineProperty(exports2, "exponentialRetryPolicyName", { enumerable: true, get: function() { - return exponentialRetryPolicy_js_1.exponentialRetryPolicyName; - } }); - var retryPolicy_js_1 = require_retryPolicy(); - Object.defineProperty(exports2, "retryPolicy", { enumerable: true, get: function() { - return retryPolicy_js_1.retryPolicy; - } }); - var systemErrorRetryPolicy_js_1 = require_systemErrorRetryPolicy(); - Object.defineProperty(exports2, "systemErrorRetryPolicy", { enumerable: true, get: function() { - return systemErrorRetryPolicy_js_1.systemErrorRetryPolicy; - } }); - Object.defineProperty(exports2, "systemErrorRetryPolicyName", { enumerable: true, get: function() { - return systemErrorRetryPolicy_js_1.systemErrorRetryPolicyName; - } }); - var throttlingRetryPolicy_js_1 = require_throttlingRetryPolicy(); - Object.defineProperty(exports2, "throttlingRetryPolicy", { enumerable: true, get: function() { - return throttlingRetryPolicy_js_1.throttlingRetryPolicy; - } }); - Object.defineProperty(exports2, "throttlingRetryPolicyName", { enumerable: true, get: function() { - return throttlingRetryPolicy_js_1.throttlingRetryPolicyName; - } }); - var formDataPolicy_js_1 = require_formDataPolicy(); - Object.defineProperty(exports2, "formDataPolicy", { enumerable: true, get: function() { - return formDataPolicy_js_1.formDataPolicy; - } }); - Object.defineProperty(exports2, "formDataPolicyName", { enumerable: true, get: function() { - return formDataPolicy_js_1.formDataPolicyName; - } }); - var logPolicy_js_1 = require_logPolicy(); - Object.defineProperty(exports2, "logPolicy", { enumerable: true, get: function() { - return logPolicy_js_1.logPolicy; - } }); - Object.defineProperty(exports2, "logPolicyName", { enumerable: true, get: function() { - return logPolicy_js_1.logPolicyName; - } }); - var multipartPolicy_js_1 = require_multipartPolicy(); - Object.defineProperty(exports2, "multipartPolicy", { enumerable: true, get: function() { - return multipartPolicy_js_1.multipartPolicy; - } }); - Object.defineProperty(exports2, "multipartPolicyName", { enumerable: true, get: function() { - return multipartPolicy_js_1.multipartPolicyName; - } }); - var proxyPolicy_js_1 = require_proxyPolicy(); - Object.defineProperty(exports2, "proxyPolicy", { enumerable: true, get: function() { - return proxyPolicy_js_1.proxyPolicy; - } }); - Object.defineProperty(exports2, "proxyPolicyName", { enumerable: true, get: function() { - return proxyPolicy_js_1.proxyPolicyName; - } }); - Object.defineProperty(exports2, "getDefaultProxySettings", { enumerable: true, get: function() { - return proxyPolicy_js_1.getDefaultProxySettings; - } }); - var redirectPolicy_js_1 = require_redirectPolicy(); - Object.defineProperty(exports2, "redirectPolicy", { enumerable: true, get: function() { - return redirectPolicy_js_1.redirectPolicy; - } }); - Object.defineProperty(exports2, "redirectPolicyName", { enumerable: true, get: function() { - return redirectPolicy_js_1.redirectPolicyName; - } }); - var tlsPolicy_js_1 = require_tlsPolicy(); - Object.defineProperty(exports2, "tlsPolicy", { enumerable: true, get: function() { - return tlsPolicy_js_1.tlsPolicy; - } }); - Object.defineProperty(exports2, "tlsPolicyName", { enumerable: true, get: function() { - return tlsPolicy_js_1.tlsPolicyName; - } }); - var userAgentPolicy_js_1 = require_userAgentPolicy(); - Object.defineProperty(exports2, "userAgentPolicy", { enumerable: true, get: function() { - return userAgentPolicy_js_1.userAgentPolicy; - } }); - Object.defineProperty(exports2, "userAgentPolicyName", { enumerable: true, get: function() { - return userAgentPolicy_js_1.userAgentPolicyName; - } }); + "node_modules/@typespec/ts-http-runtime/dist/commonjs/policies/internal.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export2(internal_exports, { + agentPolicy: () => import_agentPolicy.agentPolicy, + agentPolicyName: () => import_agentPolicy.agentPolicyName, + decompressResponsePolicy: () => import_decompress.decompressResponsePolicy, + decompressResponsePolicyName: () => import_decompress.decompressResponsePolicyName, + defaultRetryPolicy: () => import_defaultRetryPolicy.defaultRetryPolicy, + defaultRetryPolicyName: () => import_defaultRetryPolicy.defaultRetryPolicyName, + exponentialRetryPolicy: () => import_exponentialRetryPolicy.exponentialRetryPolicy, + exponentialRetryPolicyName: () => import_exponentialRetryPolicy.exponentialRetryPolicyName, + formDataPolicy: () => import_formDataPolicy.formDataPolicy, + formDataPolicyName: () => import_formDataPolicy.formDataPolicyName, + getDefaultProxySettings: () => import_proxy.getDefaultProxySettings, + logPolicy: () => import_logPolicy.logPolicy, + logPolicyName: () => import_logPolicy.logPolicyName, + multipartPolicy: () => import_multipartPolicy.multipartPolicy, + multipartPolicyName: () => import_multipartPolicy.multipartPolicyName, + proxyPolicy: () => import_proxy.proxyPolicy, + proxyPolicyName: () => import_proxy.proxyPolicyName, + redirectPolicy: () => import_redirectPolicy.redirectPolicy, + redirectPolicyName: () => import_redirectPolicy.redirectPolicyName, + retryPolicy: () => import_retryPolicy.retryPolicy, + systemErrorRetryPolicy: () => import_systemErrorRetryPolicy.systemErrorRetryPolicy, + systemErrorRetryPolicyName: () => import_systemErrorRetryPolicy.systemErrorRetryPolicyName, + throttlingRetryPolicy: () => import_throttlingRetryPolicy.throttlingRetryPolicy, + throttlingRetryPolicyName: () => import_throttlingRetryPolicy.throttlingRetryPolicyName, + tlsPolicy: () => import_tlsPolicy.tlsPolicy, + tlsPolicyName: () => import_tlsPolicy.tlsPolicyName, + userAgentPolicy: () => import_userAgentPolicy.userAgentPolicy, + userAgentPolicyName: () => import_userAgentPolicy.userAgentPolicyName + }); + module2.exports = __toCommonJS2(internal_exports); + var import_agentPolicy = require_agentPolicy(); + var import_decompress = require_decompressResponsePolicy(); + var import_defaultRetryPolicy = require_defaultRetryPolicy(); + var import_exponentialRetryPolicy = require_exponentialRetryPolicy(); + var import_retryPolicy = require_retryPolicy(); + var import_systemErrorRetryPolicy = require_systemErrorRetryPolicy(); + var import_throttlingRetryPolicy = require_throttlingRetryPolicy(); + var import_formDataPolicy = require_formDataPolicy(); + var import_logPolicy = require_logPolicy(); + var import_multipartPolicy = require_multipartPolicy(); + var import_proxy = require_proxyPolicy(); + var import_redirectPolicy = require_redirectPolicy(); + var import_tlsPolicy = require_tlsPolicy(); + var import_userAgentPolicy = require_userAgentPolicy(); } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js var require_logPolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logPolicyName = void 0; - exports2.logPolicy = logPolicy; - var log_js_1 = require_log3(); - var policies_1 = require_internal2(); - exports2.logPolicyName = policies_1.logPolicyName; - function logPolicy(options = {}) { - return (0, policies_1.logPolicy)({ - logger: log_js_1.logger.info, + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var logPolicy_exports = {}; + __export2(logPolicy_exports, { + logPolicy: () => logPolicy2, + logPolicyName: () => logPolicyName2 + }); + module2.exports = __toCommonJS2(logPolicy_exports); + var import_log = require_log3(); + var import_policies = require_internal2(); + var logPolicyName2 = import_policies.logPolicyName; + function logPolicy2(options = {}) { + return (0, import_policies.logPolicy)({ + logger: import_log.logger.info, ...options }); } @@ -40161,42 +48897,88 @@ var require_logPolicy2 = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js var require_redirectPolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.redirectPolicyName = void 0; - exports2.redirectPolicy = redirectPolicy; - var policies_1 = require_internal2(); - exports2.redirectPolicyName = policies_1.redirectPolicyName; - function redirectPolicy(options = {}) { - return (0, policies_1.redirectPolicy)(options); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var redirectPolicy_exports = {}; + __export2(redirectPolicy_exports, { + redirectPolicy: () => redirectPolicy2, + redirectPolicyName: () => redirectPolicyName2 + }); + module2.exports = __toCommonJS2(redirectPolicy_exports); + var import_policies = require_internal2(); + var redirectPolicyName2 = import_policies.redirectPolicyName; + function redirectPolicy2(options = {}) { + return (0, import_policies.redirectPolicy)(options); } } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js var require_userAgentPlatform2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getHeaderName = getHeaderName; - exports2.setPlatformSpecificData = setPlatformSpecificData; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var node_os_1 = tslib_1.__importDefault(require("node:os")); - var node_process_1 = tslib_1.__importDefault(require("node:process")); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var userAgentPlatform_exports = {}; + __export2(userAgentPlatform_exports, { + getHeaderName: () => getHeaderName, + setPlatformSpecificData: () => setPlatformSpecificData2 + }); + module2.exports = __toCommonJS2(userAgentPlatform_exports); + var import_node_os = __toESM2(require("node:os")); + var import_node_process = __toESM2(require("node:process")); function getHeaderName() { return "User-Agent"; } - async function setPlatformSpecificData(map) { - if (node_process_1.default && node_process_1.default.versions) { - const osInfo = `${node_os_1.default.type()} ${node_os_1.default.release()}; ${node_os_1.default.arch()}`; - const versions = node_process_1.default.versions; - if (versions.bun) { - map.set("Bun", `${versions.bun} (${osInfo})`); - } else if (versions.deno) { - map.set("Deno", `${versions.deno} (${osInfo})`); - } else if (versions.node) { - map.set("Node", `${versions.node} (${osInfo})`); + async function setPlatformSpecificData2(map) { + if (import_node_process.default && import_node_process.default.versions) { + const osInfo = `${import_node_os.default.type()} ${import_node_os.default.release()}; ${import_node_os.default.arch()}`; + if (import_node_process.default.versions.bun) { + map.set("Bun", `${import_node_process.default.versions.bun} (${osInfo})`); + } else if (import_node_process.default.versions.deno) { + map.set("Deno", `${import_node_process.default.versions.deno} (${osInfo})`); + } else if (import_node_process.default.versions.node) { + map.set("Node", `${import_node_process.default.versions.node} (${osInfo})`); } } } @@ -40205,24 +48987,63 @@ var require_userAgentPlatform2 = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js var require_constants9 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DEFAULT_RETRY_POLICY_COUNT = exports2.SDK_VERSION = void 0; - exports2.SDK_VERSION = "1.22.2"; - exports2.DEFAULT_RETRY_POLICY_COUNT = 3; + "node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var constants_exports = {}; + __export2(constants_exports, { + DEFAULT_RETRY_POLICY_COUNT: () => DEFAULT_RETRY_POLICY_COUNT, + SDK_VERSION: () => SDK_VERSION + }); + module2.exports = __toCommonJS2(constants_exports); + var SDK_VERSION = "1.25.0"; + var DEFAULT_RETRY_POLICY_COUNT = 3; } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js var require_userAgent2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getUserAgentHeaderName = getUserAgentHeaderName; - exports2.getUserAgentValue = getUserAgentValue; - var userAgentPlatform_js_1 = require_userAgentPlatform2(); - var constants_js_1 = require_constants9(); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var userAgent_exports = {}; + __export2(userAgent_exports, { + getUserAgentHeaderName: () => getUserAgentHeaderName, + getUserAgentValue: () => getUserAgentValue + }); + module2.exports = __toCommonJS2(userAgent_exports); + var import_userAgent = require_userAgentPlatform2(); + var import_constants5 = require_constants9(); function getUserAgentString(telemetryInfo) { const parts = []; for (const [key, value] of telemetryInfo) { @@ -40232,12 +49053,12 @@ var require_userAgent2 = __commonJS({ return parts.join(" "); } function getUserAgentHeaderName() { - return (0, userAgentPlatform_js_1.getHeaderName)(); + return (0, import_userAgent.getHeaderName)(); } async function getUserAgentValue(prefix) { const runtimeInfo = /* @__PURE__ */ new Map(); - runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION); - await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo); + runtimeInfo.set("core-rest-pipeline", import_constants5.SDK_VERSION); + await (0, import_userAgent.setPlatformSpecificData)(runtimeInfo); const defaultAgent = getUserAgentString(runtimeInfo); const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent; return userAgentValue; @@ -40247,18 +49068,37 @@ var require_userAgent2 = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js var require_userAgentPolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.userAgentPolicyName = void 0; - exports2.userAgentPolicy = userAgentPolicy; - var userAgent_js_1 = require_userAgent2(); - var UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)(); - exports2.userAgentPolicyName = "userAgentPolicy"; - function userAgentPolicy(options = {}) { - const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var userAgentPolicy_exports = {}; + __export2(userAgentPolicy_exports, { + userAgentPolicy: () => userAgentPolicy2, + userAgentPolicyName: () => userAgentPolicyName2 + }); + module2.exports = __toCommonJS2(userAgentPolicy_exports); + var import_userAgent = require_userAgent2(); + var UserAgentHeaderName = (0, import_userAgent.getUserAgentHeaderName)(); + var userAgentPolicyName2 = "userAgentPolicy"; + function userAgentPolicy2(options = {}) { + const userAgentValue = (0, import_userAgent.getUserAgentValue)(options.userAgentPrefix); return { - name: exports2.userAgentPolicyName, + name: userAgentPolicyName2, async sendRequest(request3, next) { if (!request3.headers.has(UserAgentHeaderName)) { request3.headers.set(UserAgentHeaderName, await userAgentValue); @@ -40270,363 +49110,70 @@ var require_userAgentPolicy2 = __commonJS({ } }); -// node_modules/@typespec/ts-http-runtime/dist/commonjs/util/sha256.js -var require_sha256 = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/sha256.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.computeSha256Hmac = computeSha256Hmac; - exports2.computeSha256Hash = computeSha256Hash; - var node_crypto_1 = require("node:crypto"); - async function computeSha256Hmac(key, stringToSign, encoding) { - const decodedKey = Buffer.from(key, "base64"); - return (0, node_crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); - } - async function computeSha256Hash(content, encoding) { - return (0, node_crypto_1.createHash)("sha256").update(content).digest(encoding); - } - } -}); - -// node_modules/@typespec/ts-http-runtime/dist/commonjs/util/internal.js -var require_internal3 = __commonJS({ - "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/internal.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Sanitizer = exports2.uint8ArrayToString = exports2.stringToUint8Array = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.calculateRetryDelay = void 0; - var delay_js_1 = require_delay(); - Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { - return delay_js_1.calculateRetryDelay; - } }); - var random_js_1 = require_random(); - Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { - return random_js_1.getRandomIntegerInclusive; - } }); - var object_js_1 = require_object(); - Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { - return object_js_1.isObject; - } }); - var error_js_1 = require_error(); - Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { - return error_js_1.isError; - } }); - var sha256_js_1 = require_sha256(); - Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hash; - } }); - Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hmac; - } }); - var uuidUtils_js_1 = require_uuidUtils(); - Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { - return uuidUtils_js_1.randomUUID; - } }); - var checkEnvironment_js_1 = require_checkEnvironment(); - Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBrowser; - } }); - Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBun; - } }); - Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeLike; - } }); - Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeRuntime; - } }); - Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { - return checkEnvironment_js_1.isDeno; - } }); - Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { - return checkEnvironment_js_1.isReactNative; - } }); - Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { - return checkEnvironment_js_1.isWebWorker; - } }); - var bytesEncoding_js_1 = require_bytesEncoding(); - Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { - return bytesEncoding_js_1.stringToUint8Array; - } }); - Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { - return bytesEncoding_js_1.uint8ArrayToString; - } }); - var sanitizer_js_1 = require_sanitizer(); - Object.defineProperty(exports2, "Sanitizer", { enumerable: true, get: function() { - return sanitizer_js_1.Sanitizer; - } }); - } -}); - -// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js -var require_aborterUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.cancelablePromiseRace = cancelablePromiseRace; - async function cancelablePromiseRace(abortablePromiseBuilders, options) { - const aborter = new AbortController(); - function abortHandler() { - aborter.abort(); - } - options?.abortSignal?.addEventListener("abort", abortHandler); - try { - return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); - } finally { - aborter.abort(); - options?.abortSignal?.removeEventListener("abort", abortHandler); - } - } - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError2 = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; - } +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/createFile.js +var require_createFile = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/createFile.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); }; - exports2.AbortError = AbortError; - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs3 = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError2(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); - } -}); - -// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js -var require_createAbortablePromise = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createAbortablePromise = createAbortablePromise; - var abort_controller_1 = require_commonjs3(); - function createAbortablePromise(buildPromise, options) { - const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options ?? {}; - return new Promise((resolve14, reject) => { - function rejectOnAbort() { - reject(new abort_controller_1.AbortError(abortErrorMsg ?? "The operation was aborted.")); - } - function removeListeners() { - abortSignal?.removeEventListener("abort", onAbort); - } - function onAbort() { - cleanupBeforeAbort?.(); - removeListeners(); - rejectOnAbort(); - } - if (abortSignal?.aborted) { - return rejectOnAbort(); - } - try { - buildPromise((x) => { - removeListeners(); - resolve14(x); - }, (x) => { - removeListeners(); - reject(x); - }); - } catch (err) { - reject(err); - } - abortSignal?.addEventListener("abort", onAbort); - }); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/delay.js -var require_delay2 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay2; - exports2.calculateRetryDelay = calculateRetryDelay; - var createAbortablePromise_js_1 = require_createAbortablePromise(); - var util_1 = require_internal3(); - var StandardAbortMessage = "The delay was aborted."; - function delay2(timeInMs, options) { - let token; - const { abortSignal, abortErrorMsg } = options ?? {}; - return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve14) => { - token = setTimeout(resolve14, timeInMs); - }, { - cleanupBeforeAbort: () => clearTimeout(token), - abortSignal, - abortErrorMsg: abortErrorMsg ?? StandardAbortMessage - }); - } - function calculateRetryDelay(retryAttempt, config) { - const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); - const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); - const retryAfterInMs = clampedDelay / 2 + (0, util_1.getRandomIntegerInclusive)(0, clampedDelay / 2); - return { retryAfterInMs }; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/error.js -var require_error2 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getErrorMessage = getErrorMessage2; - var util_1 = require_internal3(); - function getErrorMessage2(e) { - if ((0, util_1.isError)(e)) { - return e.message; - } else { - let stringified; - try { - if (typeof e === "object" && e) { - stringified = JSON.stringify(e); - } else { - stringified = String(e); - } - } catch (err) { - stringified = "[unable to stringify input]"; - } - return `Unknown error ${stringified}`; - } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/typeGuards.js -var require_typeGuards2 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isDefined = isDefined3; - exports2.isObjectWithProperties = isObjectWithProperties; - exports2.objectHasProperty = objectHasProperty; - function isDefined3(thing) { - return typeof thing !== "undefined" && thing !== null; - } - function isObjectWithProperties(thing, properties) { - if (!isDefined3(thing) || typeof thing !== "object") { - return false; - } - for (const property of properties) { - if (!objectHasProperty(thing, property)) { - return false; - } + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - return true; - } - function objectHasProperty(thing, property) { - return isDefined3(thing) && typeof thing === "object" && property in thing; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/index.js -var require_commonjs4 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isWebWorker = exports2.isReactNative = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isDeno = exports2.isBun = exports2.isBrowser = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.getErrorMessage = exports2.delay = exports2.createAbortablePromise = exports2.cancelablePromiseRace = void 0; - exports2.calculateRetryDelay = calculateRetryDelay; - exports2.computeSha256Hash = computeSha256Hash; - exports2.computeSha256Hmac = computeSha256Hmac; - exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; - exports2.isError = isError; - exports2.isObject = isObject2; - exports2.randomUUID = randomUUID; - exports2.uint8ArrayToString = uint8ArrayToString; - exports2.stringToUint8Array = stringToUint8Array; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var tspRuntime = tslib_1.__importStar(require_internal3()); - var aborterUtils_js_1 = require_aborterUtils(); - Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { - return aborterUtils_js_1.cancelablePromiseRace; - } }); - var createAbortablePromise_js_1 = require_createAbortablePromise(); - Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { - return createAbortablePromise_js_1.createAbortablePromise; - } }); - var delay_js_1 = require_delay2(); - Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { - return delay_js_1.delay; - } }); - var error_js_1 = require_error2(); - Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { - return error_js_1.getErrorMessage; - } }); - var typeGuards_js_1 = require_typeGuards2(); - Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { - return typeGuards_js_1.isDefined; - } }); - Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { - return typeGuards_js_1.isObjectWithProperties; - } }); - Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { - return typeGuards_js_1.objectHasProperty; - } }); - function calculateRetryDelay(retryAttempt, config) { - return tspRuntime.calculateRetryDelay(retryAttempt, config); - } - function computeSha256Hash(content, encoding) { - return tspRuntime.computeSha256Hash(content, encoding); - } - function computeSha256Hmac(key, stringToSign, encoding) { - return tspRuntime.computeSha256Hmac(key, stringToSign, encoding); - } - function getRandomIntegerInclusive(min, max) { - return tspRuntime.getRandomIntegerInclusive(min, max); - } - function isError(e) { - return tspRuntime.isError(e); - } - function isObject2(input) { - return tspRuntime.isObject(input); - } - function randomUUID() { - return tspRuntime.randomUUID(); - } - exports2.isBrowser = tspRuntime.isBrowser; - exports2.isBun = tspRuntime.isBun; - exports2.isDeno = tspRuntime.isDeno; - exports2.isNode = tspRuntime.isNodeLike; - exports2.isNodeLike = tspRuntime.isNodeLike; - exports2.isNodeRuntime = tspRuntime.isNodeRuntime; - exports2.isReactNative = tspRuntime.isReactNative; - exports2.isWebWorker = tspRuntime.isWebWorker; - function uint8ArrayToString(bytes, format) { - return tspRuntime.uint8ArrayToString(bytes, format); - } - function stringToUint8Array(value, format) { - return tspRuntime.stringToUint8Array(value, format); + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var createFile_exports = {}; + __export2(createFile_exports, { + createFile: () => createFile2 + }); + module2.exports = __toCommonJS2(createFile_exports); + var import_file7 = require_file(); + function createFile2(content, name, options = {}) { + return (0, import_file7.createRawFile)(content, name, options); } } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js -var require_file2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.hasRawContent = hasRawContent; - exports2.getRawContent = getRawContent; - exports2.createFileFromStream = createFileFromStream; - exports2.createFile = createFile; - var core_util_1 = require_commonjs4(); - function isNodeReadableStream(x) { - return Boolean(x && typeof x["pipe"] === "function"); +var require_file = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var file_exports = {}; + __export2(file_exports, { + createFile: () => import_createFile.createFile, + createFileFromStream: () => createFileFromStream2, + createRawFile: () => createRawFile, + getRawContent: () => getRawContent, + hasRawContent: () => hasRawContent + }); + module2.exports = __toCommonJS2(file_exports); + var import_createFile = require_createFile(); + function isNodeReadableStream2(x) { + return typeof x === "object" && x !== null && "pipe" in x && typeof x.pipe === "function"; } var unimplementedMethods = { arrayBuffer: () => { @@ -40653,7 +49200,20 @@ var require_file2 = __commonJS({ return blob; } } - function createFileFromStream(stream2, name, options = {}) { + function createRawFile(content, name, options = {}) { + return { + ...unimplementedMethods, + type: options.type ?? "", + lastModified: options.lastModified ?? (/* @__PURE__ */ new Date()).getTime(), + webkitRelativePath: options.webkitRelativePath ?? "", + size: content.byteLength, + name, + arrayBuffer: async () => toArrayBuffer(content).buffer, + stream: () => new Blob([toArrayBuffer(content)]).stream(), + [rawContent]: () => content + }; + } + function createFileFromStream2(stream2, name, options = {}) { return { ...unimplementedMethods, type: options.type ?? "", @@ -40663,33 +49223,24 @@ var require_file2 = __commonJS({ name, stream: () => { const s = stream2(); - if (isNodeReadableStream(s)) { - throw new Error("Not supported: a Node stream was provided as input to createFileFromStream."); + if (isNodeReadableStream2(s)) { + throw new Error( + "Not supported: a Node stream was provided as input to createFileFromStream." + ); } return s; }, [rawContent]: stream2 }; } - function createFile(content, name, options = {}) { - if (core_util_1.isNodeLike) { - return { - ...unimplementedMethods, - type: options.type ?? "", - lastModified: options.lastModified ?? (/* @__PURE__ */ new Date()).getTime(), - webkitRelativePath: options.webkitRelativePath ?? "", - size: content.byteLength, - name, - arrayBuffer: async () => content.buffer, - stream: () => new Blob([toArrayBuffer(content)]).stream(), - [rawContent]: () => content - }; - } else { - return new File([toArrayBuffer(content)], name, options); - } + function hasArrayBuffer(source) { + return "resize" in source.buffer; } function toArrayBuffer(source) { - if ("resize" in source.buffer) { + if (hasArrayBuffer(source)) { + if (source.byteOffset !== 0 || source.byteLength !== source.buffer.byteLength) { + return new Uint8Array(source); + } return source; } return source.map((x) => x); @@ -40699,23 +49250,42 @@ var require_file2 = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js var require_multipartPolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.multipartPolicyName = void 0; - exports2.multipartPolicy = multipartPolicy; - var policies_1 = require_internal2(); - var file_js_1 = require_file2(); - exports2.multipartPolicyName = policies_1.multipartPolicyName; - function multipartPolicy() { - const tspPolicy = (0, policies_1.multipartPolicy)(); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var multipartPolicy_exports = {}; + __export2(multipartPolicy_exports, { + multipartPolicy: () => multipartPolicy2, + multipartPolicyName: () => multipartPolicyName2 + }); + module2.exports = __toCommonJS2(multipartPolicy_exports); + var import_policies = require_internal2(); + var import_file7 = require_file(); + var multipartPolicyName2 = import_policies.multipartPolicyName; + function multipartPolicy2() { + const tspPolicy = (0, import_policies.multipartPolicy)(); return { - name: exports2.multipartPolicyName, + name: multipartPolicyName2, sendRequest: async (request3, next) => { if (request3.multipartBody) { for (const part of request3.multipartBody.parts) { - if ((0, file_js_1.hasRawContent)(part.body)) { - part.body = (0, file_js_1.getRawContent)(part.body); + if ((0, import_file7.hasRawContent)(part.body)) { + part.body = (0, import_file7.getRawContent)(part.body); } } } @@ -40728,121 +49298,1127 @@ var require_multipartPolicy2 = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js var require_decompressResponsePolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.decompressResponsePolicyName = void 0; - exports2.decompressResponsePolicy = decompressResponsePolicy; - var policies_1 = require_internal2(); - exports2.decompressResponsePolicyName = policies_1.decompressResponsePolicyName; - function decompressResponsePolicy() { - return (0, policies_1.decompressResponsePolicy)(); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var decompressResponsePolicy_exports = {}; + __export2(decompressResponsePolicy_exports, { + decompressResponsePolicy: () => decompressResponsePolicy2, + decompressResponsePolicyName: () => decompressResponsePolicyName2 + }); + module2.exports = __toCommonJS2(decompressResponsePolicy_exports); + var import_policies = require_internal2(); + var decompressResponsePolicyName2 = import_policies.decompressResponsePolicyName; + function decompressResponsePolicy2() { + return (0, import_policies.decompressResponsePolicy)(); } } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js var require_defaultRetryPolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.defaultRetryPolicyName = void 0; - exports2.defaultRetryPolicy = defaultRetryPolicy; - var policies_1 = require_internal2(); - exports2.defaultRetryPolicyName = policies_1.defaultRetryPolicyName; - function defaultRetryPolicy(options = {}) { - return (0, policies_1.defaultRetryPolicy)(options); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var defaultRetryPolicy_exports = {}; + __export2(defaultRetryPolicy_exports, { + defaultRetryPolicy: () => defaultRetryPolicy2, + defaultRetryPolicyName: () => defaultRetryPolicyName2 + }); + module2.exports = __toCommonJS2(defaultRetryPolicy_exports); + var import_policies = require_internal2(); + var defaultRetryPolicyName2 = import_policies.defaultRetryPolicyName; + function defaultRetryPolicy2(options = {}) { + return (0, import_policies.defaultRetryPolicy)(options); } } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js var require_formDataPolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.formDataPolicyName = void 0; - exports2.formDataPolicy = formDataPolicy; - var policies_1 = require_internal2(); - exports2.formDataPolicyName = policies_1.formDataPolicyName; - function formDataPolicy() { - return (0, policies_1.formDataPolicy)(); - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js -var require_proxyPolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.proxyPolicyName = void 0; - exports2.getDefaultProxySettings = getDefaultProxySettings; - exports2.proxyPolicy = proxyPolicy; - var policies_1 = require_internal2(); - exports2.proxyPolicyName = policies_1.proxyPolicyName; - function getDefaultProxySettings(proxyUrl) { - return (0, policies_1.getDefaultProxySettings)(proxyUrl); - } - function proxyPolicy(proxySettings, options) { - return (0, policies_1.proxyPolicy)(proxySettings, options); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var formDataPolicy_exports = {}; + __export2(formDataPolicy_exports, { + formDataPolicy: () => formDataPolicy2, + formDataPolicyName: () => formDataPolicyName2 + }); + module2.exports = __toCommonJS2(formDataPolicy_exports); + var import_policies = require_internal2(); + var formDataPolicyName2 = import_policies.formDataPolicyName; + function formDataPolicy2() { + return (0, import_policies.formDataPolicy)(); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js -var require_setClientRequestIdPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.setClientRequestIdPolicyName = void 0; - exports2.setClientRequestIdPolicy = setClientRequestIdPolicy; - exports2.setClientRequestIdPolicyName = "setClientRequestIdPolicy"; - function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { - return { - name: exports2.setClientRequestIdPolicyName, - async sendRequest(request3, next) { - if (!request3.headers.has(requestIdHeaderName)) { - request3.headers.set(requestIdHeaderName, request3.requestId); - } - return next(request3); - } - }; - } - } +// node_modules/tslib/tslib.es6.mjs +var tslib_es6_exports = {}; +__export(tslib_es6_exports, { + __addDisposableResource: () => __addDisposableResource, + __assign: () => __assign, + __asyncDelegator: () => __asyncDelegator, + __asyncGenerator: () => __asyncGenerator, + __asyncValues: () => __asyncValues, + __await: () => __await, + __awaiter: () => __awaiter, + __classPrivateFieldGet: () => __classPrivateFieldGet, + __classPrivateFieldIn: () => __classPrivateFieldIn, + __classPrivateFieldSet: () => __classPrivateFieldSet, + __createBinding: () => __createBinding, + __decorate: () => __decorate, + __disposeResources: () => __disposeResources, + __esDecorate: () => __esDecorate, + __exportStar: () => __exportStar, + __extends: () => __extends, + __generator: () => __generator, + __importDefault: () => __importDefault, + __importStar: () => __importStar, + __makeTemplateObject: () => __makeTemplateObject, + __metadata: () => __metadata, + __param: () => __param, + __propKey: () => __propKey, + __read: () => __read, + __rest: () => __rest, + __rewriteRelativeImportExtension: () => __rewriteRelativeImportExtension, + __runInitializers: () => __runInitializers, + __setFunctionName: () => __setFunctionName, + __spread: () => __spread, + __spreadArray: () => __spreadArray, + __spreadArrays: () => __spreadArrays, + __values: () => __values2, + default: () => tslib_es6_default }); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/agentPolicy.js -var require_agentPolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/agentPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.agentPolicyName = void 0; - exports2.agentPolicy = agentPolicy; - var policies_1 = require_internal2(); - exports2.agentPolicyName = policies_1.agentPolicyName; - function agentPolicy(agent) { - return (0, policies_1.agentPolicy)(agent); - } +function __extends(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; } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js -var require_tlsPolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.tlsPolicyName = void 0; - exports2.tlsPolicy = tlsPolicy; - var policies_1 = require_internal2(); - exports2.tlsPolicyName = policies_1.tlsPolicyName; - function tlsPolicy(tlsSettings) { - return (0, policies_1.tlsPolicy)(tlsSettings); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; } - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js + return t; +} +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); + return f; + } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _2, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context5 = {}; + for (var p in contextIn) context5[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context5.access[p] = contextIn.access[p]; + context5.addInitializer = function(f) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); + }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context5); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_2 = accept(result.get)) descriptor.get = _2; + if (_2 = accept(result.set)) descriptor.set = _2; + if (_2 = accept(result.init)) initializers.unshift(_2); + } else if (_2 = accept(result)) { + if (kind === "field") initializers.unshift(_2); + else descriptor[key] = _2; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +} +function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +} +function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +} +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); + }); + } + return new (P || (P = Promise))(function(resolve15, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator(thisArg, body) { + var _2 = { label: 0, sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { + return this; + }), g; + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_2 = 0)), _2) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _2.label++; + return { value: op[1], done: false }; + case 5: + _2.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _2.ops.pop(); + _2.trys.pop(); + continue; + default: + if (!(t = _2.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _2 = 0; + continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _2.label = op[1]; + break; + } + if (op[0] === 6 && _2.label < t[1]) { + _2.label = t[1]; + t = op; + break; + } + if (t && _2.label < t[2]) { + _2.label = t[2]; + _2.ops.push(op); + break; + } + if (t[2]) _2.ops.pop(); + _2.trys.pop(); + continue; + } + op = body.call(thisArg, _2); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } +} +function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} +function __values2(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function() { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error3) { + e = { error: error3 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; +} +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function awaitReturn(f) { + return function(v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function(v) { + return new Promise(function(a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); + } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } +} +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function(e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function() { + return this; + }, i; + function verb(n, f) { + i[n] = o[n] ? function(v) { + return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; + } : f; + } +} +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve15, reject) { + v = o[n](v), settle(resolve15, reject, v.done, v.value); + }); + }; + } + function settle(resolve15, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve15({ value: v2, done: d }); + }, reject); + } +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar(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; +} +function __importDefault(mod) { + return mod && mod.__esModule ? mod : { default: mod }; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldIn(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} +function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { + try { + inner.call(this); + } catch (e) { + return Promise.reject(e); + } + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; +} +function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); + } else s |= 1; + } catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} +function __rewriteRelativeImportExtension(path30, preserveJsx) { + if (typeof path30 === "string" && /^\.\.?\//.test(path30)) { + return path30.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext2, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext2 || !cm) ? m : d + ext2 + "." + cm.toLowerCase() + "js"; + }); + } + return path30; +} +var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys, _SuppressedError, tslib_es6_default; +var init_tslib_es6 = __esm({ + "node_modules/tslib/tslib.es6.mjs"() { + extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; + }; + return extendStatics(d, b); + }; + __assign = function() { + __assign = Object.assign || function __assign2(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); + }; + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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 === void 0) k2 = k; + o[k2] = m[k]; + }); + __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error3, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error3, e.suppressed = suppressed, e; + }; + tslib_es6_default = { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values: __values2, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, + __rewriteRelativeImportExtension + }; + } +}); + +// node_modules/@typespec/ts-http-runtime/dist/commonjs/util/sha256.js +var require_sha256 = __commonJS({ + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/sha256.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var sha256_exports = {}; + __export2(sha256_exports, { + computeSha256Hash: () => computeSha256Hash2, + computeSha256Hmac: () => computeSha256Hmac2 + }); + module2.exports = __toCommonJS2(sha256_exports); + var import_node_crypto = require("node:crypto"); + async function computeSha256Hmac2(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return (0, import_node_crypto.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); + } + async function computeSha256Hash2(content, encoding) { + return (0, import_node_crypto.createHash)("sha256").update(content).digest(encoding); + } + } +}); + +// node_modules/@typespec/ts-http-runtime/dist/commonjs/util/internal.js +var require_internal3 = __commonJS({ + "node_modules/@typespec/ts-http-runtime/dist/commonjs/util/internal.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export2(internal_exports, { + Sanitizer: () => import_sanitizer.Sanitizer, + calculateRetryDelay: () => import_delay.calculateRetryDelay, + computeSha256Hash: () => import_sha256.computeSha256Hash, + computeSha256Hmac: () => import_sha256.computeSha256Hmac, + getRandomIntegerInclusive: () => import_random.getRandomIntegerInclusive, + isBrowser: () => import_env.isBrowser, + isBun: () => import_env.isBun, + isDeno: () => import_env.isDeno, + isError: () => import_error2.isError, + isNodeLike: () => import_env.isNodeLike, + isNodeRuntime: () => import_env.isNodeRuntime, + isObject: () => import_object.isObject, + isReactNative: () => import_env.isReactNative, + isWebWorker: () => import_env.isWebWorker, + randomUUID: () => import_uuid2.randomUUID, + stringToUint8Array: () => import_bytesEncoding.stringToUint8Array, + uint8ArrayToString: () => import_bytesEncoding.uint8ArrayToString + }); + module2.exports = __toCommonJS2(internal_exports); + var import_delay = require_delay(); + var import_random = require_random(); + var import_object = require_object(); + var import_error2 = require_error(); + var import_sha256 = require_sha256(); + var import_uuid2 = require_uuidUtils(); + var import_env = require_env(); + var import_bytesEncoding = require_bytesEncoding(); + var import_sanitizer = require_sanitizer(); + } +}); + +// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js +var require_aborterUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.cancelablePromiseRace = cancelablePromiseRace; + async function cancelablePromiseRace(abortablePromiseBuilders, options) { + const aborter = new AbortController(); + function abortHandler() { + aborter.abort(); + } + options?.abortSignal?.addEventListener("abort", abortHandler); + try { + return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); + } finally { + aborter.abort(); + options?.abortSignal?.removeEventListener("abort", abortHandler); + } + } + } +}); + +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError2 = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError2 = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } + }; + exports2.AbortError = AbortError2; + } +}); + +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs3 = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError2(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); + } +}); + +// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js +var require_createAbortablePromise = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createAbortablePromise = createAbortablePromise; + var abort_controller_1 = require_commonjs3(); + function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options ?? {}; + return new Promise((resolve15, reject) => { + function rejectOnAbort() { + reject(new abort_controller_1.AbortError(abortErrorMsg ?? "The operation was aborted.")); + } + function removeListeners() { + abortSignal?.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort?.(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal?.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve15(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } catch (err) { + reject(err); + } + abortSignal?.addEventListener("abort", onAbort); + }); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/delay.js +var require_delay2 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.delay = delay2; + exports2.calculateRetryDelay = calculateRetryDelay2; + var createAbortablePromise_js_1 = require_createAbortablePromise(); + var util_1 = require_internal3(); + var StandardAbortMessage = "The delay was aborted."; + function delay2(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options ?? {}; + return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve15) => { + token = setTimeout(resolve15, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg ?? StandardAbortMessage + }); + } + function calculateRetryDelay2(retryAttempt, config) { + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + const retryAfterInMs = clampedDelay / 2 + (0, util_1.getRandomIntegerInclusive)(0, clampedDelay / 2); + return { retryAfterInMs }; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/error.js +var require_error2 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getErrorMessage = getErrorMessage2; + var util_1 = require_internal3(); + function getErrorMessage2(e) { + if ((0, util_1.isError)(e)) { + return e.message; + } else { + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } else { + stringified = String(e); + } + } catch (err) { + stringified = "[unable to stringify input]"; + } + return `Unknown error ${stringified}`; + } + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/typeGuards.js +var require_typeGuards2 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isDefined = isDefined3; + exports2.isObjectWithProperties = isObjectWithProperties; + exports2.objectHasProperty = objectHasProperty; + function isDefined3(thing) { + return typeof thing !== "undefined" && thing !== null; + } + function isObjectWithProperties(thing, properties) { + if (!isDefined3(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; + } + function objectHasProperty(thing, property) { + return isDefined3(thing) && typeof thing === "object" && property in thing; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/index.js +var require_commonjs4 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isWebWorker = exports2.isReactNative = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isDeno = exports2.isBun = exports2.isBrowser = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.getErrorMessage = exports2.delay = exports2.createAbortablePromise = exports2.cancelablePromiseRace = void 0; + exports2.calculateRetryDelay = calculateRetryDelay2; + exports2.computeSha256Hash = computeSha256Hash2; + exports2.computeSha256Hmac = computeSha256Hmac2; + exports2.getRandomIntegerInclusive = getRandomIntegerInclusive2; + exports2.isError = isError2; + exports2.isObject = isObject4; + exports2.randomUUID = randomUUID2; + exports2.uint8ArrayToString = uint8ArrayToString2; + exports2.stringToUint8Array = stringToUint8Array2; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var tspRuntime = tslib_1.__importStar(require_internal3()); + var aborterUtils_js_1 = require_aborterUtils(); + Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { + return aborterUtils_js_1.cancelablePromiseRace; + } }); + var createAbortablePromise_js_1 = require_createAbortablePromise(); + Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { + return createAbortablePromise_js_1.createAbortablePromise; + } }); + var delay_js_1 = require_delay2(); + Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { + return delay_js_1.delay; + } }); + var error_js_1 = require_error2(); + Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { + return error_js_1.getErrorMessage; + } }); + var typeGuards_js_1 = require_typeGuards2(); + Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { + return typeGuards_js_1.isDefined; + } }); + Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { + return typeGuards_js_1.isObjectWithProperties; + } }); + Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { + return typeGuards_js_1.objectHasProperty; + } }); + function calculateRetryDelay2(retryAttempt, config) { + return tspRuntime.calculateRetryDelay(retryAttempt, config); + } + function computeSha256Hash2(content, encoding) { + return tspRuntime.computeSha256Hash(content, encoding); + } + function computeSha256Hmac2(key, stringToSign, encoding) { + return tspRuntime.computeSha256Hmac(key, stringToSign, encoding); + } + function getRandomIntegerInclusive2(min, max) { + return tspRuntime.getRandomIntegerInclusive(min, max); + } + function isError2(e) { + return tspRuntime.isError(e); + } + function isObject4(input) { + return tspRuntime.isObject(input); + } + function randomUUID2() { + return tspRuntime.randomUUID(); + } + exports2.isBrowser = tspRuntime.isBrowser; + exports2.isBun = tspRuntime.isBun; + exports2.isDeno = tspRuntime.isDeno; + exports2.isNode = tspRuntime.isNodeLike; + exports2.isNodeLike = tspRuntime.isNodeLike; + exports2.isNodeRuntime = tspRuntime.isNodeRuntime; + exports2.isReactNative = tspRuntime.isReactNative; + exports2.isWebWorker = tspRuntime.isWebWorker; + function uint8ArrayToString2(bytes, format) { + return tspRuntime.uint8ArrayToString(bytes, format); + } + function stringToUint8Array2(value, format) { + return tspRuntime.stringToUint8Array(value, format); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js +var require_proxyPolicy2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var proxyPolicy_exports = {}; + __export2(proxyPolicy_exports, { + getDefaultProxySettings: () => getDefaultProxySettings2, + proxyPolicy: () => proxyPolicy2, + proxyPolicyName: () => proxyPolicyName2 + }); + module2.exports = __toCommonJS2(proxyPolicy_exports); + var import_policies = require_internal2(); + var proxyPolicyName2 = import_policies.proxyPolicyName; + function getDefaultProxySettings2(proxyUrl) { + return (0, import_policies.getDefaultProxySettings)(proxyUrl); + } + function proxyPolicy2(proxySettings, options) { + return (0, import_policies.proxyPolicy)(proxySettings, options); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js +var require_setClientRequestIdPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var setClientRequestIdPolicy_exports = {}; + __export2(setClientRequestIdPolicy_exports, { + setClientRequestIdPolicy: () => setClientRequestIdPolicy2, + setClientRequestIdPolicyName: () => setClientRequestIdPolicyName2 + }); + module2.exports = __toCommonJS2(setClientRequestIdPolicy_exports); + var setClientRequestIdPolicyName2 = "setClientRequestIdPolicy"; + function setClientRequestIdPolicy2(requestIdHeaderName = "x-ms-client-request-id") { + return { + name: setClientRequestIdPolicyName2, + async sendRequest(request3, next) { + if (!request3.headers.has(requestIdHeaderName)) { + request3.headers.set(requestIdHeaderName, request3.requestId); + } + return next(request3); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/agentPolicy.js +var require_agentPolicy2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/agentPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var agentPolicy_exports = {}; + __export2(agentPolicy_exports, { + agentPolicy: () => agentPolicy2, + agentPolicyName: () => agentPolicyName2 + }); + module2.exports = __toCommonJS2(agentPolicy_exports); + var import_policies = require_internal2(); + var agentPolicyName2 = import_policies.agentPolicyName; + function agentPolicy2(agent) { + return (0, import_policies.agentPolicy)(agent); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js +var require_tlsPolicy2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var tlsPolicy_exports = {}; + __export2(tlsPolicy_exports, { + tlsPolicy: () => tlsPolicy2, + tlsPolicyName: () => tlsPolicyName2 + }); + module2.exports = __toCommonJS2(tlsPolicy_exports); + var import_policies = require_internal2(); + var tlsPolicyName2 = import_policies.tlsPolicyName; + function tlsPolicy2(tlsSettings) { + return (0, import_policies.tlsPolicy)(tlsSettings); + } + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js var require_tracingContext = __commonJS({ "node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js"(exports2) { "use strict"; @@ -41038,42 +50614,80 @@ var require_commonjs5 = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js var require_restError3 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RestError = void 0; - exports2.isRestError = isRestError; - var ts_http_runtime_1 = require_commonjs(); - exports2.RestError = ts_http_runtime_1.RestError; - function isRestError(e) { - return (0, ts_http_runtime_1.isRestError)(e); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var restError_exports = {}; + __export2(restError_exports, { + RestError: () => RestError2, + isRestError: () => isRestError2 + }); + module2.exports = __toCommonJS2(restError_exports); + var import_ts_http_runtime = require_commonjs(); + var RestError2 = import_ts_http_runtime.RestError; + function isRestError2(e) { + return (0, import_ts_http_runtime.isRestError)(e); } } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js var require_tracingPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.tracingPolicyName = void 0; - exports2.tracingPolicy = tracingPolicy; - var core_tracing_1 = require_commonjs5(); - var constants_js_1 = require_constants9(); - var userAgent_js_1 = require_userAgent2(); - var log_js_1 = require_log3(); - var core_util_1 = require_commonjs4(); - var restError_js_1 = require_restError3(); - var util_1 = require_internal3(); - exports2.tracingPolicyName = "tracingPolicy"; - function tracingPolicy(options = {}) { - const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); - const sanitizer = new util_1.Sanitizer({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var tracingPolicy_exports = {}; + __export2(tracingPolicy_exports, { + tracingPolicy: () => tracingPolicy2, + tracingPolicyName: () => tracingPolicyName2 + }); + module2.exports = __toCommonJS2(tracingPolicy_exports); + var import_core_tracing = require_commonjs5(); + var import_constants5 = require_constants9(); + var import_userAgent = require_userAgent2(); + var import_log = require_log3(); + var import_core_util = require_commonjs4(); + var import_restError = require_restError3(); + var import_util61 = require_internal3(); + var tracingPolicyName2 = "tracingPolicy"; + function tracingPolicy2(options = {}) { + const userAgentPromise = (0, import_userAgent.getUserAgentValue)(options.userAgentPrefix); + const sanitizer = new import_util61.Sanitizer({ additionalAllowedQueryParameters: options.additionalAllowedQueryParameters }); const tracingClient = tryCreateTracingClient(); return { - name: exports2.tracingPolicyName, + name: tracingPolicyName2, async sendRequest(request3, next) { if (!tracingClient) { return next(request3); @@ -41105,33 +50719,39 @@ var require_tracingPolicy = __commonJS({ } function tryCreateTracingClient() { try { - return (0, core_tracing_1.createTracingClient)({ + return (0, import_core_tracing.createTracingClient)({ namespace: "", packageName: "@azure/core-rest-pipeline", - packageVersion: constants_js_1.SDK_VERSION + packageVersion: import_constants5.SDK_VERSION }); } catch (e) { - log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`); + import_log.logger.warning(`Error when creating the TracingClient: ${(0, import_core_util.getErrorMessage)(e)}`); return void 0; } } function tryCreateSpan(tracingClient, request3, spanAttributes) { try { - const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request3.method}`, { tracingOptions: request3.tracingOptions }, { - spanKind: "client", - spanAttributes - }); + const { span, updatedOptions } = tracingClient.startSpan( + `HTTP ${request3.method}`, + { tracingOptions: request3.tracingOptions }, + { + spanKind: "client", + spanAttributes + } + ); if (!span.isRecording()) { span.end(); return void 0; } - const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext); + const headers = tracingClient.createRequestHeaders( + updatedOptions.tracingOptions.tracingContext + ); for (const [key, value] of Object.entries(headers)) { request3.headers.set(key, value); } return { span, tracingContext: updatedOptions.tracingOptions.tracingContext }; } catch (e) { - log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + import_log.logger.warning(`Skipping creating a tracing span due to an error: ${(0, import_core_util.getErrorMessage)(e)}`); return void 0; } } @@ -41139,14 +50759,14 @@ var require_tracingPolicy = __commonJS({ try { span.setStatus({ status: "error", - error: (0, core_util_1.isError)(error3) ? error3 : void 0 + error: (0, import_core_util.isError)(error3) ? error3 : void 0 }); - if ((0, restError_js_1.isRestError)(error3) && error3.statusCode) { + if ((0, import_restError.isRestError)(error3) && error3.statusCode) { span.setAttribute("http.status_code", error3.statusCode); } span.end(); } catch (e) { - log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + import_log.logger.warning(`Skipping tracing span processing due to an error: ${(0, import_core_util.getErrorMessage)(e)}`); } } function tryProcessResponse(span, response) { @@ -41163,7 +50783,7 @@ var require_tracingPolicy = __commonJS({ } span.end(); } catch (e) { - log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + import_log.logger.warning(`Skipping tracing span processing due to an error: ${(0, import_core_util.getErrorMessage)(e)}`); } } } @@ -41171,16 +50791,39 @@ var require_tracingPolicy = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/util/wrapAbortSignal.js var require_wrapAbortSignal = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/wrapAbortSignal.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.wrapAbortSignalLike = wrapAbortSignalLike; + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/wrapAbortSignal.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var wrapAbortSignal_exports = {}; + __export2(wrapAbortSignal_exports, { + wrapAbortSignalLike: () => wrapAbortSignalLike + }); + module2.exports = __toCommonJS2(wrapAbortSignal_exports); function wrapAbortSignalLike(abortSignalLike) { if (abortSignalLike instanceof AbortSignal) { return { abortSignal: abortSignalLike }; } if (abortSignalLike.aborted) { - return { abortSignal: AbortSignal.abort(abortSignalLike.reason) }; + return { + abortSignal: AbortSignal.abort( + "reason" in abortSignalLike ? abortSignalLike.reason : void 0 + ) + }; } const controller = new AbortController(); let needsCleanup = true; @@ -41191,7 +50834,7 @@ var require_wrapAbortSignal = __commonJS({ } } function listener() { - controller.abort(abortSignalLike.reason); + controller.abort("reason" in abortSignalLike ? abortSignalLike.reason : void 0); cleanup(); } abortSignalLike.addEventListener("abort", listener); @@ -41202,21 +50845,40 @@ var require_wrapAbortSignal = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/wrapAbortSignalLikePolicy.js var require_wrapAbortSignalLikePolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/wrapAbortSignalLikePolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.wrapAbortSignalLikePolicyName = void 0; - exports2.wrapAbortSignalLikePolicy = wrapAbortSignalLikePolicy; - var wrapAbortSignal_js_1 = require_wrapAbortSignal(); - exports2.wrapAbortSignalLikePolicyName = "wrapAbortSignalLikePolicy"; + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/wrapAbortSignalLikePolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var wrapAbortSignalLikePolicy_exports = {}; + __export2(wrapAbortSignalLikePolicy_exports, { + wrapAbortSignalLikePolicy: () => wrapAbortSignalLikePolicy, + wrapAbortSignalLikePolicyName: () => wrapAbortSignalLikePolicyName + }); + module2.exports = __toCommonJS2(wrapAbortSignalLikePolicy_exports); + var import_wrapAbortSignal = require_wrapAbortSignal(); + var wrapAbortSignalLikePolicyName = "wrapAbortSignalLikePolicy"; function wrapAbortSignalLikePolicy() { return { - name: exports2.wrapAbortSignalLikePolicyName, + name: wrapAbortSignalLikePolicyName, sendRequest: async (request3, next) => { if (!request3.abortSignal) { return next(request3); } - const { abortSignal, cleanup } = (0, wrapAbortSignal_js_1.wrapAbortSignalLike)(request3.abortSignal); + const { abortSignal, cleanup } = (0, import_wrapAbortSignal.wrapAbortSignalLike)(request3.abortSignal); request3.abortSignal = abortSignal; try { return await next(request3); @@ -41231,50 +50893,69 @@ var require_wrapAbortSignalLikePolicy = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js var require_createPipelineFromOptions2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createPipelineFromOptions = createPipelineFromOptions; - var logPolicy_js_1 = require_logPolicy2(); - var pipeline_js_1 = require_pipeline2(); - var redirectPolicy_js_1 = require_redirectPolicy2(); - var userAgentPolicy_js_1 = require_userAgentPolicy2(); - var multipartPolicy_js_1 = require_multipartPolicy2(); - var decompressResponsePolicy_js_1 = require_decompressResponsePolicy2(); - var defaultRetryPolicy_js_1 = require_defaultRetryPolicy2(); - var formDataPolicy_js_1 = require_formDataPolicy2(); - var core_util_1 = require_commonjs4(); - var proxyPolicy_js_1 = require_proxyPolicy2(); - var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); - var agentPolicy_js_1 = require_agentPolicy2(); - var tlsPolicy_js_1 = require_tlsPolicy2(); - var tracingPolicy_js_1 = require_tracingPolicy(); - var wrapAbortSignalLikePolicy_js_1 = require_wrapAbortSignalLikePolicy(); - function createPipelineFromOptions(options) { - const pipeline2 = (0, pipeline_js_1.createEmptyPipeline)(); - if (core_util_1.isNodeLike) { + "node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var createPipelineFromOptions_exports = {}; + __export2(createPipelineFromOptions_exports, { + createPipelineFromOptions: () => createPipelineFromOptions2 + }); + module2.exports = __toCommonJS2(createPipelineFromOptions_exports); + var import_logPolicy = require_logPolicy2(); + var import_pipeline = require_pipeline2(); + var import_redirectPolicy = require_redirectPolicy2(); + var import_userAgentPolicy = require_userAgentPolicy2(); + var import_multipartPolicy = require_multipartPolicy2(); + var import_decompressResponsePolicy = require_decompressResponsePolicy2(); + var import_defaultRetryPolicy = require_defaultRetryPolicy2(); + var import_formDataPolicy = require_formDataPolicy2(); + var import_core_util = require_commonjs4(); + var import_proxyPolicy = require_proxyPolicy2(); + var import_setClientRequestIdPolicy = require_setClientRequestIdPolicy(); + var import_agentPolicy = require_agentPolicy2(); + var import_tlsPolicy = require_tlsPolicy2(); + var import_tracingPolicy = require_tracingPolicy(); + var import_wrapAbortSignalLikePolicy = require_wrapAbortSignalLikePolicy(); + function createPipelineFromOptions2(options) { + const pipeline2 = (0, import_pipeline.createEmptyPipeline)(); + if (import_core_util.isNodeLike) { if (options.agent) { - pipeline2.addPolicy((0, agentPolicy_js_1.agentPolicy)(options.agent)); + pipeline2.addPolicy((0, import_agentPolicy.agentPolicy)(options.agent)); } if (options.tlsOptions) { - pipeline2.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions)); - } - pipeline2.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions)); - pipeline2.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)()); - } - pipeline2.addPolicy((0, wrapAbortSignalLikePolicy_js_1.wrapAbortSignalLikePolicy)()); - pipeline2.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] }); - pipeline2.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions)); - pipeline2.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)(options.telemetryOptions?.clientRequestIdHeaderName)); - pipeline2.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" }); - pipeline2.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); - pipeline2.addPolicy((0, tracingPolicy_js_1.tracingPolicy)({ ...options.userAgentOptions, ...options.loggingOptions }), { + pipeline2.addPolicy((0, import_tlsPolicy.tlsPolicy)(options.tlsOptions)); + } + pipeline2.addPolicy((0, import_proxyPolicy.proxyPolicy)(options.proxyOptions)); + pipeline2.addPolicy((0, import_decompressResponsePolicy.decompressResponsePolicy)()); + } + pipeline2.addPolicy((0, import_wrapAbortSignalLikePolicy.wrapAbortSignalLikePolicy)()); + pipeline2.addPolicy((0, import_formDataPolicy.formDataPolicy)(), { beforePolicies: [import_multipartPolicy.multipartPolicyName] }); + pipeline2.addPolicy((0, import_userAgentPolicy.userAgentPolicy)(options.userAgentOptions)); + pipeline2.addPolicy((0, import_setClientRequestIdPolicy.setClientRequestIdPolicy)(options.telemetryOptions?.clientRequestIdHeaderName)); + pipeline2.addPolicy((0, import_multipartPolicy.multipartPolicy)(), { afterPhase: "Deserialize" }); + pipeline2.addPolicy((0, import_defaultRetryPolicy.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); + pipeline2.addPolicy((0, import_tracingPolicy.tracingPolicy)({ ...options.userAgentOptions, ...options.loggingOptions }), { afterPhase: "Retry" }); - if (core_util_1.isNodeLike) { - pipeline2.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" }); + if (import_core_util.isNodeLike) { + pipeline2.addPolicy((0, import_redirectPolicy.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" }); } - pipeline2.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" }); + pipeline2.addPolicy((0, import_logPolicy.logPolicy)(options.loggingOptions), { afterPhase: "Sign" }); return pipeline2; } } @@ -41282,17 +50963,36 @@ var require_createPipelineFromOptions2 = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js var require_defaultHttpClient2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createDefaultHttpClient = createDefaultHttpClient; - var ts_http_runtime_1 = require_commonjs(); - var wrapAbortSignal_js_1 = require_wrapAbortSignal(); - function createDefaultHttpClient() { - const client = (0, ts_http_runtime_1.createDefaultHttpClient)(); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var defaultHttpClient_exports = {}; + __export2(defaultHttpClient_exports, { + createDefaultHttpClient: () => createDefaultHttpClient2 + }); + module2.exports = __toCommonJS2(defaultHttpClient_exports); + var import_ts_http_runtime = require_commonjs(); + var import_wrapAbortSignal = require_wrapAbortSignal(); + function createDefaultHttpClient2() { + const client = (0, import_ts_http_runtime.createDefaultHttpClient)(); return { async sendRequest(request3) { - const { abortSignal, cleanup } = request3.abortSignal ? (0, wrapAbortSignal_js_1.wrapAbortSignalLike)(request3.abortSignal) : {}; + const { abortSignal, cleanup } = request3.abortSignal ? (0, import_wrapAbortSignal.wrapAbortSignalLike)(request3.abortSignal) : {}; try { request3.abortSignal = abortSignal; return await client.sendRequest(request3); @@ -41307,87 +51007,201 @@ var require_defaultHttpClient2 = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js var require_httpHeaders2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createHttpHeaders = createHttpHeaders; - var ts_http_runtime_1 = require_commonjs(); - function createHttpHeaders(rawHeaders) { - return (0, ts_http_runtime_1.createHttpHeaders)(rawHeaders); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var httpHeaders_exports = {}; + __export2(httpHeaders_exports, { + createHttpHeaders: () => createHttpHeaders2 + }); + module2.exports = __toCommonJS2(httpHeaders_exports); + var import_ts_http_runtime = require_commonjs(); + function createHttpHeaders2(rawHeaders) { + return (0, import_ts_http_runtime.createHttpHeaders)(rawHeaders); } } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js var require_pipelineRequest2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createPipelineRequest = createPipelineRequest; - var ts_http_runtime_1 = require_commonjs(); - function createPipelineRequest(options) { - return (0, ts_http_runtime_1.createPipelineRequest)(options); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var pipelineRequest_exports = {}; + __export2(pipelineRequest_exports, { + createPipelineRequest: () => createPipelineRequest2 + }); + module2.exports = __toCommonJS2(pipelineRequest_exports); + var import_ts_http_runtime = require_commonjs(); + function createPipelineRequest2(options) { + return (0, import_ts_http_runtime.createPipelineRequest)(options); } } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js var require_exponentialRetryPolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exponentialRetryPolicyName = void 0; - exports2.exponentialRetryPolicy = exponentialRetryPolicy; - var policies_1 = require_internal2(); - exports2.exponentialRetryPolicyName = policies_1.exponentialRetryPolicyName; - function exponentialRetryPolicy(options = {}) { - return (0, policies_1.exponentialRetryPolicy)(options); - } + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var exponentialRetryPolicy_exports = {}; + __export2(exponentialRetryPolicy_exports, { + exponentialRetryPolicy: () => exponentialRetryPolicy2, + exponentialRetryPolicyName: () => exponentialRetryPolicyName2 + }); + module2.exports = __toCommonJS2(exponentialRetryPolicy_exports); + var import_policies = require_internal2(); + var exponentialRetryPolicyName2 = import_policies.exponentialRetryPolicyName; + function exponentialRetryPolicy2(options = {}) { + return (0, import_policies.exponentialRetryPolicy)(options); + } } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js var require_systemErrorRetryPolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.systemErrorRetryPolicyName = void 0; - exports2.systemErrorRetryPolicy = systemErrorRetryPolicy; - var policies_1 = require_internal2(); - exports2.systemErrorRetryPolicyName = policies_1.systemErrorRetryPolicyName; - function systemErrorRetryPolicy(options = {}) { - return (0, policies_1.systemErrorRetryPolicy)(options); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var systemErrorRetryPolicy_exports = {}; + __export2(systemErrorRetryPolicy_exports, { + systemErrorRetryPolicy: () => systemErrorRetryPolicy2, + systemErrorRetryPolicyName: () => systemErrorRetryPolicyName2 + }); + module2.exports = __toCommonJS2(systemErrorRetryPolicy_exports); + var import_policies = require_internal2(); + var systemErrorRetryPolicyName2 = import_policies.systemErrorRetryPolicyName; + function systemErrorRetryPolicy2(options = {}) { + return (0, import_policies.systemErrorRetryPolicy)(options); } } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js var require_throttlingRetryPolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.throttlingRetryPolicyName = void 0; - exports2.throttlingRetryPolicy = throttlingRetryPolicy; - var policies_1 = require_internal2(); - exports2.throttlingRetryPolicyName = policies_1.throttlingRetryPolicyName; - function throttlingRetryPolicy(options = {}) { - return (0, policies_1.throttlingRetryPolicy)(options); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var throttlingRetryPolicy_exports = {}; + __export2(throttlingRetryPolicy_exports, { + throttlingRetryPolicy: () => throttlingRetryPolicy2, + throttlingRetryPolicyName: () => throttlingRetryPolicyName2 + }); + module2.exports = __toCommonJS2(throttlingRetryPolicy_exports); + var import_policies = require_internal2(); + var throttlingRetryPolicyName2 = import_policies.throttlingRetryPolicyName; + function throttlingRetryPolicy2(options = {}) { + return (0, import_policies.throttlingRetryPolicy)(options); } } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js var require_retryPolicy2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.retryPolicy = retryPolicy; - var logger_1 = require_commonjs2(); - var constants_js_1 = require_constants9(); - var policies_1 = require_internal2(); - var retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy"); - function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) { - return (0, policies_1.retryPolicy)(strategies, { + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var retryPolicy_exports = {}; + __export2(retryPolicy_exports, { + retryPolicy: () => retryPolicy2 + }); + module2.exports = __toCommonJS2(retryPolicy_exports); + var import_logger = require_commonjs2(); + var import_constants5 = require_constants9(); + var import_policies = require_internal2(); + var retryPolicyLogger = (0, import_logger.createClientLogger)("core-rest-pipeline retryPolicy"); + function retryPolicy2(strategies, options = { maxRetries: import_constants5.DEFAULT_RETRY_POLICY_COUNT }) { + return (0, import_policies.retryPolicy)(strategies, { logger: retryPolicyLogger, ...options }); @@ -41397,13 +51211,32 @@ var require_retryPolicy2 = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js var require_tokenCycler = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DEFAULT_CYCLER_OPTIONS = void 0; - exports2.createTokenCycler = createTokenCycler; - var core_util_1 = require_commonjs4(); - exports2.DEFAULT_CYCLER_OPTIONS = { + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var tokenCycler_exports = {}; + __export2(tokenCycler_exports, { + DEFAULT_CYCLER_OPTIONS: () => DEFAULT_CYCLER_OPTIONS, + createTokenCycler: () => createTokenCycler + }); + module2.exports = __toCommonJS2(tokenCycler_exports); + var import_core_util = require_commonjs4(); + var DEFAULT_CYCLER_OPTIONS = { forcedRefreshWindowInMs: 1e3, // Force waiting for a refresh 1s before the token expires retryIntervalInMs: 3e3, @@ -41429,7 +51262,7 @@ var require_tokenCycler = __commonJS({ } let token = await tryGetAccessToken(); while (token === null) { - await (0, core_util_1.delay)(retryIntervalInMs); + await (0, import_core_util.delay)(retryIntervalInMs); token = await tryGetAccessToken(); } return token; @@ -41439,7 +51272,7 @@ var require_tokenCycler = __commonJS({ let token = null; let tenantId; const options = { - ...exports2.DEFAULT_CYCLER_OPTIONS, + ...DEFAULT_CYCLER_OPTIONS, ...tokenCyclerOptions }; const cycler = { @@ -41454,13 +51287,16 @@ var require_tokenCycler = __commonJS({ * window and not already refreshing) */ get shouldRefresh() { + if (token === null) { + return true; + } if (cycler.isRefreshing) { return false; } - if (token?.refreshAfterTimestamp && token.refreshAfterTimestamp < Date.now()) { + if (token.refreshAfterTimestamp && token.refreshAfterTimestamp < Date.now()) { return true; } - return (token?.expiresOnTimestamp ?? 0) - options.refreshWindowInMs < Date.now(); + return token.expiresOnTimestamp - options.refreshWindowInMs < Date.now(); }, /** * Produces true if the cycler MUST refresh (null or nearly-expired @@ -41513,21 +51349,40 @@ var require_tokenCycler = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js var require_bearerTokenAuthenticationPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.bearerTokenAuthenticationPolicyName = void 0; - exports2.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; - exports2.parseChallenges = parseChallenges; - var tokenCycler_js_1 = require_tokenCycler(); - var log_js_1 = require_log3(); - var restError_js_1 = require_restError3(); - exports2.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var bearerTokenAuthenticationPolicy_exports = {}; + __export2(bearerTokenAuthenticationPolicy_exports, { + bearerTokenAuthenticationPolicy: () => bearerTokenAuthenticationPolicy2, + bearerTokenAuthenticationPolicyName: () => bearerTokenAuthenticationPolicyName2, + parseChallenges: () => parseChallenges + }); + module2.exports = __toCommonJS2(bearerTokenAuthenticationPolicy_exports); + var import_tokenCycler = require_tokenCycler(); + var import_log = require_log3(); + var import_restError = require_restError3(); + var bearerTokenAuthenticationPolicyName2 = "bearerTokenAuthenticationPolicy"; async function trySendRequest(request3, next) { try { return [await next(request3), void 0]; } catch (e) { - if ((0, restError_js_1.isRestError)(e) && e.response) { + if ((0, import_restError.isRestError)(e) && e.response) { return [e.response, e]; } else { throw e; @@ -41558,22 +51413,25 @@ var require_bearerTokenAuthenticationPolicy = __commonJS({ if (!accessToken) { return false; } - onChallengeOptions.request.headers.set("Authorization", `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`); + onChallengeOptions.request.headers.set( + "Authorization", + `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}` + ); return true; } - function bearerTokenAuthenticationPolicy(options) { + function bearerTokenAuthenticationPolicy2(options) { const { credential, scopes, challengeCallbacks } = options; - const logger = options.logger || log_js_1.logger; + const logger2 = options.logger || import_log.logger; const callbacks = { authorizeRequest: challengeCallbacks?.authorizeRequest?.bind(challengeCallbacks) ?? defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks?.authorizeRequestOnChallenge?.bind(challengeCallbacks) }; - const getAccessToken = credential ? (0, tokenCycler_js_1.createTokenCycler)( + const getAccessToken = credential ? (0, import_tokenCycler.createTokenCycler)( credential /* , options */ ) : () => Promise.resolve(null); return { - name: exports2.bearerTokenAuthenticationPolicyName, + name: bearerTokenAuthenticationPolicyName2, /** * If there's no challenge parameter: * - It will try to retrieve the token using the cache, or the credential's getToken. @@ -41589,13 +51447,15 @@ var require_bearerTokenAuthenticationPolicy = __commonJS({ */ async sendRequest(request3, next) { if (!request3.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); + throw new Error( + "Bearer token authentication is not permitted for non-TLS protected (non-https) URLs." + ); } await callbacks.authorizeRequest({ scopes: Array.isArray(scopes) ? scopes : [scopes], request: request3, getAccessToken, - logger + logger: logger2 }); let response; let error3; @@ -41608,16 +51468,21 @@ var require_bearerTokenAuthenticationPolicy = __commonJS({ try { parsedClaim = atob(claims); } catch (e) { - logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`); + logger2.warning( + `The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}` + ); return response; } - shouldSendRequest = await authorizeRequestOnCaeChallenge({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - response, - request: request3, - getAccessToken, - logger - }, parsedClaim); + shouldSendRequest = await authorizeRequestOnCaeChallenge( + { + scopes: Array.isArray(scopes) ? scopes : [scopes], + response, + request: request3, + getAccessToken, + logger: logger2 + }, + parsedClaim + ); if (shouldSendRequest) { [response, error3] = await trySendRequest(request3, next); } @@ -41627,28 +51492,33 @@ var require_bearerTokenAuthenticationPolicy = __commonJS({ request: request3, response, getAccessToken, - logger + logger: logger2 }); if (shouldSendRequest) { [response, error3] = await trySendRequest(request3, next); } if (isChallengeResponse(response)) { - claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate")); + claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate") ?? ""); if (claims) { let parsedClaim; try { parsedClaim = atob(claims); } catch (e) { - logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`); + logger2.warning( + `The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}` + ); return response; } - shouldSendRequest = await authorizeRequestOnCaeChallenge({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - response, - request: request3, - getAccessToken, - logger - }, parsedClaim); + shouldSendRequest = await authorizeRequestOnCaeChallenge( + { + scopes: Array.isArray(scopes) ? scopes : [scopes], + response, + request: request3, + getAccessToken, + logger: logger2 + }, + parsedClaim + ); if (shouldSendRequest) { [response, error3] = await trySendRequest(request3, next); } @@ -41686,28 +51556,47 @@ var require_bearerTokenAuthenticationPolicy = __commonJS({ return; } const parsedChallenges = parseChallenges(challenges); - return parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")?.params.claims; + return parsedChallenges.find( + (x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims" + )?.params.claims; } } }); // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js var require_ndJsonPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ndJsonPolicyName = void 0; - exports2.ndJsonPolicy = ndJsonPolicy; - exports2.ndJsonPolicyName = "ndJsonPolicy"; - function ndJsonPolicy() { + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var ndJsonPolicy_exports = {}; + __export2(ndJsonPolicy_exports, { + ndJsonPolicy: () => ndJsonPolicy2, + ndJsonPolicyName: () => ndJsonPolicyName2 + }); + module2.exports = __toCommonJS2(ndJsonPolicy_exports); + var ndJsonPolicyName2 = "ndJsonPolicy"; + function ndJsonPolicy2() { return { - name: exports2.ndJsonPolicyName, + name: ndJsonPolicyName2, async sendRequest(request3, next) { if (typeof request3.body === "string" && request3.body.startsWith("[")) { const body = JSON.parse(request3.body); - if (Array.isArray(body)) { - request3.body = body.map((item) => JSON.stringify(item) + "\n").join(""); - } + request3.body = body.map((item) => JSON.stringify(item) + "\n").join(""); } return next(request3); } @@ -41718,14 +51607,33 @@ var require_ndJsonPolicy = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.auxiliaryAuthenticationHeaderPolicyName = void 0; - exports2.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy; - var tokenCycler_js_1 = require_tokenCycler(); - var log_js_1 = require_log3(); - exports2.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy"; + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var auxiliaryAuthenticationHeaderPolicy_exports = {}; + __export2(auxiliaryAuthenticationHeaderPolicy_exports, { + auxiliaryAuthenticationHeaderPolicy: () => auxiliaryAuthenticationHeaderPolicy2, + auxiliaryAuthenticationHeaderPolicyName: () => auxiliaryAuthenticationHeaderPolicyName2 + }); + module2.exports = __toCommonJS2(auxiliaryAuthenticationHeaderPolicy_exports); + var import_tokenCycler = require_tokenCycler(); + var import_log = require_log3(); + var auxiliaryAuthenticationHeaderPolicyName2 = "auxiliaryAuthenticationHeaderPolicy"; var AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary"; async function sendAuthorizeRequest(options) { const { scopes, getAccessToken, request: request3 } = options; @@ -41735,40 +51643,51 @@ var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ }; return (await getAccessToken(scopes, getTokenOptions))?.token ?? ""; } - function auxiliaryAuthenticationHeaderPolicy(options) { + function auxiliaryAuthenticationHeaderPolicy2(options) { const { credentials, scopes } = options; - const logger = options.logger || log_js_1.logger; + const logger2 = options.logger || import_log.logger; const tokenCyclerMap = /* @__PURE__ */ new WeakMap(); return { - name: exports2.auxiliaryAuthenticationHeaderPolicyName, + name: auxiliaryAuthenticationHeaderPolicyName2, async sendRequest(request3, next) { if (!request3.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs."); + throw new Error( + "Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs." + ); } if (!credentials || credentials.length === 0) { - logger.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`); + logger2.info( + `${auxiliaryAuthenticationHeaderPolicyName2} header will not be set due to empty credentials.` + ); return next(request3); } const tokenPromises = []; for (const credential of credentials) { let getAccessToken = tokenCyclerMap.get(credential); if (!getAccessToken) { - getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential); + getAccessToken = (0, import_tokenCycler.createTokenCycler)(credential); tokenCyclerMap.set(credential, getAccessToken); } - tokenPromises.push(sendAuthorizeRequest({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request: request3, - getAccessToken, - logger - })); + tokenPromises.push( + sendAuthorizeRequest({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request: request3, + getAccessToken, + logger: logger2 + }) + ); } const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token)); if (auxiliaryTokens.length === 0) { - logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`); + logger2.warning( + `None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.` + ); return next(request3); } - request3.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", ")); + request3.headers.set( + AUTHORIZATION_AUXILIARY_HEADER, + auxiliaryTokens.map((token) => `Bearer ${token}`).join(", ") + ); return next(request3); } }; @@ -41778,174 +51697,100 @@ var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ // node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js var require_commonjs6 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createFileFromStream = exports2.createFile = exports2.agentPolicyName = exports2.agentPolicy = exports2.auxiliaryAuthenticationHeaderPolicyName = exports2.auxiliaryAuthenticationHeaderPolicy = exports2.ndJsonPolicyName = exports2.ndJsonPolicy = exports2.bearerTokenAuthenticationPolicyName = exports2.bearerTokenAuthenticationPolicy = exports2.formDataPolicyName = exports2.formDataPolicy = exports2.tlsPolicyName = exports2.tlsPolicy = exports2.userAgentPolicyName = exports2.userAgentPolicy = exports2.defaultRetryPolicy = exports2.tracingPolicyName = exports2.tracingPolicy = exports2.retryPolicy = exports2.throttlingRetryPolicyName = exports2.throttlingRetryPolicy = exports2.systemErrorRetryPolicyName = exports2.systemErrorRetryPolicy = exports2.redirectPolicyName = exports2.redirectPolicy = exports2.getDefaultProxySettings = exports2.proxyPolicyName = exports2.proxyPolicy = exports2.multipartPolicyName = exports2.multipartPolicy = exports2.logPolicyName = exports2.logPolicy = exports2.setClientRequestIdPolicyName = exports2.setClientRequestIdPolicy = exports2.exponentialRetryPolicyName = exports2.exponentialRetryPolicy = exports2.decompressResponsePolicyName = exports2.decompressResponsePolicy = exports2.isRestError = exports2.RestError = exports2.createPipelineRequest = exports2.createHttpHeaders = exports2.createDefaultHttpClient = exports2.createPipelineFromOptions = exports2.createEmptyPipeline = void 0; - var pipeline_js_1 = require_pipeline2(); - Object.defineProperty(exports2, "createEmptyPipeline", { enumerable: true, get: function() { - return pipeline_js_1.createEmptyPipeline; - } }); - var createPipelineFromOptions_js_1 = require_createPipelineFromOptions2(); - Object.defineProperty(exports2, "createPipelineFromOptions", { enumerable: true, get: function() { - return createPipelineFromOptions_js_1.createPipelineFromOptions; - } }); - var defaultHttpClient_js_1 = require_defaultHttpClient2(); - Object.defineProperty(exports2, "createDefaultHttpClient", { enumerable: true, get: function() { - return defaultHttpClient_js_1.createDefaultHttpClient; - } }); - var httpHeaders_js_1 = require_httpHeaders2(); - Object.defineProperty(exports2, "createHttpHeaders", { enumerable: true, get: function() { - return httpHeaders_js_1.createHttpHeaders; - } }); - var pipelineRequest_js_1 = require_pipelineRequest2(); - Object.defineProperty(exports2, "createPipelineRequest", { enumerable: true, get: function() { - return pipelineRequest_js_1.createPipelineRequest; - } }); - var restError_js_1 = require_restError3(); - Object.defineProperty(exports2, "RestError", { enumerable: true, get: function() { - return restError_js_1.RestError; - } }); - Object.defineProperty(exports2, "isRestError", { enumerable: true, get: function() { - return restError_js_1.isRestError; - } }); - var decompressResponsePolicy_js_1 = require_decompressResponsePolicy2(); - Object.defineProperty(exports2, "decompressResponsePolicy", { enumerable: true, get: function() { - return decompressResponsePolicy_js_1.decompressResponsePolicy; - } }); - Object.defineProperty(exports2, "decompressResponsePolicyName", { enumerable: true, get: function() { - return decompressResponsePolicy_js_1.decompressResponsePolicyName; - } }); - var exponentialRetryPolicy_js_1 = require_exponentialRetryPolicy2(); - Object.defineProperty(exports2, "exponentialRetryPolicy", { enumerable: true, get: function() { - return exponentialRetryPolicy_js_1.exponentialRetryPolicy; - } }); - Object.defineProperty(exports2, "exponentialRetryPolicyName", { enumerable: true, get: function() { - return exponentialRetryPolicy_js_1.exponentialRetryPolicyName; - } }); - var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); - Object.defineProperty(exports2, "setClientRequestIdPolicy", { enumerable: true, get: function() { - return setClientRequestIdPolicy_js_1.setClientRequestIdPolicy; - } }); - Object.defineProperty(exports2, "setClientRequestIdPolicyName", { enumerable: true, get: function() { - return setClientRequestIdPolicy_js_1.setClientRequestIdPolicyName; - } }); - var logPolicy_js_1 = require_logPolicy2(); - Object.defineProperty(exports2, "logPolicy", { enumerable: true, get: function() { - return logPolicy_js_1.logPolicy; - } }); - Object.defineProperty(exports2, "logPolicyName", { enumerable: true, get: function() { - return logPolicy_js_1.logPolicyName; - } }); - var multipartPolicy_js_1 = require_multipartPolicy2(); - Object.defineProperty(exports2, "multipartPolicy", { enumerable: true, get: function() { - return multipartPolicy_js_1.multipartPolicy; - } }); - Object.defineProperty(exports2, "multipartPolicyName", { enumerable: true, get: function() { - return multipartPolicy_js_1.multipartPolicyName; - } }); - var proxyPolicy_js_1 = require_proxyPolicy2(); - Object.defineProperty(exports2, "proxyPolicy", { enumerable: true, get: function() { - return proxyPolicy_js_1.proxyPolicy; - } }); - Object.defineProperty(exports2, "proxyPolicyName", { enumerable: true, get: function() { - return proxyPolicy_js_1.proxyPolicyName; - } }); - Object.defineProperty(exports2, "getDefaultProxySettings", { enumerable: true, get: function() { - return proxyPolicy_js_1.getDefaultProxySettings; - } }); - var redirectPolicy_js_1 = require_redirectPolicy2(); - Object.defineProperty(exports2, "redirectPolicy", { enumerable: true, get: function() { - return redirectPolicy_js_1.redirectPolicy; - } }); - Object.defineProperty(exports2, "redirectPolicyName", { enumerable: true, get: function() { - return redirectPolicy_js_1.redirectPolicyName; - } }); - var systemErrorRetryPolicy_js_1 = require_systemErrorRetryPolicy2(); - Object.defineProperty(exports2, "systemErrorRetryPolicy", { enumerable: true, get: function() { - return systemErrorRetryPolicy_js_1.systemErrorRetryPolicy; - } }); - Object.defineProperty(exports2, "systemErrorRetryPolicyName", { enumerable: true, get: function() { - return systemErrorRetryPolicy_js_1.systemErrorRetryPolicyName; - } }); - var throttlingRetryPolicy_js_1 = require_throttlingRetryPolicy2(); - Object.defineProperty(exports2, "throttlingRetryPolicy", { enumerable: true, get: function() { - return throttlingRetryPolicy_js_1.throttlingRetryPolicy; - } }); - Object.defineProperty(exports2, "throttlingRetryPolicyName", { enumerable: true, get: function() { - return throttlingRetryPolicy_js_1.throttlingRetryPolicyName; - } }); - var retryPolicy_js_1 = require_retryPolicy2(); - Object.defineProperty(exports2, "retryPolicy", { enumerable: true, get: function() { - return retryPolicy_js_1.retryPolicy; - } }); - var tracingPolicy_js_1 = require_tracingPolicy(); - Object.defineProperty(exports2, "tracingPolicy", { enumerable: true, get: function() { - return tracingPolicy_js_1.tracingPolicy; - } }); - Object.defineProperty(exports2, "tracingPolicyName", { enumerable: true, get: function() { - return tracingPolicy_js_1.tracingPolicyName; - } }); - var defaultRetryPolicy_js_1 = require_defaultRetryPolicy2(); - Object.defineProperty(exports2, "defaultRetryPolicy", { enumerable: true, get: function() { - return defaultRetryPolicy_js_1.defaultRetryPolicy; - } }); - var userAgentPolicy_js_1 = require_userAgentPolicy2(); - Object.defineProperty(exports2, "userAgentPolicy", { enumerable: true, get: function() { - return userAgentPolicy_js_1.userAgentPolicy; - } }); - Object.defineProperty(exports2, "userAgentPolicyName", { enumerable: true, get: function() { - return userAgentPolicy_js_1.userAgentPolicyName; - } }); - var tlsPolicy_js_1 = require_tlsPolicy2(); - Object.defineProperty(exports2, "tlsPolicy", { enumerable: true, get: function() { - return tlsPolicy_js_1.tlsPolicy; - } }); - Object.defineProperty(exports2, "tlsPolicyName", { enumerable: true, get: function() { - return tlsPolicy_js_1.tlsPolicyName; - } }); - var formDataPolicy_js_1 = require_formDataPolicy2(); - Object.defineProperty(exports2, "formDataPolicy", { enumerable: true, get: function() { - return formDataPolicy_js_1.formDataPolicy; - } }); - Object.defineProperty(exports2, "formDataPolicyName", { enumerable: true, get: function() { - return formDataPolicy_js_1.formDataPolicyName; - } }); - var bearerTokenAuthenticationPolicy_js_1 = require_bearerTokenAuthenticationPolicy(); - Object.defineProperty(exports2, "bearerTokenAuthenticationPolicy", { enumerable: true, get: function() { - return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicy; - } }); - Object.defineProperty(exports2, "bearerTokenAuthenticationPolicyName", { enumerable: true, get: function() { - return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicyName; - } }); - var ndJsonPolicy_js_1 = require_ndJsonPolicy(); - Object.defineProperty(exports2, "ndJsonPolicy", { enumerable: true, get: function() { - return ndJsonPolicy_js_1.ndJsonPolicy; - } }); - Object.defineProperty(exports2, "ndJsonPolicyName", { enumerable: true, get: function() { - return ndJsonPolicy_js_1.ndJsonPolicyName; - } }); - var auxiliaryAuthenticationHeaderPolicy_js_1 = require_auxiliaryAuthenticationHeaderPolicy(); - Object.defineProperty(exports2, "auxiliaryAuthenticationHeaderPolicy", { enumerable: true, get: function() { - return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicy; - } }); - Object.defineProperty(exports2, "auxiliaryAuthenticationHeaderPolicyName", { enumerable: true, get: function() { - return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicyName; - } }); - var agentPolicy_js_1 = require_agentPolicy2(); - Object.defineProperty(exports2, "agentPolicy", { enumerable: true, get: function() { - return agentPolicy_js_1.agentPolicy; - } }); - Object.defineProperty(exports2, "agentPolicyName", { enumerable: true, get: function() { - return agentPolicy_js_1.agentPolicyName; - } }); - var file_js_1 = require_file2(); - Object.defineProperty(exports2, "createFile", { enumerable: true, get: function() { - return file_js_1.createFile; - } }); - Object.defineProperty(exports2, "createFileFromStream", { enumerable: true, get: function() { - return file_js_1.createFileFromStream; - } }); + "node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var src_exports = {}; + __export2(src_exports, { + RestError: () => import_restError.RestError, + agentPolicy: () => import_agentPolicy.agentPolicy, + agentPolicyName: () => import_agentPolicy.agentPolicyName, + auxiliaryAuthenticationHeaderPolicy: () => import_auxiliaryAuthenticationHeaderPolicy.auxiliaryAuthenticationHeaderPolicy, + auxiliaryAuthenticationHeaderPolicyName: () => import_auxiliaryAuthenticationHeaderPolicy.auxiliaryAuthenticationHeaderPolicyName, + bearerTokenAuthenticationPolicy: () => import_bearerTokenAuthenticationPolicy.bearerTokenAuthenticationPolicy, + bearerTokenAuthenticationPolicyName: () => import_bearerTokenAuthenticationPolicy.bearerTokenAuthenticationPolicyName, + createDefaultHttpClient: () => import_defaultHttpClient.createDefaultHttpClient, + createEmptyPipeline: () => import_pipeline.createEmptyPipeline, + createFile: () => import_file7.createFile, + createFileFromStream: () => import_file7.createFileFromStream, + createHttpHeaders: () => import_httpHeaders.createHttpHeaders, + createPipelineFromOptions: () => import_createPipelineFromOptions.createPipelineFromOptions, + createPipelineRequest: () => import_pipelineRequest.createPipelineRequest, + decompressResponsePolicy: () => import_decompressResponsePolicy.decompressResponsePolicy, + decompressResponsePolicyName: () => import_decompressResponsePolicy.decompressResponsePolicyName, + defaultRetryPolicy: () => import_defaultRetryPolicy.defaultRetryPolicy, + exponentialRetryPolicy: () => import_exponentialRetryPolicy.exponentialRetryPolicy, + exponentialRetryPolicyName: () => import_exponentialRetryPolicy.exponentialRetryPolicyName, + formDataPolicy: () => import_formDataPolicy.formDataPolicy, + formDataPolicyName: () => import_formDataPolicy.formDataPolicyName, + getDefaultProxySettings: () => import_proxyPolicy.getDefaultProxySettings, + isRestError: () => import_restError.isRestError, + logPolicy: () => import_logPolicy.logPolicy, + logPolicyName: () => import_logPolicy.logPolicyName, + multipartPolicy: () => import_multipartPolicy.multipartPolicy, + multipartPolicyName: () => import_multipartPolicy.multipartPolicyName, + ndJsonPolicy: () => import_ndJsonPolicy.ndJsonPolicy, + ndJsonPolicyName: () => import_ndJsonPolicy.ndJsonPolicyName, + proxyPolicy: () => import_proxyPolicy.proxyPolicy, + proxyPolicyName: () => import_proxyPolicy.proxyPolicyName, + redirectPolicy: () => import_redirectPolicy.redirectPolicy, + redirectPolicyName: () => import_redirectPolicy.redirectPolicyName, + retryPolicy: () => import_retryPolicy.retryPolicy, + setClientRequestIdPolicy: () => import_setClientRequestIdPolicy.setClientRequestIdPolicy, + setClientRequestIdPolicyName: () => import_setClientRequestIdPolicy.setClientRequestIdPolicyName, + systemErrorRetryPolicy: () => import_systemErrorRetryPolicy.systemErrorRetryPolicy, + systemErrorRetryPolicyName: () => import_systemErrorRetryPolicy.systemErrorRetryPolicyName, + throttlingRetryPolicy: () => import_throttlingRetryPolicy.throttlingRetryPolicy, + throttlingRetryPolicyName: () => import_throttlingRetryPolicy.throttlingRetryPolicyName, + tlsPolicy: () => import_tlsPolicy.tlsPolicy, + tlsPolicyName: () => import_tlsPolicy.tlsPolicyName, + tracingPolicy: () => import_tracingPolicy.tracingPolicy, + tracingPolicyName: () => import_tracingPolicy.tracingPolicyName, + userAgentPolicy: () => import_userAgentPolicy.userAgentPolicy, + userAgentPolicyName: () => import_userAgentPolicy.userAgentPolicyName + }); + module2.exports = __toCommonJS2(src_exports); + var import_pipeline = require_pipeline2(); + var import_createPipelineFromOptions = require_createPipelineFromOptions2(); + var import_defaultHttpClient = require_defaultHttpClient2(); + var import_httpHeaders = require_httpHeaders2(); + var import_pipelineRequest = require_pipelineRequest2(); + var import_restError = require_restError3(); + var import_decompressResponsePolicy = require_decompressResponsePolicy2(); + var import_exponentialRetryPolicy = require_exponentialRetryPolicy2(); + var import_setClientRequestIdPolicy = require_setClientRequestIdPolicy(); + var import_logPolicy = require_logPolicy2(); + var import_multipartPolicy = require_multipartPolicy2(); + var import_proxyPolicy = require_proxyPolicy2(); + var import_redirectPolicy = require_redirectPolicy2(); + var import_systemErrorRetryPolicy = require_systemErrorRetryPolicy2(); + var import_throttlingRetryPolicy = require_throttlingRetryPolicy2(); + var import_retryPolicy = require_retryPolicy2(); + var import_tracingPolicy = require_tracingPolicy(); + var import_defaultRetryPolicy = require_defaultRetryPolicy2(); + var import_userAgentPolicy = require_userAgentPolicy2(); + var import_tlsPolicy = require_tlsPolicy2(); + var import_formDataPolicy = require_formDataPolicy2(); + var import_bearerTokenAuthenticationPolicy = require_bearerTokenAuthenticationPolicy(); + var import_ndJsonPolicy = require_ndJsonPolicy(); + var import_auxiliaryAuthenticationHeaderPolicy = require_auxiliaryAuthenticationHeaderPolicy(); + var import_agentPolicy = require_agentPolicy2(); + var import_file7 = require_file(); } }); @@ -42173,24 +52018,43 @@ var require_commonjs7 = __commonJS({ // node_modules/@azure/core-http-compat/dist/commonjs/policies/disableKeepAlivePolicy.js var require_disableKeepAlivePolicy = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/policies/disableKeepAlivePolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.disableKeepAlivePolicyName = void 0; - exports2.createDisableKeepAlivePolicy = createDisableKeepAlivePolicy; - exports2.pipelineContainsDisableKeepAlivePolicy = pipelineContainsDisableKeepAlivePolicy; - exports2.disableKeepAlivePolicyName = "DisableKeepAlivePolicy"; + "node_modules/@azure/core-http-compat/dist/commonjs/policies/disableKeepAlivePolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var disableKeepAlivePolicy_exports = {}; + __export2(disableKeepAlivePolicy_exports, { + createDisableKeepAlivePolicy: () => createDisableKeepAlivePolicy, + disableKeepAlivePolicyName: () => disableKeepAlivePolicyName2, + pipelineContainsDisableKeepAlivePolicy: () => pipelineContainsDisableKeepAlivePolicy + }); + module2.exports = __toCommonJS2(disableKeepAlivePolicy_exports); + var disableKeepAlivePolicyName2 = "DisableKeepAlivePolicy"; function createDisableKeepAlivePolicy() { return { - name: exports2.disableKeepAlivePolicyName, - async sendRequest(request3, next) { + name: disableKeepAlivePolicyName2, + sendRequest(request3, next) { request3.disableKeepAlive = true; return next(request3); } }; } function pipelineContainsDisableKeepAlivePolicy(pipeline2) { - return pipeline2.getOrderedPolicies().some((policy) => policy.name === exports2.disableKeepAlivePolicyName); + return pipeline2.getOrderedPolicies().some((policy) => policy.name === disableKeepAlivePolicyName2); } } }); @@ -42204,18 +52068,18 @@ var require_base64 = __commonJS({ exports2.encodeByteArray = encodeByteArray; exports2.decodeString = decodeString; exports2.decodeStringToString = decodeStringToString; + var core_util_1 = require_commonjs4(); function encodeString(value) { - return Buffer.from(value).toString("base64"); + return (0, core_util_1.uint8ArrayToString)((0, core_util_1.stringToUint8Array)(value, "utf-8"), "base64"); } function encodeByteArray(value) { - const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer); - return bufferValue.toString("base64"); + return (0, core_util_1.uint8ArrayToString)(value, "base64"); } function decodeString(value) { - return Buffer.from(value, "base64"); + return (0, core_util_1.stringToUint8Array)(value, "base64"); } function decodeStringToString(value) { - return Buffer.from(value, "base64").toString(); + return (0, core_util_1.uint8ArrayToString)((0, core_util_1.stringToUint8Array)(value, "base64"), "utf-8"); } } }); @@ -42683,7 +52547,7 @@ var require_serializer = __commonJS({ } let elementType = mapper.type.element; if (!elementType || typeof elementType !== "object") { - throw new Error(`element" metadata for an Array must be defined in the mapper and it must of type "object" in ${objectName}.`); + throw new Error(`"element" metadata for an Array must be defined in the mapper and it must be of type "object" in ${objectName}.`); } if (elementType.type.name === "Composite" && elementType.type.className) { elementType = serializer.modelMappers[elementType.type.className] ?? elementType; @@ -42819,10 +52683,15 @@ var require_serializer = __commonJS({ const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); if (additionalPropertiesMapper) { const propNames = Object.keys(modelProps); - for (const clientPropName in object2) { + for (const clientPropName of Object.keys(object2)) { const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); if (isAdditionalProperty) { - payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object2[clientPropName], objectName + '["' + clientPropName + '"]', options); + Object.defineProperty(payload, clientPropName, { + value: serializer.serialize(additionalPropertiesMapper, object2[clientPropName], objectName + '["' + clientPropName + '"]', options), + enumerable: true, + configurable: true, + writable: true + }); } } } @@ -42859,7 +52728,7 @@ var require_serializer = __commonJS({ mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); } const modelProps = resolveModelProperties(serializer, mapper, objectName); - let instance = {}; + let instance8 = {}; const handledPropertyNames = []; for (const key of Object.keys(modelProps)) { const propertyMapper = modelProps[key]; @@ -42879,26 +52748,31 @@ var require_serializer = __commonJS({ } handledPropertyNames.push(headerKey); } - instance[key] = dictionary; + instance8[key] = dictionary; } else if (serializer.isXML) { if (propertyMapper.xmlIsAttribute && responseBody[interfaces_js_1.XML_ATTRKEY]) { - instance[key] = serializer.deserialize(propertyMapper, responseBody[interfaces_js_1.XML_ATTRKEY][xmlName], propertyObjectName, options); + instance8[key] = serializer.deserialize(propertyMapper, responseBody[interfaces_js_1.XML_ATTRKEY][xmlName], propertyObjectName, options); } else if (propertyMapper.xmlIsMsText) { if (responseBody[xmlCharKey] !== void 0) { - instance[key] = responseBody[xmlCharKey]; + instance8[key] = responseBody[xmlCharKey]; } else if (typeof responseBody === "string") { - instance[key] = responseBody; + instance8[key] = responseBody; } } else { const propertyName = xmlElementName || xmlName || serializedName; if (propertyMapper.xmlIsWrapped) { const wrapped = responseBody[xmlName]; const elementList = wrapped?.[xmlElementName] ?? []; - instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); + Object.defineProperty(instance8, key, { + value: serializer.deserialize(propertyMapper, elementList, propertyObjectName, options), + enumerable: true, + configurable: true, + writable: true + }); handledPropertyNames.push(xmlName); } else { const property = responseBody[propertyName]; - instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); + instance8[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); handledPropertyNames.push(propertyName); } } @@ -42924,22 +52798,22 @@ var require_serializer = __commonJS({ if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { propertyInstance = responseBody[key]; const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); - for (const [k, v] of Object.entries(instance)) { + for (const [k, v] of Object.entries(instance8)) { if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) { arrayInstance[k] = v; } } - instance = arrayInstance; + instance8 = arrayInstance; } else if (propertyInstance !== void 0 || propertyMapper.defaultValue !== void 0) { serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); - instance[key] = serializedValue; + instance8[key] = serializedValue; } } } const additionalPropertiesMapper = mapper.type.additionalProperties; if (additionalPropertiesMapper) { const isAdditionalProperty = (responsePropName) => { - for (const clientPropName in modelProps) { + for (const clientPropName of Object.keys(modelProps)) { const paths = splitSerializeName(modelProps[clientPropName].serializedName); if (paths[0] === responsePropName) { return false; @@ -42947,19 +52821,30 @@ var require_serializer = __commonJS({ } return true; }; - for (const responsePropName in responseBody) { + for (const responsePropName of Object.keys(responseBody)) { if (isAdditionalProperty(responsePropName)) { - instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); + const deserializedValue = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); + Object.defineProperty(instance8, responsePropName, { + value: deserializedValue, + enumerable: true, + configurable: true, + writable: true + }); } } } else if (responseBody && !options.ignoreUnknownProperties) { for (const key of Object.keys(responseBody)) { - if (instance[key] === void 0 && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key, options)) { - instance[key] = responseBody[key]; + if (instance8[key] === void 0 && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key, options)) { + Object.defineProperty(instance8, key, { + value: responseBody[key], + enumerable: true, + configurable: true, + writable: true + }); } } } - return instance; + return instance8; } function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { const value = mapper.type.value; @@ -42978,7 +52863,7 @@ var require_serializer = __commonJS({ function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { let element = mapper.type.element; if (!element || typeof element !== "object") { - throw new Error(`element" metadata for an Array must be defined in the mapper and it must of type "object" in ${objectName}`); + throw new Error(`"element" metadata for an Array must be defined in the mapper and it must be of type "object" in ${objectName}`); } if (responseBody) { if (!Array.isArray(responseBody)) { @@ -43059,9 +52944,9 @@ var require_serializer = __commonJS({ } }); -// node_modules/@azure/core-client/dist/commonjs/state.js -var require_state2 = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/state.js"(exports2) { +// node_modules/@azure/core-client/dist/commonjs/state-cjs.js +var require_state_cjs = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/state-cjs.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.state = void 0; @@ -43078,7 +52963,7 @@ var require_operationHelpers = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getOperationArgumentValueFromParameter = getOperationArgumentValueFromParameter; exports2.getOperationRequestInfo = getOperationRequestInfo; - var state_js_1 = require_state2(); + var state_1 = require_state_cjs(); function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) { let parameterPath = parameter.parameterPath; const parameterMapper = parameter.mapper; @@ -43106,9 +52991,8 @@ var require_operationHelpers = __commonJS({ if (parameterMapper.required) { value = {}; } - for (const propertyName in parameterPath) { + for (const [propertyName, propertyPath] of Object.entries(parameterPath)) { const propertyMapper = parameterMapper.type.modelProperties[propertyName]; - const propertyPath = parameterPath[propertyName]; const propertyValue = getOperationArgumentValueFromParameter(operationArguments, { parameterPath: propertyPath, mapper: propertyMapper @@ -43117,7 +53001,12 @@ var require_operationHelpers = __commonJS({ if (!value) { value = {}; } - value[propertyName] = propertyValue; + Object.defineProperty(value, propertyName, { + value: propertyValue, + enumerable: true, + configurable: true, + writable: true + }); } } } @@ -43148,10 +53037,10 @@ var require_operationHelpers = __commonJS({ if (hasOriginalRequest(request3)) { return getOperationRequestInfo(request3[originalRequestSymbol]); } - let info8 = state_js_1.state.operationRequestMap.get(request3); + let info8 = state_1.state.operationRequestMap.get(request3); if (!info8) { info8 = {}; - state_js_1.state.operationRequestMap.set(request3, info8); + state_1.state.operationRequestMap.set(request3, info8); } return info8; } @@ -43221,7 +53110,7 @@ var require_deserializationPolicy = __commonJS({ return result; } async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) { - const parsedResponse = await parse3(jsonContentTypes, xmlContentTypes, response, options, parseXML); + const parsedResponse = await parse4(jsonContentTypes, xmlContentTypes, response, options, parseXML); if (!shouldDeserializeResponse(parsedResponse)) { return parsedResponse; } @@ -43322,7 +53211,7 @@ var require_deserializationPolicy = __commonJS({ } return { error: error3, shouldReturnResponse: false }; } - async function parse3(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) { + async function parse4(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) { if (!operationResponse.request.streamResponseStatusCodes?.has(operationResponse.status) && operationResponse.bodyAsText) { const text = operationResponse.bodyAsText; const contentType = operationResponse.headers.get("Content-Type") || ""; @@ -43366,8 +53255,7 @@ var require_interfaceHelpers = __commonJS({ var serializer_js_1 = require_serializer(); function getStreamingResponseStatusCodes(operationSpec) { const result = /* @__PURE__ */ new Set(); - for (const statusCode in operationSpec.responses) { - const operationResponse = operationSpec.responses[statusCode]; + for (const [statusCode, operationResponse] of Object.entries(operationSpec.responses)) { if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Stream) { result.add(Number(statusCode)); } @@ -43407,7 +53295,7 @@ var require_serializationPolicy = __commonJS({ const stringifyXML = options.stringifyXML; return { name: exports2.serializationPolicyName, - async sendRequest(request3, next) { + sendRequest(request3, next) { const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request3); const operationSpec = operationInfo?.operationSpec; const operationArguments = operationInfo?.operationArguments; @@ -43483,7 +53371,7 @@ var require_serializationPolicy = __commonJS({ } } } catch (error3) { - throw new Error(`Error "${error3.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, void 0, " ")}.`); + throw new Error(`Error "${error3.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, void 0, " ")}.`, { cause: error3 }); } } else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) { request3.formData = {}; @@ -43550,10 +53438,10 @@ var require_httpClientCache = __commonJS({ "node_modules/@azure/core-client/dist/commonjs/httpClientCache.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getCachedDefaultHttpClient = getCachedDefaultHttpClient; + exports2.getCachedDefaultHttpClient = getCachedDefaultHttpClient2; var core_rest_pipeline_1 = require_commonjs6(); var cachedHttpClient; - function getCachedDefaultHttpClient() { + function getCachedDefaultHttpClient2() { if (!cachedHttpClient) { cachedHttpClient = (0, core_rest_pipeline_1.createDefaultHttpClient)(); } @@ -43646,7 +53534,7 @@ var require_urlHelpers2 = __commonJS({ } else { newPath = newPath + pathToAppend; } - parsedUrl.pathname = newPath; + Object.assign(parsedUrl, { pathname: newPath }); return parsedUrl.toString(); } function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) { @@ -43837,7 +53725,7 @@ var require_serviceClient = __commonJS({ /** * Send the provided httpRequest. */ - async sendRequest(request3) { + sendRequest(request3) { return this.pipeline.sendRequest(this._httpClient, request3); } /** @@ -43935,7 +53823,7 @@ var require_serviceClient = __commonJS({ if (options.baseUri) { return `${options.baseUri}/.default`; } - if (options.credential && !options.credentialScopes) { + if (options.credential) { throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`); } return void 0; @@ -43962,16 +53850,16 @@ var require_authorizeRequestOnClaimChallenge = __commonJS({ } async function authorizeRequestOnClaimChallenge(onChallengeOptions) { const { scopes, response } = onChallengeOptions; - const logger = onChallengeOptions.logger || log_js_1.logger; + const logger2 = onChallengeOptions.logger || log_js_1.logger; const challenge = response.headers.get("WWW-Authenticate"); if (!challenge) { - logger.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`); + logger2.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`); return false; } const challenges = parseCAEChallenge(challenge) || []; const parsedChallenge = challenges.find((x) => x.claims); if (!parsedChallenge) { - logger.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`); + logger2.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`); return false; } const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, { @@ -44044,8 +53932,7 @@ var require_authorizeRequestOnTenantChallenge = __commonJS({ return challengeOptions.scopes; } const challengeScopes = new URL(challengeInfo.resource_id); - challengeScopes.pathname = Constants.DefaultScope; - let scope = challengeScopes.toString(); + let scope = new URL(Constants.DefaultScope, challengeScopes.origin).toString(); if (scope === "https://disk.azure.com/.default") { scope = "https://disk.azure.com//.default"; } @@ -44130,26 +54017,60 @@ var require_commonjs8 = __commonJS({ }); // node_modules/@azure/core-http-compat/dist/commonjs/util.js -var require_util9 = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/util.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HttpHeaders = void 0; - exports2.toPipelineRequest = toPipelineRequest; - exports2.toWebResourceLike = toWebResourceLike; - exports2.toHttpHeadersLike = toHttpHeadersLike; - var core_rest_pipeline_1 = require_commonjs6(); +var require_util7 = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/util.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var util_exports2 = {}; + __export2(util_exports2, { + toHttpHeadersLike: () => toHttpHeadersLike2, + toPipelineRequest: () => toPipelineRequest, + toWebResourceLike: () => toWebResourceLike + }); + module2.exports = __toCommonJS2(util_exports2); + var import_core_rest_pipeline = require_commonjs6(); var originalRequestSymbol = /* @__PURE__ */ Symbol("Original PipelineRequest"); var originalClientRequestSymbol = /* @__PURE__ */ Symbol.for("@azure/core-client original request"); + var passThroughProps = /* @__PURE__ */ new Set([ + "url", + "method", + "withCredentials", + "timeout", + "requestId", + "abortSignal", + "body", + "formData", + "onDownloadProgress", + "onUploadProgress", + "proxySettings", + "streamResponseStatusCodes", + "agent", + "requestOverrides" + ]); function toPipelineRequest(webResource, options = {}) { const compatWebResource = webResource; const request3 = compatWebResource[originalRequestSymbol]; - const headers = (0, core_rest_pipeline_1.createHttpHeaders)(webResource.headers.toJson({ preserveCase: true })); + const headers = (0, import_core_rest_pipeline.createHttpHeaders)(webResource.headers.toJson({ preserveCase: true })); if (request3) { request3.headers = headers; return request3; } else { - const newRequest = (0, core_rest_pipeline_1.createPipelineRequest)({ + const newRequest = (0, import_core_rest_pipeline.createPipelineRequest)({ url: webResource.url, method: webResource.method, headers, @@ -44178,7 +54099,7 @@ var require_util9 = __commonJS({ const webResource = { url: request3.url, method: request3.method, - headers: toHttpHeadersLike(request3.headers), + headers: toHttpHeadersLike2(request3.headers), withCredentials: request3.withCredentials, timeout: request3.timeout, requestId: request3.headers.get("x-ms-client-request-id") || request3.requestId, @@ -44220,23 +54141,7 @@ var require_util9 = __commonJS({ if (prop === "keepAlive") { request3.disableKeepAlive = !value; } - const passThroughProps = [ - "url", - "method", - "withCredentials", - "timeout", - "requestId", - "abortSignal", - "body", - "formData", - "onDownloadProgress", - "onUploadProgress", - "proxySettings", - "streamResponseStatusCodes", - "agent", - "requestOverrides" - ]; - if (typeof prop === "string" && passThroughProps.includes(prop)) { + if (typeof prop === "string" && passThroughProps.has(prop)) { request3[prop] = value; } return Reflect.set(target, prop, value, receiver); @@ -44246,7 +54151,7 @@ var require_util9 = __commonJS({ return webResource; } } - function toHttpHeadersLike(headers) { + function toHttpHeadersLike2(headers) { return new HttpHeaders(headers.toJSON({ preserveCase: true })); } function getHeaderKey(headerName) { @@ -44373,23 +54278,41 @@ var require_util9 = __commonJS({ return new _HttpHeaders(resultPreservingCasing); } }; - exports2.HttpHeaders = HttpHeaders; } }); // node_modules/@azure/core-http-compat/dist/commonjs/response.js var require_response2 = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/response.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.toCompatResponse = toCompatResponse; - exports2.toPipelineResponse = toPipelineResponse; - var core_rest_pipeline_1 = require_commonjs6(); - var util_js_1 = require_util9(); + "node_modules/@azure/core-http-compat/dist/commonjs/response.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var response_exports = {}; + __export2(response_exports, { + toCompatResponse: () => toCompatResponse2, + toPipelineResponse: () => toPipelineResponse + }); + module2.exports = __toCommonJS2(response_exports); + var import_core_rest_pipeline = require_commonjs6(); + var import_util61 = require_util7(); var originalResponse = /* @__PURE__ */ Symbol("Original FullOperationResponse"); - function toCompatResponse(response, options) { - let request3 = (0, util_js_1.toWebResourceLike)(response.request); - let headers = (0, util_js_1.toHttpHeadersLike)(response.headers); + function toCompatResponse2(response, options) { + let request3 = (0, import_util61.toWebResourceLike)(response.request); + let headers = (0, import_util61.toHttpHeadersLike)(response.headers); if (options?.createProxy) { return new Proxy(response, { get(target, prop, receiver) { @@ -44422,7 +54345,7 @@ var require_response2 = __commonJS({ function toPipelineResponse(compatResponse) { const extendedCompatResponse = compatResponse; const response = extendedCompatResponse[originalResponse]; - const headers = (0, core_rest_pipeline_1.createHttpHeaders)(compatResponse.headers.toJson({ preserveCase: true })); + const headers = (0, import_core_rest_pipeline.createHttpHeaders)(compatResponse.headers.toJson({ preserveCase: true })); if (response) { response.headers = headers; return response; @@ -44430,7 +54353,7 @@ var require_response2 = __commonJS({ return { ...compatResponse, headers, - request: (0, util_js_1.toPipelineRequest)(compatResponse.request) + request: (0, import_util61.toPipelineRequest)(compatResponse.request) }; } } @@ -44439,23 +54362,42 @@ var require_response2 = __commonJS({ // node_modules/@azure/core-http-compat/dist/commonjs/extendedClient.js var require_extendedClient = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/extendedClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ExtendedServiceClient = void 0; - var disableKeepAlivePolicy_js_1 = require_disableKeepAlivePolicy(); - var core_rest_pipeline_1 = require_commonjs6(); - var core_client_1 = require_commonjs8(); - var response_js_1 = require_response2(); - var ExtendedServiceClient = class extends core_client_1.ServiceClient { + "node_modules/@azure/core-http-compat/dist/commonjs/extendedClient.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var extendedClient_exports = {}; + __export2(extendedClient_exports, { + ExtendedServiceClient: () => ExtendedServiceClient2 + }); + module2.exports = __toCommonJS2(extendedClient_exports); + var import_disableKeepAlivePolicy = require_disableKeepAlivePolicy(); + var import_core_rest_pipeline = require_commonjs6(); + var import_core_client = require_commonjs8(); + var import_response = require_response2(); + var ExtendedServiceClient2 = class extends import_core_client.ServiceClient { constructor(options) { super(options); - if (options.keepAliveOptions?.enable === false && !(0, disableKeepAlivePolicy_js_1.pipelineContainsDisableKeepAlivePolicy)(this.pipeline)) { - this.pipeline.addPolicy((0, disableKeepAlivePolicy_js_1.createDisableKeepAlivePolicy)()); + if (options.keepAliveOptions?.enable === false && !(0, import_disableKeepAlivePolicy.pipelineContainsDisableKeepAlivePolicy)(this.pipeline)) { + this.pipeline.addPolicy((0, import_disableKeepAlivePolicy.createDisableKeepAlivePolicy)()); } if (options.redirectOptions?.handleRedirects === false) { this.pipeline.removePolicy({ - name: core_rest_pipeline_1.redirectPolicyName + name: import_core_rest_pipeline.redirectPolicyName }); } } @@ -44482,32 +54424,51 @@ var require_extendedClient = __commonJS({ const result = await super.sendOperationRequest(operationArguments, operationSpec); if (lastResponse) { Object.defineProperty(result, "_response", { - value: (0, response_js_1.toCompatResponse)(lastResponse) + value: (0, import_response.toCompatResponse)(lastResponse) }); } return result; } }; - exports2.ExtendedServiceClient = ExtendedServiceClient; } }); // node_modules/@azure/core-http-compat/dist/commonjs/policies/requestPolicyFactoryPolicy.js var require_requestPolicyFactoryPolicy = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/policies/requestPolicyFactoryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.requestPolicyFactoryPolicyName = exports2.HttpPipelineLogLevel = void 0; - exports2.createRequestPolicyFactoryPolicy = createRequestPolicyFactoryPolicy; - var util_js_1 = require_util9(); - var response_js_1 = require_response2(); - var HttpPipelineLogLevel; - (function(HttpPipelineLogLevel2) { - HttpPipelineLogLevel2[HttpPipelineLogLevel2["ERROR"] = 1] = "ERROR"; - HttpPipelineLogLevel2[HttpPipelineLogLevel2["INFO"] = 3] = "INFO"; - HttpPipelineLogLevel2[HttpPipelineLogLevel2["OFF"] = 0] = "OFF"; - HttpPipelineLogLevel2[HttpPipelineLogLevel2["WARNING"] = 2] = "WARNING"; - })(HttpPipelineLogLevel || (exports2.HttpPipelineLogLevel = HttpPipelineLogLevel = {})); + "node_modules/@azure/core-http-compat/dist/commonjs/policies/requestPolicyFactoryPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var requestPolicyFactoryPolicy_exports = {}; + __export2(requestPolicyFactoryPolicy_exports, { + HttpPipelineLogLevel: () => HttpPipelineLogLevel2, + createRequestPolicyFactoryPolicy: () => createRequestPolicyFactoryPolicy2, + requestPolicyFactoryPolicyName: () => requestPolicyFactoryPolicyName2 + }); + module2.exports = __toCommonJS2(requestPolicyFactoryPolicy_exports); + var import_util61 = require_util7(); + var import_response = require_response2(); + var HttpPipelineLogLevel2 = /* @__PURE__ */ ((HttpPipelineLogLevel22) => { + HttpPipelineLogLevel22[HttpPipelineLogLevel22["ERROR"] = 1] = "ERROR"; + HttpPipelineLogLevel22[HttpPipelineLogLevel22["INFO"] = 3] = "INFO"; + HttpPipelineLogLevel22[HttpPipelineLogLevel22["OFF"] = 0] = "OFF"; + HttpPipelineLogLevel22[HttpPipelineLogLevel22["WARNING"] = 2] = "WARNING"; + return HttpPipelineLogLevel22; + })(HttpPipelineLogLevel2 || {}); var mockRequestPolicyOptions = { log(_logLevel, _message) { }, @@ -44515,24 +54476,24 @@ var require_requestPolicyFactoryPolicy = __commonJS({ return false; } }; - exports2.requestPolicyFactoryPolicyName = "RequestPolicyFactoryPolicy"; - function createRequestPolicyFactoryPolicy(factories) { + var requestPolicyFactoryPolicyName2 = "RequestPolicyFactoryPolicy"; + function createRequestPolicyFactoryPolicy2(factories) { const orderedFactories = factories.slice().reverse(); return { - name: exports2.requestPolicyFactoryPolicyName, + name: requestPolicyFactoryPolicyName2, async sendRequest(request3, next) { let httpPipeline = { async sendRequest(httpRequest) { - const response2 = await next((0, util_js_1.toPipelineRequest)(httpRequest)); - return (0, response_js_1.toCompatResponse)(response2, { createProxy: true }); + const response2 = await next((0, import_util61.toPipelineRequest)(httpRequest)); + return (0, import_response.toCompatResponse)(response2, { createProxy: true }); } }; for (const factory of orderedFactories) { httpPipeline = factory.create(httpPipeline, mockRequestPolicyOptions); } - const webResourceLike = (0, util_js_1.toWebResourceLike)(request3, { createProxy: true }); + const webResourceLike = (0, import_util61.toWebResourceLike)(request3, { createProxy: true }); const response = await httpPipeline.sendRequest(webResourceLike); - return (0, response_js_1.toPipelineResponse)(response); + return (0, import_response.toPipelineResponse)(response); } }; } @@ -44541,17 +54502,38 @@ var require_requestPolicyFactoryPolicy = __commonJS({ // node_modules/@azure/core-http-compat/dist/commonjs/httpClientAdapter.js var require_httpClientAdapter = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/httpClientAdapter.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.convertHttpClient = convertHttpClient; - var response_js_1 = require_response2(); - var util_js_1 = require_util9(); - function convertHttpClient(requestPolicyClient) { + "node_modules/@azure/core-http-compat/dist/commonjs/httpClientAdapter.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var httpClientAdapter_exports = {}; + __export2(httpClientAdapter_exports, { + convertHttpClient: () => convertHttpClient2 + }); + module2.exports = __toCommonJS2(httpClientAdapter_exports); + var import_response = require_response2(); + var import_util61 = require_util7(); + function convertHttpClient2(requestPolicyClient) { return { sendRequest: async (request3) => { - const response = await requestPolicyClient.sendRequest((0, util_js_1.toWebResourceLike)(request3, { createProxy: true })); - return (0, response_js_1.toPipelineResponse)(response); + const response = await requestPolicyClient.sendRequest( + (0, import_util61.toWebResourceLike)(request3, { createProxy: true }) + ); + return (0, import_response.toPipelineResponse)(response); } }; } @@ -44560,36 +54542,42 @@ var require_httpClientAdapter = __commonJS({ // node_modules/@azure/core-http-compat/dist/commonjs/index.js var require_commonjs9 = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.toHttpHeadersLike = exports2.convertHttpClient = exports2.disableKeepAlivePolicyName = exports2.HttpPipelineLogLevel = exports2.createRequestPolicyFactoryPolicy = exports2.requestPolicyFactoryPolicyName = exports2.ExtendedServiceClient = void 0; - var extendedClient_js_1 = require_extendedClient(); - Object.defineProperty(exports2, "ExtendedServiceClient", { enumerable: true, get: function() { - return extendedClient_js_1.ExtendedServiceClient; - } }); - var requestPolicyFactoryPolicy_js_1 = require_requestPolicyFactoryPolicy(); - Object.defineProperty(exports2, "requestPolicyFactoryPolicyName", { enumerable: true, get: function() { - return requestPolicyFactoryPolicy_js_1.requestPolicyFactoryPolicyName; - } }); - Object.defineProperty(exports2, "createRequestPolicyFactoryPolicy", { enumerable: true, get: function() { - return requestPolicyFactoryPolicy_js_1.createRequestPolicyFactoryPolicy; - } }); - Object.defineProperty(exports2, "HttpPipelineLogLevel", { enumerable: true, get: function() { - return requestPolicyFactoryPolicy_js_1.HttpPipelineLogLevel; - } }); - var disableKeepAlivePolicy_js_1 = require_disableKeepAlivePolicy(); - Object.defineProperty(exports2, "disableKeepAlivePolicyName", { enumerable: true, get: function() { - return disableKeepAlivePolicy_js_1.disableKeepAlivePolicyName; - } }); - var httpClientAdapter_js_1 = require_httpClientAdapter(); - Object.defineProperty(exports2, "convertHttpClient", { enumerable: true, get: function() { - return httpClientAdapter_js_1.convertHttpClient; - } }); - var util_js_1 = require_util9(); - Object.defineProperty(exports2, "toHttpHeadersLike", { enumerable: true, get: function() { - return util_js_1.toHttpHeadersLike; - } }); + "node_modules/@azure/core-http-compat/dist/commonjs/index.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var src_exports = {}; + __export2(src_exports, { + ExtendedServiceClient: () => import_extendedClient.ExtendedServiceClient, + HttpPipelineLogLevel: () => import_requestPolicyFactoryPolicy.HttpPipelineLogLevel, + convertHttpClient: () => import_httpClientAdapter.convertHttpClient, + createRequestPolicyFactoryPolicy: () => import_requestPolicyFactoryPolicy.createRequestPolicyFactoryPolicy, + disableKeepAlivePolicyName: () => import_disableKeepAlivePolicy.disableKeepAlivePolicyName, + requestPolicyFactoryPolicyName: () => import_requestPolicyFactoryPolicy.requestPolicyFactoryPolicyName, + toCompatResponse: () => import_response.toCompatResponse, + toHttpHeadersLike: () => import_util61.toHttpHeadersLike + }); + module2.exports = __toCommonJS2(src_exports); + var import_extendedClient = require_extendedClient(); + var import_response = require_response2(); + var import_requestPolicyFactoryPolicy = require_requestPolicyFactoryPolicy(); + var import_disableKeepAlivePolicy = require_disableKeepAlivePolicy(); + var import_httpClientAdapter = require_httpClientAdapter(); + var import_util61 = require_util7(); } }); @@ -45746,7 +55734,7 @@ var require_fxp = __commonJS({ if (a2[h2]) { let t3 = vt(a2[h2], e2, n2, i2); const s3 = At(t3, e2); - if (a2[":@"] ? _t(t3, a2[":@"], i2, e2) : 1 !== Object.keys(t3).length || void 0 === t3[e2.textNodeName] || e2.alwaysCreateTextNode ? 0 === Object.keys(t3).length && (e2.alwaysCreateTextNode ? t3[e2.textNodeName] = "" : t3 = "") : t3 = t3[e2.textNodeName], void 0 !== a2[yt] && "object" == typeof t3 && null !== t3 && (t3[yt] = a2[yt]), void 0 !== r2[h2] && Object.prototype.hasOwnProperty.call(r2, h2)) Array.isArray(r2[h2]) || (r2[h2] = [r2[h2]]), r2[h2].push(t3); + if (a2[":@"] ? _t2(t3, a2[":@"], i2, e2) : 1 !== Object.keys(t3).length || void 0 === t3[e2.textNodeName] || e2.alwaysCreateTextNode ? 0 === Object.keys(t3).length && (e2.alwaysCreateTextNode ? t3[e2.textNodeName] = "" : t3 = "") : t3 = t3[e2.textNodeName], void 0 !== a2[yt] && "object" == typeof t3 && null !== t3 && (t3[yt] = a2[yt]), void 0 !== r2[h2] && Object.prototype.hasOwnProperty.call(r2, h2)) Array.isArray(r2[h2]) || (r2[h2] = [r2[h2]]), r2[h2].push(t3); else { const n3 = e2.jPath ? i2.toString() : i2; e2.isArray(h2, n3, s3) ? r2[h2] = [t3] : r2[h2] = t3; @@ -45764,7 +55752,7 @@ var require_fxp = __commonJS({ if (":@" !== n2) return n2; } } - function _t(t2, e2, n2, i2) { + function _t2(t2, e2, n2, i2) { if (e2) { const s2 = Object.keys(e2), r2 = s2.length; for (let o2 = 0; o2 < r2; o2++) { @@ -46135,17 +56123,17 @@ var require_xml = __commonJS({ var fast_xml_parser_1 = require_fxp(); var xml_common_js_1 = require_xml_common(); function getCommonOptions(options) { - var _a2; + var _a6; return { attributesGroupName: xml_common_js_1.XML_ATTRKEY, - textNodeName: (_a2 = options.xmlCharKey) !== null && _a2 !== void 0 ? _a2 : xml_common_js_1.XML_CHARKEY, + textNodeName: (_a6 = options.xmlCharKey) !== null && _a6 !== void 0 ? _a6 : xml_common_js_1.XML_CHARKEY, ignoreAttributes: false, suppressBooleanAttributes: false }; } function getSerializerOptions(options = {}) { - var _a2, _b; - return Object.assign(Object.assign({}, getCommonOptions(options)), { attributeNamePrefix: "@_", format: true, suppressEmptyNode: true, indentBy: "", rootNodeName: (_a2 = options.rootName) !== null && _a2 !== void 0 ? _a2 : "root", cdataPropName: (_b = options.cdataPropName) !== null && _b !== void 0 ? _b : "__cdata" }); + var _a6, _b2; + return Object.assign(Object.assign({}, getCommonOptions(options)), { attributeNamePrefix: "@_", format: true, suppressEmptyNode: true, indentBy: "", rootNodeName: (_a6 = options.rootName) !== null && _a6 !== void 0 ? _a6 : "root", cdataPropName: (_b2 = options.cdataPropName) !== null && _b2 !== void 0 ? _b2 : "__cdata" }); } function getParserOptions(options = {}) { return Object.assign(Object.assign({}, getCommonOptions(options)), { parseAttributeValue: false, parseTagValue: false, attributeNamePrefix: "", stopNodes: options.stopNodes, processEntities: true, trimValues: false }); @@ -46206,1142 +56194,4539 @@ var require_commonjs10 = __commonJS({ // node_modules/@azure/storage-blob/dist/commonjs/log.js var require_log5 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/log.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = void 0; - var logger_1 = require_commonjs2(); - exports2.logger = (0, logger_1.createClientLogger)("storage-blob"); - } -}); - -// node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError3 = __commonJS({ - "node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + "node_modules/@azure/storage-blob/dist/commonjs/log.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.AbortError = AbortError; - } -}); - -// node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs11 = __commonJS({ - "node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError3(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var log_exports = {}; + __export2(log_exports, { + logger: () => logger2 + }); + module2.exports = __toCommonJS2(log_exports); + var import_logger = require_commonjs2(); + var logger2 = (0, import_logger.createClientLogger)("storage-blob"); } }); -// node_modules/@azure/storage-blob/dist/commonjs/policies/RequestPolicy.js -var require_RequestPolicy = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/policies/RequestPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BaseRequestPolicy = void 0; - var BaseRequestPolicy = class { - _nextPolicy; - _options; +// node_modules/@azure/storage-common/dist/commonjs/BuffersStream.js +var require_BuffersStream = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/BuffersStream.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BuffersStream_exports = {}; + __export2(BuffersStream_exports, { + BuffersStream: () => BuffersStream + }); + module2.exports = __toCommonJS2(BuffersStream_exports); + var import_node_stream5 = require("node:stream"); + var BuffersStream = class extends import_node_stream5.Readable { /** - * The main method to implement that manipulates a request/response. + * Creates an instance of BuffersStream that will emit the data + * contained in the array of buffers. + * + * @param buffers - Array of buffers containing the data + * @param byteLength - The total length of data contained in the buffers */ - constructor(_nextPolicy, _options) { - this._nextPolicy = _nextPolicy; - this._options = _options; + constructor(buffers, byteLength, options) { + super(options); + this.buffers = buffers; + this.byteLength = byteLength; + this.byteOffsetInCurrentBuffer = 0; + this.bufferIndex = 0; + this.pushedBytesLength = 0; + let buffersLength = 0; + for (const buf of this.buffers) { + buffersLength += buf.byteLength; + } + if (buffersLength < this.byteLength) { + throw new Error("Data size shouldn't be larger than the total length of buffers."); + } } + buffers; + byteLength; /** - * Get whether or not a log with the provided log level should be logged. - * @param logLevel - The log level of the log that will be logged. - * @returns Whether or not a log with the provided log level should be logged. + * The offset of data to be read in the current buffer. */ - shouldLog(logLevel) { - return this._options.shouldLog(logLevel); - } + byteOffsetInCurrentBuffer; /** - * Attempt to log the provided message to the provided logger. If no logger was provided or if - * the log level does not meat the logger's threshold, then nothing will be logged. - * @param logLevel - The log level of this log. - * @param message - The message of this log. + * The index of buffer to be read in the array of buffers. */ - log(logLevel, message) { - this._options.log(logLevel, message); + bufferIndex; + /** + * The total length of data already read. + */ + pushedBytesLength; + /** + * Internal _read() that will be called when the stream wants to pull more data in. + * + * @param size - Optional. The size of data to be read + */ + _read(size) { + if (this.pushedBytesLength >= this.byteLength) { + this.push(null); + } + if (!size) { + size = this.readableHighWaterMark; + } + const outBuffers = []; + let i = 0; + while (i < size && this.pushedBytesLength < this.byteLength) { + const remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength; + const remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer; + const remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers); + if (remaining > size - i) { + const end = this.byteOffsetInCurrentBuffer + size - i; + outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); + this.pushedBytesLength += size - i; + this.byteOffsetInCurrentBuffer = end; + i = size; + break; + } else { + const end = this.byteOffsetInCurrentBuffer + remaining; + outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); + if (remaining === remainingCapacityInThisBuffer) { + this.byteOffsetInCurrentBuffer = 0; + this.bufferIndex++; + } else { + this.byteOffsetInCurrentBuffer = end; + } + this.pushedBytesLength += remaining; + i += remaining; + } + } + if (outBuffers.length > 1) { + this.push(Buffer.concat(outBuffers)); + } else if (outBuffers.length === 1) { + this.push(outBuffers[0]); + } } }; - exports2.BaseRequestPolicy = BaseRequestPolicy; } }); -// node_modules/@azure/storage-blob/dist/commonjs/utils/constants.js -var require_constants10 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/utils/constants.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PathStylePorts = exports2.BlobDoesNotUseCustomerSpecifiedEncryption = exports2.BlobUsesCustomerSpecifiedEncryptionMsg = exports2.StorageBlobLoggingAllowedQueryParameters = exports2.StorageBlobLoggingAllowedHeaderNames = exports2.DevelopmentConnectionString = exports2.EncryptionAlgorithmAES25 = exports2.HTTP_VERSION_1_1 = exports2.HTTP_LINE_ENDING = exports2.BATCH_MAX_PAYLOAD_IN_BYTES = exports2.BATCH_MAX_REQUEST = exports2.SIZE_1_MB = exports2.ETagAny = exports2.ETagNone = exports2.HeaderConstants = exports2.HTTPURLConnection = exports2.URLConstants = exports2.StorageOAuthScopes = exports2.REQUEST_TIMEOUT = exports2.DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = exports2.DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = exports2.DEFAULT_BLOCK_BUFFER_SIZE_BYTES = exports2.BLOCK_BLOB_MAX_BLOCKS = exports2.BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = exports2.BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = exports2.SERVICE_VERSION = exports2.SDK_VERSION = void 0; - exports2.SDK_VERSION = "12.29.1"; - exports2.SERVICE_VERSION = "2025-11-05"; - exports2.BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; - exports2.BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4e3 * 1024 * 1024; - exports2.BLOCK_BLOB_MAX_BLOCKS = 5e4; - exports2.DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; - exports2.DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; - exports2.DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5; - exports2.REQUEST_TIMEOUT = 100 * 1e3; - exports2.StorageOAuthScopes = "https://storage.azure.com/.default"; - exports2.URLConstants = { - Parameters: { - FORCE_BROWSER_NO_CACHE: "_", - SIGNATURE: "sig", - SNAPSHOT: "snapshot", - VERSIONID: "versionid", - TIMEOUT: "timeout" - } - }; - exports2.HTTPURLConnection = { - HTTP_ACCEPTED: 202, - HTTP_CONFLICT: 409, - HTTP_NOT_FOUND: 404, - HTTP_PRECON_FAILED: 412, - HTTP_RANGE_NOT_SATISFIABLE: 416 +// node_modules/@azure/storage-common/dist/commonjs/PooledBuffer.js +var require_PooledBuffer = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/PooledBuffer.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); }; - exports2.HeaderConstants = { - AUTHORIZATION: "Authorization", - AUTHORIZATION_SCHEME: "Bearer", - CONTENT_ENCODING: "Content-Encoding", - CONTENT_ID: "Content-ID", - CONTENT_LANGUAGE: "Content-Language", - CONTENT_LENGTH: "Content-Length", - CONTENT_MD5: "Content-Md5", - CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding", - CONTENT_TYPE: "Content-Type", - COOKIE: "Cookie", - DATE: "date", - IF_MATCH: "if-match", - IF_MODIFIED_SINCE: "if-modified-since", - IF_NONE_MATCH: "if-none-match", - IF_UNMODIFIED_SINCE: "if-unmodified-since", - PREFIX_FOR_STORAGE: "x-ms-", - RANGE: "Range", - USER_AGENT: "User-Agent", - X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id", - X_MS_COPY_SOURCE: "x-ms-copy-source", - X_MS_DATE: "x-ms-date", - X_MS_ERROR_CODE: "x-ms-error-code", - X_MS_VERSION: "x-ms-version", - X_MS_CopySourceErrorCode: "x-ms-copy-source-error-code" + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; }; - exports2.ETagNone = ""; - exports2.ETagAny = "*"; - exports2.SIZE_1_MB = 1 * 1024 * 1024; - exports2.BATCH_MAX_REQUEST = 256; - exports2.BATCH_MAX_PAYLOAD_IN_BYTES = 4 * exports2.SIZE_1_MB; - exports2.HTTP_LINE_ENDING = "\r\n"; - exports2.HTTP_VERSION_1_1 = "HTTP/1.1"; - exports2.EncryptionAlgorithmAES25 = "AES256"; - exports2.DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`; - exports2.StorageBlobLoggingAllowedHeaderNames = [ - "Access-Control-Allow-Origin", - "Cache-Control", - "Content-Length", - "Content-Type", - "Date", - "Request-Id", - "traceparent", - "Transfer-Encoding", - "User-Agent", - "x-ms-client-request-id", - "x-ms-date", - "x-ms-error-code", - "x-ms-request-id", - "x-ms-return-client-request-id", - "x-ms-version", - "Accept-Ranges", - "Content-Disposition", - "Content-Encoding", - "Content-Language", - "Content-MD5", - "Content-Range", - "ETag", - "Last-Modified", - "Server", - "Vary", - "x-ms-content-crc64", - "x-ms-copy-action", - "x-ms-copy-completion-time", - "x-ms-copy-id", - "x-ms-copy-progress", - "x-ms-copy-status", - "x-ms-has-immutability-policy", - "x-ms-has-legal-hold", - "x-ms-lease-state", - "x-ms-lease-status", - "x-ms-range", - "x-ms-request-server-encrypted", - "x-ms-server-encrypted", - "x-ms-snapshot", - "x-ms-source-range", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "x-ms-access-tier", - "x-ms-access-tier-change-time", - "x-ms-access-tier-inferred", - "x-ms-account-kind", - "x-ms-archive-status", - "x-ms-blob-append-offset", - "x-ms-blob-cache-control", - "x-ms-blob-committed-block-count", - "x-ms-blob-condition-appendpos", - "x-ms-blob-condition-maxsize", - "x-ms-blob-content-disposition", - "x-ms-blob-content-encoding", - "x-ms-blob-content-language", - "x-ms-blob-content-length", - "x-ms-blob-content-md5", - "x-ms-blob-content-type", - "x-ms-blob-public-access", - "x-ms-blob-sequence-number", - "x-ms-blob-type", - "x-ms-copy-destination-snapshot", - "x-ms-creation-time", - "x-ms-default-encryption-scope", - "x-ms-delete-snapshots", - "x-ms-delete-type-permanent", - "x-ms-deny-encryption-scope-override", - "x-ms-encryption-algorithm", - "x-ms-if-sequence-number-eq", - "x-ms-if-sequence-number-le", - "x-ms-if-sequence-number-lt", - "x-ms-incremental-copy", - "x-ms-lease-action", - "x-ms-lease-break-period", - "x-ms-lease-duration", - "x-ms-lease-id", - "x-ms-lease-time", - "x-ms-page-write", - "x-ms-proposed-lease-id", - "x-ms-range-get-content-md5", - "x-ms-rehydrate-priority", - "x-ms-sequence-number-action", - "x-ms-sku-name", - "x-ms-source-content-md5", - "x-ms-source-if-match", - "x-ms-source-if-modified-since", - "x-ms-source-if-none-match", - "x-ms-source-if-unmodified-since", - "x-ms-tag-count", - "x-ms-encryption-key-sha256", - "x-ms-copy-source-error-code", - "x-ms-copy-source-status-code", - "x-ms-if-tags", - "x-ms-source-if-tags" - ]; - exports2.StorageBlobLoggingAllowedQueryParameters = [ - "comp", - "maxresults", - "rscc", - "rscd", - "rsce", - "rscl", - "rsct", - "se", - "si", - "sip", - "sp", - "spr", - "sr", - "srt", - "ss", - "st", - "sv", - "include", - "marker", - "prefix", - "copyid", - "restype", - "blockid", - "blocklisttype", - "delimiter", - "prevsnapshot", - "ske", - "skoid", - "sks", - "skt", - "sktid", - "skv", - "snapshot" - ]; - exports2.BlobUsesCustomerSpecifiedEncryptionMsg = "BlobUsesCustomerSpecifiedEncryption"; - exports2.BlobDoesNotUseCustomerSpecifiedEncryption = "BlobDoesNotUseCustomerSpecifiedEncryption"; - exports2.PathStylePorts = [ - "10000", - "10001", - "10002", - "10003", - "10004", - "10100", - "10101", - "10102", - "10103", - "10104", - "11000", - "11001", - "11002", - "11003", - "11004", - "11100", - "11101", - "11102", - "11103", - "11104" - ]; - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/utils/utils.common.js -var require_utils_common = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/utils/utils.common.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.escapeURLPath = escapeURLPath; - exports2.getValueInConnString = getValueInConnString; - exports2.extractConnectionStringParts = extractConnectionStringParts; - exports2.appendToURLPath = appendToURLPath; - exports2.setURLParameter = setURLParameter; - exports2.getURLParameter = getURLParameter; - exports2.setURLHost = setURLHost; - exports2.getURLPath = getURLPath; - exports2.getURLScheme = getURLScheme; - exports2.getURLPathAndQuery = getURLPathAndQuery; - exports2.getURLQueries = getURLQueries; - exports2.appendToURLQuery = appendToURLQuery; - exports2.truncatedISO8061Date = truncatedISO8061Date; - exports2.base64encode = base64encode; - exports2.base64decode = base64decode; - exports2.generateBlockID = generateBlockID; - exports2.delay = delay2; - exports2.padStart = padStart2; - exports2.sanitizeURL = sanitizeURL; - exports2.sanitizeHeaders = sanitizeHeaders; - exports2.iEqual = iEqual; - exports2.getAccountNameFromUrl = getAccountNameFromUrl; - exports2.isIpEndpointStyle = isIpEndpointStyle; - exports2.toBlobTagsString = toBlobTagsString; - exports2.toBlobTags = toBlobTags; - exports2.toTags = toTags; - exports2.toQuerySerialization = toQuerySerialization; - exports2.parseObjectReplicationRecord = parseObjectReplicationRecord; - exports2.attachCredential = attachCredential; - exports2.httpAuthorizationToString = httpAuthorizationToString; - exports2.BlobNameToString = BlobNameToString; - exports2.ConvertInternalResponseOfListBlobFlat = ConvertInternalResponseOfListBlobFlat; - exports2.ConvertInternalResponseOfListBlobHierarchy = ConvertInternalResponseOfListBlobHierarchy; - exports2.ExtractPageRangeInfoItems = ExtractPageRangeInfoItems; - exports2.EscapePath = EscapePath; - exports2.assertResponse = assertResponse; - var core_rest_pipeline_1 = require_commonjs6(); - var core_util_1 = require_commonjs4(); - var constants_js_1 = require_constants10(); - function escapeURLPath(url2) { - const urlParsed = new URL(url2); - let path30 = urlParsed.pathname; - path30 = path30 || "/"; - path30 = escape3(path30); - urlParsed.pathname = path30; - return urlParsed.toString(); - } - function getProxyUriFromDevConnString(connectionString) { - let proxyUri = ""; - if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { - const matchCredentials = connectionString.split(";"); - for (const element of matchCredentials) { - if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { - proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var PooledBuffer_exports = {}; + __export2(PooledBuffer_exports, { + PooledBuffer: () => PooledBuffer + }); + module2.exports = __toCommonJS2(PooledBuffer_exports); + var import_BuffersStream = require_BuffersStream(); + var import_node_buffer = __toESM2(require("node:buffer")); + var maxBufferLength = import_node_buffer.default.constants.MAX_LENGTH; + var PooledBuffer = class { + /** + * Internal buffers used to keep the data. + * Each buffer has a length of the maxBufferLength except last one. + */ + buffers = []; + /** + * The total size of internal buffers. + */ + capacity; + /** + * The total size of data contained in internal buffers. + */ + _size; + /** + * The size of the data contained in the pooled buffers. + */ + get size() { + return this._size; + } + constructor(capacity, buffers, totalLength) { + this.capacity = capacity; + this._size = 0; + const bufferNum = Math.ceil(capacity / maxBufferLength); + for (let i = 0; i < bufferNum; i++) { + let len = i === bufferNum - 1 ? capacity % maxBufferLength : maxBufferLength; + if (len === 0) { + len = maxBufferLength; } + this.buffers.push(Buffer.allocUnsafe(len)); } - } - return proxyUri; - } - function getValueInConnString(connectionString, argument) { - const elements = connectionString.split(";"); - for (const element of elements) { - if (element.trim().startsWith(argument)) { - return element.trim().match(argument + "=(.*)")[1]; + if (buffers) { + this.fill(buffers, totalLength); } } - return ""; - } - function extractConnectionStringParts(connectionString) { - let proxyUri = ""; - if (connectionString.startsWith("UseDevelopmentStorage=true")) { - proxyUri = getProxyUriFromDevConnString(connectionString); - connectionString = constants_js_1.DevelopmentConnectionString; - } - let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); - blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; - if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && connectionString.search("AccountKey=") !== -1) { - let defaultEndpointsProtocol = ""; - let accountName = ""; - let accountKey = Buffer.from("accountKey", "base64"); - let endpointSuffix = ""; - accountName = getValueInConnString(connectionString, "AccountName"); - accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); - if (!blobEndpoint) { - defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); - const protocol = defaultEndpointsProtocol.toLowerCase(); - if (protocol !== "https" && protocol !== "http") { - throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'"); + /** + * Fill the internal buffers with data in the input buffers serially + * with respect to the total length and the total capacity of the internal buffers. + * Data copied will be shift out of the input buffers. + * + * @param buffers - Input buffers containing the data to be filled in the pooled buffer + * @param totalLength - Total length of the data to be filled in. + * + */ + fill(buffers, totalLength) { + this._size = Math.min(this.capacity, totalLength); + let i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0; + while (totalCopiedNum < this._size) { + const source = buffers[i]; + const target = this.buffers[j]; + const copiedNum = source.copy(target, targetOffset, sourceOffset); + totalCopiedNum += copiedNum; + sourceOffset += copiedNum; + targetOffset += copiedNum; + if (sourceOffset === source.length) { + i++; + sourceOffset = 0; } - endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix"); - if (!endpointSuffix) { - throw new Error("Invalid EndpointSuffix in the provided Connection String"); + if (targetOffset === target.length) { + j++; + targetOffset = 0; } - blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; } - if (!accountName) { - throw new Error("Invalid AccountName in the provided Connection String"); - } else if (accountKey.length === 0) { - throw new Error("Invalid AccountKey in the provided Connection String"); + buffers.splice(0, i); + if (buffers.length > 0) { + buffers[0] = buffers[0].slice(sourceOffset); } - return { - kind: "AccountConnString", - url: blobEndpoint, - accountName, - accountKey, - proxyUri - }; - } else { - let accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); - let accountName = getValueInConnString(connectionString, "AccountName"); - if (!accountName) { - accountName = getAccountNameFromUrl(blobEndpoint); + } + /** + * Get the readable stream assembled from all the data in the internal buffers. + * + */ + getReadableStream() { + return new import_BuffersStream.BuffersStream(this.buffers, this.size); + } + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/BufferScheduler.js +var require_BufferScheduler = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/BufferScheduler.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BufferScheduler_exports = {}; + __export2(BufferScheduler_exports, { + BufferScheduler: () => BufferScheduler + }); + module2.exports = __toCommonJS2(BufferScheduler_exports); + var import_events2 = require("events"); + var import_PooledBuffer = require_PooledBuffer(); + var BufferScheduler = class { + /** + * Size of buffers in incoming and outgoing queues. This class will try to align + * data read from Readable stream into buffer chunks with bufferSize defined. + */ + bufferSize; + /** + * How many buffers can be created or maintained. + */ + maxBuffers; + /** + * A Node.js Readable stream. + */ + readable; + /** + * OutgoingHandler is an async function triggered by BufferScheduler when there + * are available buffers in outgoing array. + */ + outgoingHandler; + /** + * An internal event emitter. + */ + emitter = new import_events2.EventEmitter(); + /** + * Concurrency of executing outgoingHandlers. (0 lesser than concurrency lesser than or equal to maxBuffers) + */ + concurrency; + /** + * An internal offset marker to track data offset in bytes of next outgoingHandler. + */ + offset = 0; + /** + * An internal marker to track whether stream is end. + */ + isStreamEnd = false; + /** + * An internal marker to track whether stream or outgoingHandler returns error. + */ + isError = false; + /** + * How many handlers are executing. + */ + executingOutgoingHandlers = 0; + /** + * Encoding of the input Readable stream which has string data type instead of Buffer. + */ + encoding; + /** + * How many buffers have been allocated. + */ + numBuffers = 0; + /** + * Because this class doesn't know how much data every time stream pops, which + * is defined by highWaterMarker of the stream. So BufferScheduler will cache + * data received from the stream, when data in unresolvedDataArray exceeds the + * blockSize defined, it will try to concat a blockSize of buffer, fill into available + * buffers from incoming and push to outgoing array. + */ + unresolvedDataArray = []; + /** + * How much data consisted in unresolvedDataArray. + */ + unresolvedLength = 0; + /** + * The array includes all the available buffers can be used to fill data from stream. + */ + incoming = []; + /** + * The array (queue) includes all the buffers filled from stream data. + */ + outgoing = []; + /** + * Creates an instance of BufferScheduler. + * + * @param readable - A Node.js Readable stream + * @param bufferSize - Buffer size of every maintained buffer + * @param maxBuffers - How many buffers can be allocated + * @param outgoingHandler - An async function scheduled to be + * triggered when a buffer fully filled + * with stream data + * @param concurrency - Concurrency of executing outgoingHandlers (>0) + * @param encoding - [Optional] Encoding of Readable stream when it's a string stream + */ + constructor(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) { + if (bufferSize <= 0) { + throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`); } - if (!blobEndpoint) { - throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); - } else if (!accountSas) { - throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); + if (maxBuffers <= 0) { + throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`); } - if (accountSas.startsWith("?")) { - accountSas = accountSas.substring(1); + if (concurrency <= 0) { + throw new RangeError(`concurrency must be larger than 0, current is ${concurrency}`); } - return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas }; + this.bufferSize = bufferSize; + this.maxBuffers = maxBuffers; + this.readable = readable; + this.outgoingHandler = outgoingHandler; + this.concurrency = concurrency; + this.encoding = encoding; } - } - function escape3(text) { - return encodeURIComponent(text).replace(/%2F/g, "/").replace(/'/g, "%27").replace(/\+/g, "%20").replace(/%25/g, "%"); - } - function appendToURLPath(url2, name) { - const urlParsed = new URL(url2); - let path30 = urlParsed.pathname; - path30 = path30 ? path30.endsWith("/") ? `${path30}${name}` : `${path30}/${name}` : name; - urlParsed.pathname = path30; - return urlParsed.toString(); - } - function setURLParameter(url2, name, value) { - const urlParsed = new URL(url2); - const encodedName = encodeURIComponent(name); - const encodedValue = value ? encodeURIComponent(value) : void 0; - const searchString = urlParsed.search === "" ? "?" : urlParsed.search; - const searchPieces = []; - for (const pair of searchString.slice(1).split("&")) { - if (pair) { - const [key] = pair.split("=", 2); - if (key !== encodedName) { - searchPieces.push(pair); + /** + * Start the scheduler, will return error when stream of any of the outgoingHandlers + * returns error. + * + */ + async do() { + return new Promise((resolve15, reject) => { + this.readable.on("data", (data) => { + data = typeof data === "string" ? Buffer.from(data, this.encoding) : data; + this.appendUnresolvedData(data); + if (!this.resolveData()) { + this.readable.pause(); + } + }); + this.readable.on("error", (err) => { + this.emitter.emit("error", err); + }); + this.readable.on("end", () => { + this.isStreamEnd = true; + this.emitter.emit("checkEnd"); + }); + this.emitter.on("error", (err) => { + this.isError = true; + this.readable.pause(); + reject(err); + }); + this.emitter.on("checkEnd", () => { + if (this.outgoing.length > 0) { + this.triggerOutgoingHandlers(); + return; + } + if (this.isStreamEnd && this.executingOutgoingHandlers === 0) { + if (this.unresolvedLength > 0 && this.unresolvedLength < this.bufferSize) { + const buffer = this.shiftBufferFromUnresolvedDataArray(); + this.outgoingHandler(() => buffer.getReadableStream(), buffer.size, this.offset).then(resolve15).catch(reject); + } else if (this.unresolvedLength >= this.bufferSize) { + return; + } else { + resolve15(); + } + } + }); + }); + } + /** + * Insert a new data into unresolved array. + * + * @param data - + */ + appendUnresolvedData(data) { + this.unresolvedDataArray.push(data); + this.unresolvedLength += data.length; + } + /** + * Try to shift a buffer with size in blockSize. The buffer returned may be less + * than blockSize when data in unresolvedDataArray is less than bufferSize. + * + */ + shiftBufferFromUnresolvedDataArray(buffer) { + if (!buffer) { + buffer = new import_PooledBuffer.PooledBuffer(this.bufferSize, this.unresolvedDataArray, this.unresolvedLength); + } else { + buffer.fill(this.unresolvedDataArray, this.unresolvedLength); + } + this.unresolvedLength -= buffer.size; + return buffer; + } + /** + * Resolve data in unresolvedDataArray. For every buffer with size in blockSize + * shifted, it will try to get (or allocate a buffer) from incoming, and fill it, + * then push it into outgoing to be handled by outgoing handler. + * + * Return false when available buffers in incoming are not enough, else true. + * + * @returns Return false when buffers in incoming are not enough, else true. + */ + resolveData() { + while (this.unresolvedLength >= this.bufferSize) { + let buffer; + if (this.incoming.length > 0) { + buffer = this.incoming.shift(); + this.shiftBufferFromUnresolvedDataArray(buffer); + } else { + if (this.numBuffers < this.maxBuffers) { + buffer = this.shiftBufferFromUnresolvedDataArray(); + this.numBuffers++; + } else { + return false; + } } + this.outgoing.push(buffer); + this.triggerOutgoingHandlers(); } + return true; } - if (encodedValue) { - searchPieces.push(`${encodedName}=${encodedValue}`); + /** + * Try to trigger a outgoing handler for every buffer in outgoing. Stop when + * concurrency reaches. + */ + async triggerOutgoingHandlers() { + let buffer; + do { + if (this.executingOutgoingHandlers >= this.concurrency) { + return; + } + buffer = this.outgoing.shift(); + if (buffer) { + this.triggerOutgoingHandler(buffer); + } + } while (buffer); } - urlParsed.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; - return urlParsed.toString(); + /** + * Trigger a outgoing handler for a buffer shifted from outgoing. + * + * @param buffer - + */ + async triggerOutgoingHandler(buffer) { + const bufferLength = buffer.size; + this.executingOutgoingHandlers++; + this.offset += bufferLength; + try { + await this.outgoingHandler( + () => buffer.getReadableStream(), + bufferLength, + this.offset - bufferLength + ); + } catch (err) { + this.emitter.emit("error", err); + return; + } + this.executingOutgoingHandlers--; + this.reuseBuffer(buffer); + this.emitter.emit("checkEnd"); + } + /** + * Return buffer used by outgoing handler into incoming. + * + * @param buffer - + */ + reuseBuffer(buffer) { + this.incoming.push(buffer); + if (!this.isError && this.resolveData() && !this.isStreamEnd) { + this.readable.resume(); + } + } + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/bufferHelpers.js +var require_bufferHelpers = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/bufferHelpers.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var bufferHelpers_exports = {}; + __export2(bufferHelpers_exports, { + allocBuffer: () => allocBuffer, + bufferFromArrayBuffer: () => bufferFromArrayBuffer, + getBufferLength: () => getBufferLength, + isBuffer: () => isBuffer + }); + module2.exports = __toCommonJS2(bufferHelpers_exports); + function isBuffer(value) { + return Buffer.isBuffer(value); } - function getURLParameter(url2, name) { - const urlParsed = new URL(url2); - return urlParsed.searchParams.get(name) ?? void 0; + function allocBuffer(size) { + return Buffer.alloc(size); } - function setURLHost(url2, host) { - const urlParsed = new URL(url2); - urlParsed.hostname = host; - return urlParsed.toString(); + function bufferFromArrayBuffer(ab, byteOffset, length) { + return Buffer.from(ab, byteOffset, length); } - function getURLPath(url2) { - try { - const urlParsed = new URL(url2); - return urlParsed.pathname; - } catch (e) { - return void 0; - } + function getBufferLength(buffer) { + return buffer.length; } - function getURLScheme(url2) { - try { - const urlParsed = new URL(url2); - return urlParsed.protocol.endsWith(":") ? urlParsed.protocol.slice(0, -1) : urlParsed.protocol; - } catch (e) { - return void 0; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/bufferHelpers.common.js +var require_bufferHelpers_common = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/bufferHelpers.common.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - } - function getURLPathAndQuery(url2) { - const urlParsed = new URL(url2); - const pathString = urlParsed.pathname; - if (!pathString) { - throw new RangeError("Invalid url without valid path."); + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var bufferHelpers_common_exports = {}; + __export2(bufferHelpers_common_exports, { + createBlobFromData: () => createBlobFromData2 + }); + module2.exports = __toCommonJS2(bufferHelpers_common_exports); + function createBlobFromData2(data) { + if (data instanceof Blob) { + return data; } - let queryString = urlParsed.search || ""; - queryString = queryString.trim(); - if (queryString !== "") { - queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; + const BlobCtor = Blob; + if (data instanceof ArrayBuffer) { + return new BlobCtor([data]); + } else { + const ab = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); + return new BlobCtor([ab]); } - return `${pathString}${queryString}`; } - function getURLQueries(url2) { - let queryString = new URL(url2).search; - if (!queryString) { - return {}; - } - queryString = queryString.trim(); - queryString = queryString.startsWith("?") ? queryString.substring(1) : queryString; - let querySubStrings = queryString.split("&"); - querySubStrings = querySubStrings.filter((value) => { - const indexOfEqual = value.indexOf("="); - const lastIndexOfEqual = value.lastIndexOf("="); - return indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1; - }); - const queries = {}; - for (const querySubString of querySubStrings) { - const splitResults = querySubString.split("="); - const key = splitResults[0]; - const value = splitResults[1]; - queries[key] = value; + } +}); + +// node_modules/@azure/storage-common/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError3 = __commonJS({ + "node_modules/@azure/storage-common/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - return queries; - } - function appendToURLQuery(url2, queryParts) { - const urlParsed = new URL(url2); - let query = urlParsed.search; - if (query) { - query += "&" + queryParts; - } else { - query = queryParts; + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var AbortError_exports = {}; + __export2(AbortError_exports, { + AbortError: () => AbortError2 + }); + module2.exports = __toCommonJS2(AbortError_exports); + var AbortError2 = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } - urlParsed.search = query; - return urlParsed.toString(); - } - function truncatedISO8061Date(date, withMilliseconds = true) { - const dateString = date.toISOString(); - return withMilliseconds ? dateString.substring(0, dateString.length - 1) + "0000Z" : dateString.substring(0, dateString.length - 5) + "Z"; - } - function base64encode(content) { - return !core_util_1.isNodeLike ? btoa(content) : Buffer.from(content).toString("base64"); - } - function base64decode(encodedString) { - return !core_util_1.isNodeLike ? atob(encodedString) : Buffer.from(encodedString, "base64").toString(); - } - function generateBlockID(blockIDPrefix, blockIndex) { - const maxSourceStringLength = 48; - const maxBlockIndexLength = 6; - const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; - if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { - blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); + }; + } +}); + +// node_modules/@azure/storage-common/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs11 = __commonJS({ + "node_modules/@azure/storage-common/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - const res = blockIDPrefix + padStart2(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); - return base64encode(res); - } - async function delay2(timeInMs, aborter, abortError) { - return new Promise((resolve14, reject) => { - let timeout; - const abortHandler = () => { - if (timeout !== void 0) { - clearTimeout(timeout); + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var src_exports = {}; + __export2(src_exports, { + AbortError: () => import_AbortError.AbortError + }); + module2.exports = __toCommonJS2(src_exports); + var import_AbortError = require_AbortError3(); + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/crc64.js +var require_crc64 = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/crc64.js"(exports2, module2) { + var NativeCRC64 = (() => { + var _scriptDir = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : void 0; + return (function(NativeCRC642) { + NativeCRC642 = NativeCRC642 || {}; + var Module = typeof NativeCRC642 != "undefined" ? NativeCRC642 : {}; + var readyPromiseResolve, readyPromiseReject; + Module["ready"] = new Promise(function(resolve15, reject) { + readyPromiseResolve = resolve15; + readyPromiseReject = reject; + }); + ["_malloc", "_free", "_emscripten_bind_VoidPtr___destroy___0", "_emscripten_bind_Crc64Hash_Crc64Hash_0", "_emscripten_bind_Crc64Hash_OnAppend_2", "_emscripten_bind_Crc64Hash_OnFinal_3", "_emscripten_bind_Crc64Hash___destroy___0", "_fflush", "onRuntimeInitialized"].forEach((prop) => { + if (!Object.getOwnPropertyDescriptor(Module["ready"], prop)) { + Object.defineProperty(Module["ready"], prop, { + get: () => abort("You are getting " + prop + " on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js"), + set: () => abort("You are setting " + prop + " on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js") + }); } - reject(abortError); + }); + var moduleOverrides = Object.assign({}, Module); + var arguments_ = []; + var thisProgram = "./this.program"; + var quit_ = (status, toThrow) => { + throw toThrow; }; - const resolveHandler = () => { - if (aborter !== void 0) { - aborter.removeEventListener("abort", abortHandler); + var ENVIRONMENT_IS_WEB = typeof window == "object"; + var ENVIRONMENT_IS_WORKER = typeof importScripts == "function"; + var ENVIRONMENT_IS_NODE = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string"; + var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; + if (Module["ENVIRONMENT"]) { + throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)"); + } + var scriptDirectory = ""; + function locateFile(path30) { + if (Module["locateFile"]) { + return Module["locateFile"](path30, scriptDirectory); + } + return scriptDirectory + path30; + } + var read_, readAsync, readBinary, setWindowTitle; + function logExceptionOnExit(e) { + if (e instanceof ExitStatus) return; + let toLog = e; + if (e && typeof e == "object" && e.stack) { + toLog = [e, e.stack]; + } + err("exiting due to exception: " + toLog); + } + if (ENVIRONMENT_IS_NODE) { + if (typeof process == "undefined" || !process.release || process.release.name !== "node") throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)"); + if (process["argv"].length > 1) { + thisProgram = process["argv"][1].replace(/\\/g, "/"); + } + arguments_ = process["argv"].slice(2); + process["on"]("uncaughtException", function(ex) { + if (!(ex instanceof ExitStatus)) { + throw ex; + } + }); + process["on"]("unhandledRejection", function(reason) { + throw reason; + }); + quit_ = (status, toThrow) => { + if (keepRuntimeAlive()) { + process["exitCode"] = status; + throw toThrow; + } + logExceptionOnExit(toThrow); + process["exit"](status); + }; + Module["inspect"] = function() { + return "[Emscripten Module object]"; + }; + } else if (ENVIRONMENT_IS_SHELL) { + if (typeof process == "object" && typeof require === "function" || typeof window == "object" || typeof importScripts == "function") throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)"); + if (typeof scriptArgs != "undefined") { + arguments_ = scriptArgs; + } else if (typeof arguments != "undefined") { + arguments_ = arguments; + } + if (typeof quit == "function") { + quit_ = (status, toThrow) => { + logExceptionOnExit(toThrow); + quit(status); + }; + } + if (typeof print != "undefined") { + if (typeof console == "undefined") console = /** @type{!Console} */ + {}; + console.log = /** @type{!function(this:Console, ...*): undefined} */ + print; + console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */ + typeof printErr != "undefined" ? printErr : print; + } + } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { + if (!(typeof window == "object" || typeof importScripts == "function")) throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)"); + } else { + throw new Error("environment detection error"); + } + var out = Module["print"] || console.log.bind(console); + var err = Module["printErr"] || console.warn.bind(console); + Object.assign(Module, moduleOverrides); + moduleOverrides = null; + checkIncomingModuleAPI(); + if (Module["arguments"]) arguments_ = Module["arguments"]; + legacyModuleProp("arguments", "arguments_"); + if (Module["thisProgram"]) thisProgram = Module["thisProgram"]; + legacyModuleProp("thisProgram", "thisProgram"); + if (Module["quit"]) quit_ = Module["quit"]; + legacyModuleProp("quit", "quit_"); + assert(typeof Module["memoryInitializerPrefixURL"] == "undefined", "Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"); + assert(typeof Module["pthreadMainPrefixURL"] == "undefined", "Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"); + assert(typeof Module["cdInitializerPrefixURL"] == "undefined", "Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"); + assert(typeof Module["filePackagePrefixURL"] == "undefined", "Module.filePackagePrefixURL option was removed, use Module.locateFile instead"); + assert(typeof Module["read"] == "undefined", "Module.read option was removed (modify read_ in JS)"); + assert(typeof Module["readAsync"] == "undefined", "Module.readAsync option was removed (modify readAsync in JS)"); + assert(typeof Module["readBinary"] == "undefined", "Module.readBinary option was removed (modify readBinary in JS)"); + assert(typeof Module["setWindowTitle"] == "undefined", "Module.setWindowTitle option was removed (modify setWindowTitle in JS)"); + assert(typeof Module["TOTAL_MEMORY"] == "undefined", "Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"); + legacyModuleProp("read", "read_"); + legacyModuleProp("readAsync", "readAsync"); + legacyModuleProp("readBinary", "readBinary"); + legacyModuleProp("setWindowTitle", "setWindowTitle"); + var IDBFS = "IDBFS is no longer included by default; build with -lidbfs.js"; + var PROXYFS = "PROXYFS is no longer included by default; build with -lproxyfs.js"; + var WORKERFS = "WORKERFS is no longer included by default; build with -lworkerfs.js"; + var NODEFS = "NODEFS is no longer included by default; build with -lnodefs.js"; + assert(!ENVIRONMENT_IS_SHELL, "shell environment detected but not enabled at build time. Add 'shell' to `-sENVIRONMENT` to enable."); + var STACK_ALIGN = 16; + var POINTER_SIZE = 4; + function getNativeTypeSize(type) { + switch (type) { + case "i1": + case "i8": + case "u8": + return 1; + case "i16": + case "u16": + return 2; + case "i32": + case "u32": + return 4; + case "i64": + case "u64": + return 8; + case "float": + return 4; + case "double": + return 8; + default: { + if (type[type.length - 1] === "*") { + return POINTER_SIZE; + } + if (type[0] === "i") { + const bits = Number(type.substr(1)); + assert(bits % 8 === 0, "getNativeTypeSize invalid bits " + bits + ", type " + type); + return bits / 8; + } + return 0; + } + } + } + function legacyModuleProp(prop, newName) { + if (!Object.getOwnPropertyDescriptor(Module, prop)) { + Object.defineProperty(Module, prop, { + configurable: true, + get: function() { + abort("Module." + prop + " has been replaced with plain " + newName + " (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)"); + } + }); + } + } + function ignoredModuleProp(prop) { + if (Object.getOwnPropertyDescriptor(Module, prop)) { + abort("`Module." + prop + "` was supplied but `" + prop + "` not included in INCOMING_MODULE_JS_API"); + } + } + function isExportedByForceFilesystem(name) { + return name === "FS_createPath" || name === "FS_createDataFile" || name === "FS_createPreloadedFile" || name === "FS_unlink" || name === "addRunDependency" || // The old FS has some functionality that WasmFS lacks. + name === "FS_createLazyFile" || name === "FS_createDevice" || name === "removeRunDependency"; + } + function missingLibrarySymbol(sym) { + if (typeof globalThis !== "undefined" && !Object.getOwnPropertyDescriptor(globalThis, sym)) { + Object.defineProperty(globalThis, sym, { + configurable: true, + get: function() { + var msg = "`" + sym + "` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line"; + var librarySymbol = sym; + if (!librarySymbol.startsWith("_")) { + librarySymbol = "$" + sym; + } + msg += " (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE=" + librarySymbol + ")"; + if (isExportedByForceFilesystem(sym)) { + msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"; + } + warnOnce(msg); + return void 0; + } + }); + } + } + function unexportedRuntimeSymbol(sym) { + if (!Object.getOwnPropertyDescriptor(Module, sym)) { + Object.defineProperty(Module, sym, { + configurable: true, + get: function() { + var msg = "'" + sym + "' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)"; + if (isExportedByForceFilesystem(sym)) { + msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"; + } + abort(msg); + } + }); + } + } + var wasmBinary; + if (Module["wasmBinary"]) wasmBinary = Module["wasmBinary"]; + legacyModuleProp("wasmBinary", "wasmBinary"); + var noExitRuntime = Module["noExitRuntime"] || true; + legacyModuleProp("noExitRuntime", "noExitRuntime"); + if (typeof WebAssembly != "object") { + abort("no native wasm support detected"); + } + var wasmMemory; + var ABORT = false; + var EXITSTATUS; + function assert(condition, text) { + if (!condition) { + abort("Assertion failed" + (text ? ": " + text : "")); + } + } + var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder("utf8") : void 0; + function UTF8ArrayToString(heapOrArray, idx, maxBytesToRead) { + var endIdx = idx + maxBytesToRead; + var endPtr = idx; + while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr; + if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) { + return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr)); + } + var str = ""; + while (idx < endPtr) { + var u0 = heapOrArray[idx++]; + if (!(u0 & 128)) { + str += String.fromCharCode(u0); + continue; + } + var u1 = heapOrArray[idx++] & 63; + if ((u0 & 224) == 192) { + str += String.fromCharCode((u0 & 31) << 6 | u1); + continue; + } + var u2 = heapOrArray[idx++] & 63; + if ((u0 & 240) == 224) { + u0 = (u0 & 15) << 12 | u1 << 6 | u2; + } else { + if ((u0 & 248) != 240) warnOnce("Invalid UTF-8 leading byte " + ptrToString(u0) + " encountered when deserializing a UTF-8 string in wasm memory to a JS string!"); + u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63; + } + if (u0 < 65536) { + str += String.fromCharCode(u0); + } else { + var ch = u0 - 65536; + str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023); + } + } + return str; + } + function UTF8ToString(ptr, maxBytesToRead) { + return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ""; + } + function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { + if (!(maxBytesToWrite > 0)) + return 0; + var startIdx = outIdx; + var endIdx = outIdx + maxBytesToWrite - 1; + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i); + if (u >= 55296 && u <= 57343) { + var u1 = str.charCodeAt(++i); + u = 65536 + ((u & 1023) << 10) | u1 & 1023; + } + if (u <= 127) { + if (outIdx >= endIdx) break; + heap[outIdx++] = u; + } else if (u <= 2047) { + if (outIdx + 1 >= endIdx) break; + heap[outIdx++] = 192 | u >> 6; + heap[outIdx++] = 128 | u & 63; + } else if (u <= 65535) { + if (outIdx + 2 >= endIdx) break; + heap[outIdx++] = 224 | u >> 12; + heap[outIdx++] = 128 | u >> 6 & 63; + heap[outIdx++] = 128 | u & 63; + } else { + if (outIdx + 3 >= endIdx) break; + if (u > 1114111) warnOnce("Invalid Unicode code point " + ptrToString(u) + " encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."); + heap[outIdx++] = 240 | u >> 18; + heap[outIdx++] = 128 | u >> 12 & 63; + heap[outIdx++] = 128 | u >> 6 & 63; + heap[outIdx++] = 128 | u & 63; + } + } + heap[outIdx] = 0; + return outIdx - startIdx; + } + function stringToUTF8(str, outPtr, maxBytesToWrite) { + assert(typeof maxBytesToWrite == "number", "stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"); + return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite); + } + function lengthBytesUTF8(str) { + var len = 0; + for (var i = 0; i < str.length; ++i) { + var c = str.charCodeAt(i); + if (c <= 127) { + len++; + } else if (c <= 2047) { + len += 2; + } else if (c >= 55296 && c <= 57343) { + len += 4; + ++i; + } else { + len += 3; + } + } + return len; + } + var HEAP, buffer, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64; + function updateGlobalBufferAndViews(buf) { + buffer = buf; + Module["HEAP8"] = HEAP8 = new Int8Array(buf); + Module["HEAP16"] = HEAP16 = new Int16Array(buf); + Module["HEAP32"] = HEAP32 = new Int32Array(buf); + Module["HEAPU8"] = HEAPU8 = new Uint8Array(buf); + Module["HEAPU16"] = HEAPU16 = new Uint16Array(buf); + Module["HEAPU32"] = HEAPU32 = new Uint32Array(buf); + Module["HEAPF32"] = HEAPF32 = new Float32Array(buf); + Module["HEAPF64"] = HEAPF64 = new Float64Array(buf); + } + var STACK_SIZE = 5242880; + if (Module["STACK_SIZE"]) assert(STACK_SIZE === Module["STACK_SIZE"], "the stack size can no longer be determined at runtime"); + var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216; + legacyModuleProp("INITIAL_MEMORY", "INITIAL_MEMORY"); + assert(INITIAL_MEMORY >= STACK_SIZE, "INITIAL_MEMORY should be larger than STACK_SIZE, was " + INITIAL_MEMORY + "! (STACK_SIZE=" + STACK_SIZE + ")"); + assert( + typeof Int32Array != "undefined" && typeof Float64Array !== "undefined" && Int32Array.prototype.subarray != void 0 && Int32Array.prototype.set != void 0, + "JS engine does not provide full typed array support" + ); + assert(!Module["wasmMemory"], "Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"); + assert(INITIAL_MEMORY == 16777216, "Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically"); + var wasmTable; + function writeStackCookie() { + var max = _emscripten_stack_get_end(); + assert((max & 3) == 0); + if (max == 0) { + max += 4; + } + HEAPU32[max >> 2] = 34821223; + HEAPU32[max + 4 >> 2] = 2310721022; + HEAPU32[0] = 1668509029; + } + function checkStackCookie() { + if (ABORT) return; + var max = _emscripten_stack_get_end(); + if (max == 0) { + max += 4; + } + var cookie1 = HEAPU32[max >> 2]; + var cookie2 = HEAPU32[max + 4 >> 2]; + if (cookie1 != 34821223 || cookie2 != 2310721022) { + abort("Stack overflow! Stack cookie has been overwritten at " + ptrToString(max) + ", expected hex dwords 0x89BACDFE and 0x2135467, but received " + ptrToString(cookie2) + " " + ptrToString(cookie1)); + } + if (HEAPU32[0] !== 1668509029) { + abort("Runtime error: The application has corrupted its heap memory area (address zero)!"); + } + } + (function() { + var h16 = new Int16Array(1); + var h8 = new Int8Array(h16.buffer); + h16[0] = 25459; + if (h8[0] !== 115 || h8[1] !== 99) throw "Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"; + })(); + var __ATPRERUN__ = []; + var __ATINIT__ = []; + var __ATEXIT__ = []; + var __ATPOSTRUN__ = []; + var runtimeInitialized = false; + function keepRuntimeAlive() { + return noExitRuntime; + } + function preRun() { + if (Module["preRun"]) { + if (typeof Module["preRun"] == "function") Module["preRun"] = [Module["preRun"]]; + while (Module["preRun"].length) { + addOnPreRun(Module["preRun"].shift()); + } + } + callRuntimeCallbacks(__ATPRERUN__); + } + function initRuntime() { + assert(!runtimeInitialized); + runtimeInitialized = true; + checkStackCookie(); + callRuntimeCallbacks(__ATINIT__); + } + function postRun() { + checkStackCookie(); + if (Module["postRun"]) { + if (typeof Module["postRun"] == "function") Module["postRun"] = [Module["postRun"]]; + while (Module["postRun"].length) { + addOnPostRun(Module["postRun"].shift()); + } + } + callRuntimeCallbacks(__ATPOSTRUN__); + } + function addOnPreRun(cb) { + __ATPRERUN__.unshift(cb); + } + function addOnInit(cb) { + __ATINIT__.unshift(cb); + } + function addOnExit(cb) { + } + function addOnPostRun(cb) { + __ATPOSTRUN__.unshift(cb); + } + assert(Math.imul, "This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"); + assert(Math.fround, "This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"); + assert(Math.clz32, "This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"); + assert(Math.trunc, "This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"); + var runDependencies = 0; + var runDependencyWatcher = null; + var dependenciesFulfilled = null; + var runDependencyTracking = {}; + function getUniqueRunDependency(id) { + var orig = id; + while (1) { + if (!runDependencyTracking[id]) return id; + id = orig + Math.random(); + } + } + function addRunDependency(id) { + runDependencies++; + if (Module["monitorRunDependencies"]) { + Module["monitorRunDependencies"](runDependencies); + } + if (id) { + assert(!runDependencyTracking[id]); + runDependencyTracking[id] = 1; + if (runDependencyWatcher === null && typeof setInterval != "undefined") { + runDependencyWatcher = setInterval(function() { + if (ABORT) { + clearInterval(runDependencyWatcher); + runDependencyWatcher = null; + return; + } + var shown = false; + for (var dep in runDependencyTracking) { + if (!shown) { + shown = true; + err("still waiting on run dependencies:"); + } + err("dependency: " + dep); + } + if (shown) { + err("(end of list)"); + } + }, 1e4); + } + } else { + err("warning: run dependency added without ID"); + } + } + function removeRunDependency(id) { + runDependencies--; + if (Module["monitorRunDependencies"]) { + Module["monitorRunDependencies"](runDependencies); + } + if (id) { + assert(runDependencyTracking[id]); + delete runDependencyTracking[id]; + } else { + err("warning: run dependency removed without ID"); + } + if (runDependencies == 0) { + if (runDependencyWatcher !== null) { + clearInterval(runDependencyWatcher); + runDependencyWatcher = null; + } + if (dependenciesFulfilled) { + var callback = dependenciesFulfilled; + dependenciesFulfilled = null; + callback(); + } + } + } + function abort(what) { + if (Module["onAbort"]) { + Module["onAbort"](what); + } + what = "Aborted(" + what + ")"; + err(what); + ABORT = true; + EXITSTATUS = 1; + var e = new WebAssembly.RuntimeError(what); + readyPromiseReject(e); + throw e; + } + var FS = { + error: function() { + abort("Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with -sFORCE_FILESYSTEM"); + }, + init: function() { + FS.error(); + }, + createDataFile: function() { + FS.error(); + }, + createPreloadedFile: function() { + FS.error(); + }, + createLazyFile: function() { + FS.error(); + }, + open: function() { + FS.error(); + }, + mkdev: function() { + FS.error(); + }, + registerDevice: function() { + FS.error(); + }, + analyzePath: function() { + FS.error(); + }, + loadFilesFromDB: function() { + FS.error(); + }, + ErrnoError: function ErrnoError() { + FS.error(); } - resolve14(); }; - timeout = setTimeout(resolveHandler, timeInMs); - if (aborter !== void 0) { - aborter.addEventListener("abort", abortHandler); + Module["FS_createDataFile"] = FS.createDataFile; + Module["FS_createPreloadedFile"] = FS.createPreloadedFile; + var dataURIPrefix = "data:application/octet-stream;base64,"; + function isDataURI(filename) { + return filename.startsWith(dataURIPrefix); + } + function isFileURI(filename) { + return filename.startsWith("file://"); + } + function createExportWrapper(name, fixedasm) { + return function() { + var displayName = name; + var asm2 = fixedasm; + if (!fixedasm) { + asm2 = Module["asm"]; + } + assert(runtimeInitialized, "native function `" + displayName + "` called before runtime initialization"); + if (!asm2[name]) { + assert(asm2[name], "exported native function `" + displayName + "` not found"); + } + return asm2[name].apply(null, arguments); + }; + } + var wasmBinaryFile; + wasmBinaryFile = "crc64.wasm"; + if (!isDataURI(wasmBinaryFile)) { + wasmBinaryFile = locateFile(wasmBinaryFile); + } + var binaryInString = [ + "AGFzbQEAAAABzYCAgAAMYAF/AX9gAAF/YAF/AGAAAGADf35/AX5gA39/fwBgBH9/f38AYAN/f38Bf2AFf39", + "/f38Bf2AEf39/fwF/YAR/f35/AX5gBH9+f38BfwKPgYCAAAUDZW52BWFib3J0AAMDZW52FmVtc2NyaXB0ZW", + "5fcmVzaXplX2hlYXAAABZ3YXNpX3NuYXBzaG90X3ByZXZpZXcxCGZkX2Nsb3NlAAAWd2FzaV9zbmFwc2hvd", + "F9wcmV2aWV3MQhmZF93cml0ZQAJFndhc2lfc25hcHNob3RfcHJldmlldzEHZmRfc2VlawAIA62AgIAALAMF", + "BgIBAAUGAgEBAAACAAIAAAAHBAQCAgEDAAIAAQIBAQIAAQMBAQEACggLBIWAgIAAAXABBAQFh4CAgAABAYA", + "CgIACBsiAgIAACn8BQYCAwAILfwFBAAt/AUEAC38BQQALfwBBnJHBAgt/AEGwkcECC38AQZyRwQILfwBBsJ", + "HBAgt/AEGwkcECC38AQZKSwQILB/qEgIAAGwZtZW1vcnkCABFfX3dhc21fY2FsbF9jdG9ycwAFJWVtc2Nya", + "XB0ZW5fYmluZF9Wb2lkUHRyX19fZGVzdHJveV9fXzAACCVlbXNjcmlwdGVuX2JpbmRfQ3JjNjRIYXNoX0Ny", + "YzY0SGFzaF8wAAkkZW1zY3JpcHRlbl9iaW5kX0NyYzY0SGFzaF9PbkFwcGVuZF8yAAsjZW1zY3JpcHRlbl9", + "iaW5kX0NyYzY0SGFzaF9PbkZpbmFsXzMADCdlbXNjcmlwdGVuX2JpbmRfQ3JjNjRIYXNoX19fZGVzdHJveV", + "9fXzAADRtfX2VtX2xpYl9kZXBzX3dlYmlkbF9iaW5kZXIDBCFfX2VtX2pzX19hcnJheV9ib3VuZHNfY2hlY", + "2tfZXJyb3IDBRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQAQX19lcnJub19sb2NhdGlvbgAPBmZmbHVz", + "aAAtBm1hbGxvYwARBGZyZWUAEhVlbXNjcmlwdGVuX3N0YWNrX2luaXQAKRllbXNjcmlwdGVuX3N0YWNrX2d", + "ldF9mcmVlACoZZW1zY3JpcHRlbl9zdGFja19nZXRfYmFzZQArGGVtc2NyaXB0ZW5fc3RhY2tfZ2V0X2VuZA", + "AsCXN0YWNrU2F2ZQAlDHN0YWNrUmVzdG9yZQAmCnN0YWNrQWxsb2MAJxxlbXNjcmlwdGVuX3N0YWNrX2dld", + "F9jdXJyZW50ACgTX19zdGFydF9lbV9saWJfZGVwcwMGEl9fc3RvcF9lbV9saWJfZGVwcwMHDV9fc3RhcnRf", + "ZW1fanMDCAxfX3N0b3BfZW1fanMDCQxkeW5DYWxsX2ppamkALwmJgICAAAEAQQELAxYYGgqtkYGAACwEABA", + "pC81IAvcCf6EFfiMAIQNBgAEhBCADIARrIQUgBSAANgJ8IAUgATYCeCAFIAI2AnQgBSgCfCEGIAUoAnghBy", + "AFIAc2AnAgBSgCdCEIIAghCSAJrCH6AiAGKQMIIfsCIPsCIPoCfCH8AiAGIPwCNwMIIAYpAwAh/QJCfyH+A", + "iD9AiD+AoUh/wIgBSD/AjcDaEIAIYADIAUggAM3A2AgBSgCdCEKIAUoAnQhC0EgIQwgCyAMbyENIAogDWsh", + "DiAFIA42AlwgBSgCXCEPQcAAIRAgDyERIBAhEiARIBJPIRNBASEUIBMgFHEhFQJAIBVFDQAgBSgCcCEWIAU", + "gFjYCWEIAIYEDIAUggQM3A1BCACGCAyAFIIIDNwNIQgAhgwMgBSCDAzcDQEIAIYQDIAUghAM3AzggBSkDYC", + "GFAyAFKAJcIRcgFyEYIBitIYYDIIUDIIYDfCGHA0IgIYgDIIcDIIgDfSGJAyAFIIkDNwMwIAUoAlwhGSAFK", + "AJ0IRogGiAZayEbIAUgGzYCdCAFKQNoIYoDIAUgigM3A1ACQANAIAUpA2AhiwMgBSkDMCGMAyCLAyGNAyCM", + "AyGOAyCNAyCOA1QhHEEBIR0gHCAdcSEeIB5FDQEgBSgCWCEfIB8pAwAhjwMgBSkDUCGQAyCPAyCQA4UhkQM", + "gBSCRAzcDKCAFKAJYISAgICkDCCGSAyAFKQNIIZMDIJIDIJMDhSGUAyAFIJQDNwMgIAUoAlghISAhKQMQIZ", + "UDIAUpA0AhlgMglQMglgOFIZcDIAUglwM3AxggBSgCWCEiICIpAxghmAMgBSkDOCGZAyCYAyCZA4UhmgMgB", + "SCaAzcDECAFKQMoIZsDQv8BIZwDIJsDIJwDgyGdA0KADiGeAyCdAyCeA3whnwMgnwOnISNBgIDAAiEkQQMh", + "JSAjICV0ISYgJCAmaiEnICcpAwAhoAMgBSCgAzcDUCAFKQMoIaEDQgghogMgoQMgogOIIaMDIAUgowM3Ayg", + "gBSkDICGkA0L/ASGlAyCkAyClA4MhpgNCgA4hpwMgpgMgpwN8IagDIKgDpyEoQYCAwAIhKUEDISogKCAqdC", + "ErICkgK2ohLCAsKQMAIakDIAUgqQM3A0ggBSkDICGqA0IIIasDIKoDIKsDiCGsAyAFIKwDNwMgIAUpAxghr", + "QNC/wEhrgMgrQMgrgODIa8DQoAOIbADIK8DILADfCGxAyCxA6chLUGAgMACIS5BAyEvIC0gL3QhMCAuIDBq", + "ITEgMSkDACGyAyAFILIDNwNAIAUpAxghswNCCCG0AyCzAyC0A4ghtQMgBSC1AzcDGCAFKQMQIbYDQv8BIbc", + "DILYDILcDgyG4A0KADiG5AyC4AyC5A3whugMgugOnITJBgIDAAiEzQQMhNCAyIDR0ITUgMyA1aiE2IDYpAw", + "AhuwMgBSC7AzcDOCAFKQMQIbwDQgghvQMgvAMgvQOIIb4DIAUgvgM3AxAgBSkDKCG/A0L/ASHAAyC/AyDAA", + "4MhwQNCgAwhwgMgwQMgwgN8IcMDIMMDpyE3QYCAwAIhOEEDITkgNyA5dCE6IDggOmohOyA7KQMAIcQDIAUp", + "A1AhxQMgxQMgxAOFIcYDIAUgxgM3A1AgBSkDKCHHA0IIIcgDIMcDIMgDiCHJAyAFIMkDNwMoIAUpAyAhygN", + "C/wEhywMgygMgywODIcwDQoAMIc0DIMwDIM0DfCHOAyDOA6chPEGAgMACIT1BAyE+IDwgPnQhPyA9ID9qIU", + "AgQCkDACHPAyAFKQNIIdADINADIM8DhSHRAyAFINEDNwNIIAUpAyAh0gNCCCHTAyDSAyDTA4gh1AMgBSDUA", + "zcDICAFKQMYIdUDQv8BIdYDINUDINYDgyHXA0KADCHYAyDXAyDYA3wh2QMg2QOnIUFBgIDAAiFCQQMhQyBB", + "IEN0IUQgQiBEaiFFIEUpAwAh2gMgBSkDQCHbAyDbAyDaA4Uh3AMgBSDcAzcDQCAFKQMYId0DQggh3gMg3QM", + "g3gOIId8DIAUg3wM3AxggBSkDECHgA0L/ASHhAyDgAyDhA4Mh4gNCgAwh4wMg4gMg4wN8IeQDIOQDpyFGQY", + "CAwAIhR0EDIUggRiBIdCFJIEcgSWohSiBKKQMAIeUDIAUpAzgh5gMg5gMg5QOFIecDIAUg5wM3AzggBSkDE", + "CHoA0IIIekDIOgDIOkDiCHqAyAFIOoDNwMQIAUpAygh6wNC/wEh7AMg6wMg7AODIe0DQoAKIe4DIO0DIO4D", + "fCHvAyDvA6chS0GAgMACIUxBAyFNIEsgTXQhTiBMIE5qIU8gTykDACHwAyAFKQNQIfEDIPEDIPADhSHyAyA", + "FIPIDNwNQIAUpAygh8wNCCCH0AyDzAyD0A4gh9QMgBSD1AzcDKCAFKQMgIfYDQv8BIfcDIPYDIPcDgyH4A0", + "KACiH5AyD4AyD5A3wh+gMg+gOnIVBBgIDAAiFRQQMhUiBQIFJ0IVMgUSBTaiFUIFQpAwAh+wMgBSkDSCH8A", + "yD8AyD7A4Uh/QMgBSD9AzcDSCAFKQMgIf4DQggh/wMg/gMg/wOIIYAEIAUggAQ3AyAgBSkDGCGBBEL/ASGC", + "BCCBBCCCBIMhgwRCgAohhAQggwQghAR8IYUEIIUEpyFVQYCAwAIhVkEDIVcgVSBXdCFYIFYgWGohWSBZKQM", + "AIYYEIAUpA0AhhwQghwQghgSFIYgEIAUgiAQ3A0AgBSkDGCGJBEIIIYoEIIkEIIoEiCGLBCAFIIsENwMYIA", + "UpAxAhjARC/wEhjQQgjAQgjQSDIY4EQoAKIY8EII4EII8EfCGQBCCQBKchWkGAgMACIVtBAyFcIFogXHQhX", + "SBbIF1qIV4gXikDACGRBCAFKQM4IZIEIJIEIJEEhSGTBCAFIJMENwM4IAUpAxAhlARCCCGVBCCUBCCVBIgh", + "lgQgBSCWBDcDECAFKQMoIZcEQv8BIZgEIJcEIJgEgyGZBEKACCGaBCCZBCCaBHwhmwQgmwSnIV9BgIDAAiF", + "gQQMhYSBfIGF0IWIgYCBiaiFjIGMpAwAhnAQgBSkDUCGdBCCdBCCcBIUhngQgBSCeBDcDUCAFKQMoIZ8EQg", + "ghoAQgnwQgoASIIaEEIAUgoQQ3AyggBSkDICGiBEL/ASGjBCCiBCCjBIMhpARCgAghpQQgpAQgpQR8IaYEI", + "KYEpyFkQYCAwAIhZUEDIWYgZCBmdCFnIGUgZ2ohaCBoKQMAIacEIAUpA0ghqAQgqAQgpwSFIakEIAUgqQQ3", + "A0ggBSkDICGqBEIIIasEIKoEIKsEiCGsBCAFIKwENwMgIAUpAxghrQRC/wEhrgQgrQQgrgSDIa8EQoAIIbA", + "EIK8EILAEfCGxBCCxBKchaUGAgMACIWpBAyFrIGkga3QhbCBqIGxqIW0gbSkDACGyBCAFKQNAIbMEILMEIL", + "IEhSG0BCAFILQENwNAIAUpAxghtQRCCCG2BCC1BCC2BIghtwQgBSC3BDcDGCAFKQMQIbgEQv8BIbkEILgEI", + "LkEgyG6BEKACCG7BCC6BCC7BHwhvAQgvASnIW5BgIDAAiFvQQMhcCBuIHB0IXEgbyBxaiFyIHIpAwAhvQQg", + "BSkDOCG+BCC+BCC9BIUhvwQgBSC/BDcDOCAFKQMQIcAEQgghwQQgwAQgwQSIIcIEIAUgwgQ3AxAgBSkDKCH", + "DBEL/ASHEBCDDBCDEBIMhxQRCgAYhxgQgxQQgxgR8IccEIMcEpyFzQYCAwAIhdEEDIXUgcyB1dCF2IHQgdm", + "ohdyB3KQMAIcgEIAUpA1AhyQQgyQQgyASFIcoEIAUgygQ3A1AgBSkDKCHLBEIIIcwEIMsEIMwEiCHNBCAFI", + "M0ENwMoIAUpAyAhzgRC/wEhzwQgzgQgzwSDIdAEQoAGIdEEINAEINEEfCHSBCDSBKcheEGAgMACIXlBAyF6", + "IHggenQheyB5IHtqIXwgfCkDACHTBCAFKQNIIdQEINQEINMEhSHVBCAFINUENwNIIAUpAyAh1gRCCCHXBCD", + "WBCDXBIgh2AQgBSDYBDcDICAFKQMYIdkEQv8BIdoEINkEINoEgyHbBEKABiHcBCDbBCDcBHwh3QQg3QSnIX", + "1BgIDAAiF+QQMhfyB9IH90IYABIH4ggAFqIYEBIIEBKQMAId4EIAUpA0Ah3wQg3wQg3gSFIeAEIAUg4AQ3A", + "0AgBSkDGCHhBEIIIeIEIOEEIOIEiCHjBCAFIOMENwMYIAUpAxAh5ARC/wEh5QQg5AQg5QSDIeYEQoAGIecE", + "IOYEIOcEfCHoBCDoBKchggFBgIDAAiGDAUEDIYQBIIIBIIQBdCGFASCDASCFAWohhgEghgEpAwAh6QQgBSk", + "DOCHqBCDqBCDpBIUh6wQgBSDrBDcDOCAFKQMQIewEQggh7QQg7AQg7QSIIe4EIAUg7gQ3AxAgBSkDKCHvBE", + "L/ASHwBCDvBCDwBIMh8QRCgAQh8gQg8QQg8gR8IfMEIPMEpyGHAUGAgMACIYgBQQMhiQEghwEgiQF0IYoBI", + "IgBIIoBaiGLASCLASkDACH0BCAFKQNQIfUEIPUEIPQEhSH2BCAFIPYENwNQIAUpAygh9wRCCCH4BCD3BCD4", + "BIgh+QQgBSD5BDcDKCAFKQMgIfoEQv8BIfsEIPoEIPsEgyH8BEKABCH9BCD8BCD9BHwh/gQg/gSnIYwBQYC", + "AwAIhjQFBAyGOASCMASCOAXQhjwEgjQEgjwFqIZABIJABKQMAIf8EIAUpA0ghgAUggAUg/wSFIYEFIAUggQ", + "U3A0ggBSkDICGCBUIIIYMFIIIFIIMFiCGEBSAFIIQFNwMgIAUpAxghhQVC/wEhhgUghQUghgWDIYcFQoAEI", + "YgFIIcFIIgFfCGJBSCJBachkQFBgIDAAiGSAUEDIZMBIJEBIJMBdCGUASCSASCUAWohlQEglQEpAwAhigUg", + "BSkDQCGLBSCLBSCKBYUhjAUgBSCMBTcDQCAFKQMYIY0FQgghjgUgjQUgjgWIIY8FIAUgjwU3AxggBSkDECG", + "QBUL/ASGRBSCQBSCRBYMhkgVCgAQhkwUgkgUgkwV8IZQFIJQFpyGWAUGAgMACIZcBQQMhmAEglgEgmAF0IZ", + "kBIJcBIJkBaiGaASCaASkDACGVBSAFKQM4IZYFIJYFIJUFhSGXBSAFIJcFNwM4IAUpAxAhmAVCCCGZBSCYB", + "SCZBYghmgUgBSCaBTcDECAFKQMoIZsFQv8BIZwFIJsFIJwFgyGdBUKAAiGeBSCdBSCeBXwhnwUgnwWnIZsB", + "QYCAwAIhnAFBAyGdASCbASCdAXQhngEgnAEgngFqIZ8BIJ8BKQMAIaAFIAUpA1AhoQUgoQUgoAWFIaIFIAU", + "gogU3A1AgBSkDKCGjBUIIIaQFIKMFIKQFiCGlBSAFIKUFNwMoIAUpAyAhpgVC/wEhpwUgpgUgpwWDIagFQo", + "ACIakFIKgFIKkFfCGqBSCqBachoAFBgIDAAiGhAUEDIaIBIKABIKIBdCGjASChASCjAWohpAEgpAEpAwAhq", + "wUgBSkDSCGsBSCsBSCrBYUhrQUgBSCtBTcDSCAFKQMgIa4FQgghrwUgrgUgrwWIIbAFIAUgsAU3AyAgBSkD", + "GCGxBUL/ASGyBSCxBSCyBYMhswVCgAIhtAUgswUgtAV8IbUFILUFpyGlAUGAgMACIaYBQQMhpwEgpQEgpwF", + "0IagBIKYBIKgBaiGpASCpASkDACG2BSAFKQNAIbcFILcFILYFhSG4BSAFILgFNwNAIAUpAxghuQVCCCG6BS", + "C5BSC6BYghuwUgBSC7BTcDGCAFKQMQIbwFQv8BIb0FILwFIL0FgyG+BUKAAiG/BSC+BSC/BXwhwAUgwAWnI", + "aoBQYCAwAIhqwFBAyGsASCqASCsAXQhrQEgqwEgrQFqIa4BIK4BKQMAIcEFIAUpAzghwgUgwgUgwQWFIcMF", + "IAUgwwU3AzggBSkDECHEBUIIIcUFIMQFIMUFiCHGBSAFIMYFNwMQIAUpAyghxwVC/wEhyAUgxwUgyAWDIck", + "FQgAhygUgyQUgygV8IcsFIMsFpyGvAUGAgMACIbABQQMhsQEgrwEgsQF0IbIBILABILIBaiGzASCzASkDAC", + "HMBSAFKQNQIc0FIM0FIMwFhSHOBSAFIM4FNwNQIAUpAyAhzwVC/wEh0AUgzwUg0AWDIdEFQgAh0gUg0QUg0", + "gV8IdMFINMFpyG0AUGAgMACIbUBQQMhtgEgtAEgtgF0IbcBILUBILcBaiG4ASC4ASkDACHUBSAFKQNIIdUF", + "INUFINQFhSHWBSAFINYFNwNIIAUpAxgh1wVC/wEh2AUg1wUg2AWDIdkFQgAh2gUg2QUg2gV8IdsFINsFpyG", + "5AUGAgMACIboBQQMhuwEguQEguwF0IbwBILoBILwBaiG9ASC9ASkDACHcBSAFKQNAId0FIN0FINwFhSHeBS", + "AFIN4FNwNAIAUpAxAh3wVC/wEh4AUg3wUg4AWDIeEFQgAh4gUg4QUg4gV8IeMFIOMFpyG+AUGAgMACIb8BQ", + "QMhwAEgvgEgwAF0IcEBIL8BIMEBaiHCASDCASkDACHkBSAFKQM4IeUFIOUFIOQFhSHmBSAFIOYFNwM4IAUp", + "A2Ah5wVCICHoBSDnBSDoBXwh6QUgBSDpBTcDYCAFKAJYIcMBQSAhxAEgwwEgxAFqIcUBIAUgxQE2AlgMAAs", + "AC0IAIeoFIAUg6gU3A2ggBSgCWCHGASDGASkDACHrBSAFKQNQIewFIOsFIOwFhSHtBSAFKQNoIe4FIO4FIO", + "0FhSHvBSAFIO8FNwNoIAUpA2gh8AVCCCHxBSDwBSDxBYgh8gUgBSkDaCHzBUL/ASH0BSDzBSD0BYMh9QUg9", + "QWnIccBQYCAwQIhyAFBAyHJASDHASDJAXQhygEgyAEgygFqIcsBIMsBKQMAIfYFIPIFIPYFhSH3BSAFIPcF", + "NwNoIAUpA2gh+AVCCCH5BSD4BSD5BYgh+gUgBSkDaCH7BUL/ASH8BSD7BSD8BYMh/QUg/QWnIcwBQYCAwQI", + "hzQFBAyHOASDMASDOAXQhzwEgzQEgzwFqIdABINABKQMAIf4FIPoFIP4FhSH/BSAFIP8FNwNoIAUpA2ghgA", + "ZCCCGBBiCABiCBBoghggYgBSkDaCGDBkL/ASGEBiCDBiCEBoMhhQYghQanIdEBQYCAwQIh0gFBAyHTASDRA", + "SDTAXQh1AEg0gEg1AFqIdUBINUBKQMAIYYGIIIGIIYGhSGHBiAFIIcGNwNoIAUpA2ghiAZCCCGJBiCIBiCJ", + "BoghigYgBSkDaCGLBkL/ASGMBiCLBiCMBoMhjQYgjQanIdYBQYCAwQIh1wFBAyHYASDWASDYAXQh2QEg1wE", + "g2QFqIdoBINoBKQMAIY4GIIoGII4GhSGPBiAFII8GNwNoIAUpA2ghkAZCCCGRBiCQBiCRBoghkgYgBSkDaC", + "GTBkL/ASGUBiCTBiCUBoMhlQYglQanIdsBQYCAwQIh3AFBAyHdASDbASDdAXQh3gEg3AEg3gFqId8BIN8BK", + "QMAIZYGIJIGIJYGhSGXBiAFIJcGNwNoIAUpA2ghmAZCCCGZBiCYBiCZBoghmgYgBSkDaCGbBkL/ASGcBiCb", + "BiCcBoMhnQYgnQanIeABQYCAwQIh4QFBAyHiASDgASDiAXQh4wEg4QEg4wFqIeQBIOQBKQMAIZ4GIJoGIJ4", + "GhSGfBiAFIJ8GNwNoIAUpA2ghoAZCCCGhBiCgBiChBoghogYgBSkDaCGjBkL/ASGkBiCjBiCkBoMhpQYgpQ", + "anIeUBQYCAwQIh5gFBAyHnASDlASDnAXQh6AEg5gEg6AFqIekBIOkBKQMAIaYGIKIGIKYGhSGnBiAFIKcGN", + "wNoIAUpA2ghqAZCCCGpBiCoBiCpBoghqgYgBSkDaCGrBkL/ASGsBiCrBiCsBoMhrQYgrQanIeoBQYCAwQIh", + "6wFBAyHsASDqASDsAXQh7QEg6wEg7QFqIe4BIO4BKQMAIa4GIKoGIK4GhSGvBiAFIK8GNwNoIAUoAlgh7wE", + "g7wEpAwghsAYgBSkDSCGxBiCwBiCxBoUhsgYgBSkDaCGzBiCzBiCyBoUhtAYgBSC0BjcDaCAFKQNoIbUGQg", + "ghtgYgtQYgtgaIIbcGIAUpA2ghuAZC/wEhuQYguAYguQaDIboGILoGpyHwAUGAgMECIfEBQQMh8gEg8AEg8", + "gF0IfMBIPEBIPMBaiH0ASD0ASkDACG7BiC3BiC7BoUhvAYgBSC8BjcDaCAFKQNoIb0GQgghvgYgvQYgvgaI", + "Ib8GIAUpA2ghwAZC/wEhwQYgwAYgwQaDIcIGIMIGpyH1AUGAgMECIfYBQQMh9wEg9QEg9wF0IfgBIPYBIPg", + "BaiH5ASD5ASkDACHDBiC/BiDDBoUhxAYgBSDEBjcDaCAFKQNoIcUGQgghxgYgxQYgxgaIIccGIAUpA2ghyA", + "ZC/wEhyQYgyAYgyQaDIcoGIMoGpyH6AUGAgMECIfsBQQMh/AEg+gEg/AF0If0BIPsBIP0BaiH+ASD+ASkDA", + "CHLBiDHBiDLBoUhzAYgBSDMBjcDaCAFKQNoIc0GQgghzgYgzQYgzgaIIc8GIAUpA2gh0AZC/wEh0QYg0AYg", + "0QaDIdIGINIGpyH/AUGAgMECIYACQQMhgQIg/wEggQJ0IYICIIACIIICaiGDAiCDAikDACHTBiDPBiDTBoU", + "h1AYgBSDUBjcDaCAFKQNoIdUGQggh1gYg1QYg1gaIIdcGIAUpA2gh2AZC/wEh2QYg2AYg2QaDIdoGINoGpy", + "GEAkGAgMECIYUCQQMhhgIghAIghgJ0IYcCIIUCIIcCaiGIAiCIAikDACHbBiDXBiDbBoUh3AYgBSDcBjcDa", + "CAFKQNoId0GQggh3gYg3QYg3gaIId8GIAUpA2gh4AZC/wEh4QYg4AYg4QaDIeIGIOIGpyGJAkGAgMECIYoC", + "QQMhiwIgiQIgiwJ0IYwCIIoCIIwCaiGNAiCNAikDACHjBiDfBiDjBoUh5AYgBSDkBjcDaCAFKQNoIeUGQgg", + "h5gYg5QYg5gaIIecGIAUpA2gh6AZC/wEh6QYg6AYg6QaDIeoGIOoGpyGOAkGAgMECIY8CQQMhkAIgjgIgkA", + "J0IZECII8CIJECaiGSAiCSAikDACHrBiDnBiDrBoUh7AYgBSDsBjcDaCAFKQNoIe0GQggh7gYg7QYg7gaII", + "e8GIAUpA2gh8AZC/wEh8QYg8AYg8QaDIfIGIPIGpyGTAkGAgMECIZQCQQMhlQIgkwIglQJ0IZYCIJQCIJYC", + "aiGXAiCXAikDACHzBiDvBiDzBoUh9AYgBSD0BjcDaCAFKAJYIZgCIJgCKQMQIfUGIAUpA0Ah9gYg9QYg9ga", + "FIfcGIAUpA2gh+AYg+AYg9waFIfkGIAUg+QY3A2ggBSkDaCH6BkIIIfsGIPoGIPsGiCH8BiAFKQNoIf0GQv", + "8BIf4GIP0GIP4GgyH/BiD/BqchmQJBgIDBAiGaAkEDIZsCIJkCIJsCdCGcAiCaAiCcAmohnQIgnQIpAwAhg", + "Acg/AYggAeFIYEHIAUggQc3A2ggBSkDaCGCB0IIIYMHIIIHIIMHiCGEByAFKQNoIYUHQv8BIYYHIIUHIIYH", + "gyGHByCHB6chngJBgIDBAiGfAkEDIaACIJ4CIKACdCGhAiCfAiChAmohogIgogIpAwAhiAcghAcgiAeFIYk", + "HIAUgiQc3A2ggBSkDaCGKB0IIIYsHIIoHIIsHiCGMByAFKQNoIY0HQv8BIY4HII0HII4HgyGPByCPB6chow", + "JBgIDBAiGkAkEDIaUCIKMCIKUCdCGmAiCkAiCmAmohpwIgpwIpAwAhkAcgjAcgkAeFIZEHIAUgkQc3A2ggB", + "SkDaCGSB0IIIZMHIJIHIJMHiCGUByAFKQNoIZUHQv8BIZYHIJUHIJYHgyGXByCXB6chqAJBgIDBAiGpAkED", + "IaoCIKgCIKoCdCGrAiCpAiCrAmohrAIgrAIpAwAhmAcglAcgmAeFIZkHIAUgmQc3A2ggBSkDaCGaB0IIIZs", + "HIJoHIJsHiCGcByAFKQNoIZ0HQv8BIZ4HIJ0HIJ4HgyGfByCfB6chrQJBgIDBAiGuAkEDIa8CIK0CIK8CdC", + "GwAiCuAiCwAmohsQIgsQIpAwAhoAcgnAcgoAeFIaEHIAUgoQc3A2ggBSkDaCGiB0IIIaMHIKIHIKMHiCGkB", + "yAFKQNoIaUHQv8BIaYHIKUHIKYHgyGnByCnB6chsgJBgIDBAiGzAkEDIbQCILICILQCdCG1AiCzAiC1Amoh", + "tgIgtgIpAwAhqAcgpAcgqAeFIakHIAUgqQc3A2ggBSkDaCGqB0IIIasHIKoHIKsHiCGsByAFKQNoIa0HQv8", + "BIa4HIK0HIK4HgyGvByCvB6chtwJBgIDBAiG4AkEDIbkCILcCILkCdCG6AiC4AiC6AmohuwIguwIpAwAhsA", + "cgrAcgsAeFIbEHIAUgsQc3A2ggBSkDaCGyB0IIIbMHILIHILMHiCG0ByAFKQNoIbUHQv8BIbYHILUHILYHg", + "yG3ByC3B6chvAJBgIDBAiG9AkEDIb4CILwCIL4CdCG/AiC9AiC/AmohwAIgwAIpAwAhuAcgtAcguAeFIbkH", + "IAUguQc3A2ggBSgCWCHBAiDBAikDGCG6ByAFKQM4IbsHILoHILsHhSG8ByAFKQNoIb0HIL0HILwHhSG+ByA", + "FIL4HNwNoIAUpA2ghvwdCCCHAByC/ByDAB4ghwQcgBSkDaCHCB0L/ASHDByDCByDDB4MhxAcgxAenIcICQY", + "CAwQIhwwJBAyHEAiDCAiDEAnQhxQIgwwIgxQJqIcYCIMYCKQMAIcUHIMEHIMUHhSHGByAFIMYHNwNoIAUpA", + "2ghxwdCCCHIByDHByDIB4ghyQcgBSkDaCHKB0L/ASHLByDKByDLB4MhzAcgzAenIccCQYCAwQIhyAJBAyHJ", + "AiDHAiDJAnQhygIgyAIgygJqIcsCIMsCKQMAIc0HIMkHIM0HhSHOByAFIM4HNwNoIAUpA2ghzwdCCCHQByD", + "PByDQB4gh0QcgBSkDaCHSB0L/ASHTByDSByDTB4Mh1Acg1AenIcwCQYCAwQIhzQJBAyHOAiDMAiDOAnQhzw", + "IgzQIgzwJqIdACINACKQMAIdUHINEHINUHhSHWByAFINYHNwNoIAUpA2gh1wdCCCHYByDXByDYB4gh2QcgB", + "SkDaCHaB0L/ASHbByDaByDbB4Mh3Acg3AenIdECQYCAwQIh0gJBAyHTAiDRAiDTAnQh1AIg0gIg1AJqIdUC", + "INUCKQMAId0HINkHIN0HhSHeByAFIN4HNwNoIAUpA2gh3wdCCCHgByDfByDgB4gh4QcgBSkDaCHiB0L/ASH", + "jByDiByDjB4Mh5Acg5AenIdYCQYCAwQIh1wJBAyHYAiDWAiDYAnQh2QIg1wIg2QJqIdoCINoCKQMAIeUHIO", + "EHIOUHhSHmByAFIOYHNwNoIAUpA2gh5wdCCCHoByDnByDoB4gh6QcgBSkDaCHqB0L/ASHrByDqByDrB4Mh7", + "Acg7AenIdsCQYCAwQIh3AJBAyHdAiDbAiDdAnQh3gIg3AIg3gJqId8CIN8CKQMAIe0HIOkHIO0HhSHuByAF", + "IO4HNwNoIAUpA2gh7wdCCCHwByDvByDwB4gh8QcgBSkDaCHyB0L/ASHzByDyByDzB4Mh9Acg9AenIeACQYC", + "AwQIh4QJBAyHiAiDgAiDiAnQh4wIg4QIg4wJqIeQCIOQCKQMAIfUHIPEHIPUHhSH2ByAFIPYHNwNoIAUpA2", + "gh9wdCCCH4ByD3ByD4B4gh+QcgBSkDaCH6B0L/ASH7ByD6ByD7B4Mh/Acg/AenIeUCQYCAwQIh5gJBAyHnA", + "iDlAiDnAnQh6AIg5gIg6AJqIekCIOkCKQMAIf0HIPkHIP0HhSH+ByAFIP4HNwNoIAUpA2Ah/wdCICGACCD/", + "ByCACHwhgQggBSCBCDcDYAtCACGCCCAFIIIINwMIAkADQCAFKQMIIYMIIAUoAnQh6gIg6gIh6wIg6wKsIYQ", + "IIIMIIYUIIIQIIYYIIIUIIIYIVCHsAkEBIe0CIOwCIO0CcSHuAiDuAkUNASAFKQNoIYcIQgghiAgghwggiA", + "iIIYkIIAUpA2ghigggBSgCcCHvAiAFKQNgIYsIIIsIpyHwAiDvAiDwAmoh8QIg8QItAAAh8gJB/wEh8wIg8", + "gIg8wJxIfQCIPQCrSGMCCCKCCCMCIUhjQhC/wEhjgggjQggjgiDIY8III8IpyH1AkGAgMECIfYCQQMh9wIg", + "9QIg9wJ0IfgCIPYCIPgCaiH5AiD5AikDACGQCCCJCCCQCIUhkQggBSCRCDcDaCAFKQMIIZIIQgEhkwggkgg", + "gkwh8IZQIIAUglAg3AwggBSkDYCGVCEIBIZYIIJUIIJYIfCGXCCAFIJcINwNgDAALAAsgBSkDaCGYCEJ/IZ", + "kIIJgIIJkIhSGaCCAGIJoINwMADwudAgIcfwV+IwAhBEEgIQUgBCAFayEGIAYkACAGIAA2AhwgBiABNgIYI", + "AYgAjYCFCAGIAM2AhAgBigCHCEHIAYoAhghCCAGKAIUIQkgByAIIAkQBiAGKAIQIQogBiAKNgIMQQAhCyAG", + "IAs2AggCQANAIAYoAgghDEEIIQ0gDCEOIA0hDyAOIA9JIRBBASERIBAgEXEhEiASRQ0BIAcpAwAhICAGKAI", + "IIRNBAyEUIBMgFHQhFSAVIRYgFq0hISAgICGIISJC/wEhIyAiICODISQgJKchFyAGKAIMIRggBigCCCEZIB", + "ggGWohGiAaIBc6AAAgBigCCCEbQQEhHCAbIBxqIR0gBiAdNgIIDAALAAtBICEeIAYgHmohHyAfJAAPC14BD", + "H8jACEBQRAhAiABIAJrIQMgAyQAIAMgADYCDCADKAIMIQRBACEFIAQhBiAFIQcgBiAHRiEIQQEhCSAIIAlx", + "IQoCQCAKDQAgBBAUC0EQIQsgAyALaiEMIAwkAA8LNQIEfwF+QRAhACAAEBMhAUIAIQQgASAENwMAQQghAiA", + "BIAJqIQMgAyAENwMAIAEQChogAQ8LPAIEfwJ+IwAhAUEQIQIgASACayEDIAMgADYCDCADKAIMIQRCACEFIA", + "QgBTcDAEIAIQYgBCAGNwMIIAQPC1kBCH8jACEDQRAhBCADIARrIQUgBSQAIAUgADYCDCAFIAE2AgggBSACN", + "gIEIAUoAgwhBiAFKAIIIQcgBSgCBCEIIAYgByAIEAZBECEJIAUgCWohCiAKJAAPC2kBCX8jACEEQRAhBSAE", + "IAVrIQYgBiQAIAYgADYCDCAGIAE2AgggBiACNgIEIAYgAzYCACAGKAIMIQcgBigCCCEIIAYoAgQhCSAGKAI", + "AIQogByAIIAkgChAHQRAhCyAGIAtqIQwgDCQADwteAQx/IwAhAUEQIQIgASACayEDIAMkACADIAA2AgwgAy", + "gCDCEEQQAhBSAEIQYgBSEHIAYgB0YhCEEBIQkgCCAJcSEKAkAgCg0AIAQQFAtBECELIAMgC2ohDCAMJAAPC", + "wcAPwBBEHQLBwBBlJLBAgtUAQJ/QQAoAoCQwQIiASAAQQdqQXhxIgJqIQACQAJAIAJFDQAgACABTQ0BCwJA", + "IAAQDk0NACAAEAFFDQELQQAgADYCgJDBAiABDwsQD0EwNgIAQX8LviwBC38jAEEQayIBJAACQAJAAkACQAJ", + "AAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AUsNAAJAQQAoApiSwQIiAkEQIABBC2pBeHEgAEELSRsiA0EDdi", + "IEdiIAQQNxRQ0AAkACQCAAQX9zQQFxIARqIgVBA3QiBEHAksECaiIAIARByJLBAmooAgAiBCgCCCIDRw0AQ", + "QAgAkF+IAV3cTYCmJLBAgwBCyADIAA2AgwgACADNgIICyAEQQhqIQAgBCAFQQN0IgVBA3I2AgQgBCAFaiIE", + "IAQoAgRBAXI2AgQMDwsgA0EAKAKgksECIgZNDQECQCAARQ0AAkACQCAAIAR0QQIgBHQiAEEAIABrcnEiAEE", + "AIABrcWgiBEEDdCIAQcCSwQJqIgUgAEHIksECaigCACIAKAIIIgdHDQBBACACQX4gBHdxIgI2ApiSwQIMAQ", + "sgByAFNgIMIAUgBzYCCAsgACADQQNyNgIEIAAgA2oiByAEQQN0IgQgA2siBUEBcjYCBCAAIARqIAU2AgACQ", + "CAGRQ0AIAZBeHFBwJLBAmohA0EAKAKsksECIQQCQAJAIAJBASAGQQN2dCIIcQ0AQQAgAiAIcjYCmJLBAiAD", + "IQgMAQsgAygCCCEICyADIAQ2AgggCCAENgIMIAQgAzYCDCAEIAg2AggLIABBCGohAEEAIAc2AqySwQJBACA", + "FNgKgksECDA8LQQAoApySwQIiCUUNASAJQQAgCWtxaEECdEHIlMECaigCACIHKAIEQXhxIANrIQQgByEFAk", + "ADQAJAIAUoAhAiAA0AIAVBFGooAgAiAEUNAgsgACgCBEF4cSADayIFIAQgBSAESSIFGyEEIAAgByAFGyEHI", + "AAhBQwACwALIAcoAhghCgJAIAcoAgwiCCAHRg0AIAcoAggiAEEAKAKoksECSRogACAINgIMIAggADYCCAwO", + "CwJAIAdBFGoiBSgCACIADQAgBygCECIARQ0DIAdBEGohBQsDQCAFIQsgACIIQRRqIgUoAgAiAA0AIAhBEGo", + "hBSAIKAIQIgANAAsgC0EANgIADA0LQX8hAyAAQb9/Sw0AIABBC2oiAEF4cSEDQQAoApySwQIiBkUNAEEAIQ", + "sCQCADQYACSQ0AQR8hCyADQf///wdLDQAgA0EmIABBCHZnIgBrdkEBcSAAQQF0a0E+aiELC0EAIANrIQQCQ", + "AJAAkACQCALQQJ0QciUwQJqKAIAIgUNAEEAIQBBACEIDAELQQAhACADQQBBGSALQQF2ayALQR9GG3QhB0EA", + "IQgDQAJAIAUoAgRBeHEgA2siAiAETw0AIAIhBCAFIQggAg0AQQAhBCAFIQggBSEADAMLIAAgBUEUaigCACI", + "CIAIgBSAHQR12QQRxakEQaigCACIFRhsgACACGyEAIAdBAXQhByAFDQALCwJAIAAgCHINAEEAIQhBAiALdC", + "IAQQAgAGtyIAZxIgBFDQMgAEEAIABrcWhBAnRByJTBAmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIANrIgIgB", + "EkhBwJAIAAoAhAiBQ0AIABBFGooAgAhBQsgAiAEIAcbIQQgACAIIAcbIQggBSEAIAUNAAsLIAhFDQAgBEEA", + "KAKgksECIANrTw0AIAgoAhghCwJAIAgoAgwiByAIRg0AIAgoAggiAEEAKAKoksECSRogACAHNgIMIAcgADY", + "CCAwMCwJAIAhBFGoiBSgCACIADQAgCCgCECIARQ0DIAhBEGohBQsDQCAFIQIgACIHQRRqIgUoAgAiAA0AIA", + "dBEGohBSAHKAIQIgANAAsgAkEANgIADAsLAkBBACgCoJLBAiIAIANJDQBBACgCrJLBAiEEAkACQCAAIANrI", + "gVBEEkNAEEAIAU2AqCSwQJBACAEIANqIgc2AqySwQIgByAFQQFyNgIEIAQgAGogBTYCACAEIANBA3I2AgQM", + "AQtBAEEANgKsksECQQBBADYCoJLBAiAEIABBA3I2AgQgBCAAaiIAIAAoAgRBAXI2AgQLIARBCGohAAwNCwJ", + "AQQAoAqSSwQIiByADTQ0AQQAgByADayIENgKkksECQQBBACgCsJLBAiIAIANqIgU2ArCSwQIgBSAEQQFyNg", + "IEIAAgA0EDcjYCBCAAQQhqIQAMDQsCQAJAQQAoAvCVwQJFDQBBACgC+JXBAiEEDAELQQBCfzcC/JXBAkEAQ", + "oCggICAgAQ3AvSVwQJBACABQQxqQXBxQdiq1aoFczYC8JXBAkEAQQA2AoSWwQJBAEEANgLUlcECQYAgIQQL", + "QQAhACAEIANBL2oiBmoiAkEAIARrIgtxIgggA00NDEEAIQACQEEAKALQlcECIgRFDQBBACgCyJXBAiIFIAh", + "qIgkgBU0NDSAJIARLDQ0LAkACQEEALQDUlcECQQRxDQACQAJAAkACQAJAQQAoArCSwQIiBEUNAEHYlcECIQ", + "ADQAJAIAAoAgAiBSAESw0AIAUgACgCBGogBEsNAwsgACgCCCIADQALC0EAEBAiB0F/Rg0DIAghAgJAQQAoA", + "vSVwQIiAEF/aiIEIAdxRQ0AIAggB2sgBCAHakEAIABrcWohAgsgAiADTQ0DAkBBACgC0JXBAiIARQ0AQQAo", + "AsiVwQIiBCACaiIFIARNDQQgBSAASw0ECyACEBAiACAHRw0BDAULIAIgB2sgC3EiAhAQIgcgACgCACAAKAI", + "EakYNASAHIQALIABBf0YNAQJAIANBMGogAksNACAAIQcMBAsgBiACa0EAKAL4lcECIgRqQQAgBGtxIgQQEE", + "F/Rg0BIAQgAmohAiAAIQcMAwsgB0F/Rw0CC0EAQQAoAtSVwQJBBHI2AtSVwQILIAgQECEHQQAQECEAIAdBf", + "0YNBSAAQX9GDQUgByAATw0FIAAgB2siAiADQShqTQ0FC0EAQQAoAsiVwQIgAmoiADYCyJXBAgJAIABBACgC", + "zJXBAk0NAEEAIAA2AsyVwQILAkACQEEAKAKwksECIgRFDQBB2JXBAiEAA0AgByAAKAIAIgUgACgCBCIIakY", + "NAiAAKAIIIgANAAwFCwALAkACQEEAKAKoksECIgBFDQAgByAATw0BC0EAIAc2AqiSwQILQQAhAEEAIAI2At", + "yVwQJBACAHNgLYlcECQQBBfzYCuJLBAkEAQQAoAvCVwQI2ArySwQJBAEEANgLklcECA0AgAEEDdCIEQciSw", + "QJqIARBwJLBAmoiBTYCACAEQcySwQJqIAU2AgAgAEEBaiIAQSBHDQALQQAgAkFYaiIAQXggB2tBB3FBACAH", + "QQhqQQdxGyIEayIFNgKkksECQQAgByAEaiIENgKwksECIAQgBUEBcjYCBCAHIABqQSg2AgRBAEEAKAKAlsE", + "CNgK0ksECDAQLIAAtAAxBCHENAiAEIAVJDQIgBCAHTw0CIAAgCCACajYCBEEAIARBeCAEa0EHcUEAIARBCG", + "pBB3EbIgBqIgU2ArCSwQJBAEEAKAKkksECIAJqIgcgAGsiADYCpJLBAiAFIABBAXI2AgQgBCAHakEoNgIEQ", + "QBBACgCgJbBAjYCtJLBAgwDC0EAIQgMCgtBACEHDAgLAkAgB0EAKAKoksECIghPDQBBACAHNgKoksECIAch", + "CAsgByACaiEFQdiVwQIhAAJAAkACQAJAA0AgACgCACAFRg0BIAAoAggiAA0ADAILAAsgAC0ADEEIcUUNAQt", + "B2JXBAiEAA0ACQCAAKAIAIgUgBEsNACAFIAAoAgRqIgUgBEsNAwsgACgCCCEADAALAAsgACAHNgIAIAAgAC", + "gCBCACajYCBCAHQXggB2tBB3FBACAHQQhqQQdxG2oiCyADQQNyNgIEIAVBeCAFa0EHcUEAIAVBCGpBB3Eba", + "iICIAsgA2oiA2shAAJAIAIgBEcNAEEAIAM2ArCSwQJBAEEAKAKkksECIABqIgA2AqSSwQIgAyAAQQFyNgIE", + "DAgLAkAgAkEAKAKsksECRw0AQQAgAzYCrJLBAkEAQQAoAqCSwQIgAGoiADYCoJLBAiADIABBAXI2AgQgAyA", + "AaiAANgIADAgLIAIoAgQiBEEDcUEBRw0GIARBeHEhBgJAIARB/wFLDQAgAigCCCIFIARBA3YiCEEDdEHAks", + "ECaiIHRhoCQCACKAIMIgQgBUcNAEEAQQAoApiSwQJBfiAId3E2ApiSwQIMBwsgBCAHRhogBSAENgIMIAQgB", + "TYCCAwGCyACKAIYIQkCQCACKAIMIgcgAkYNACACKAIIIgQgCEkaIAQgBzYCDCAHIAQ2AggMBQsCQCACQRRq", + "IgUoAgAiBA0AIAIoAhAiBEUNBCACQRBqIQULA0AgBSEIIAQiB0EUaiIFKAIAIgQNACAHQRBqIQUgBygCECI", + "EDQALIAhBADYCAAwEC0EAIAJBWGoiAEF4IAdrQQdxQQAgB0EIakEHcRsiCGsiCzYCpJLBAkEAIAcgCGoiCD", + "YCsJLBAiAIIAtBAXI2AgQgByAAakEoNgIEQQBBACgCgJbBAjYCtJLBAiAEIAVBJyAFa0EHcUEAIAVBWWpBB", + "3EbakFRaiIAIAAgBEEQakkbIghBGzYCBCAIQRBqQQApAuCVwQI3AgAgCEEAKQLYlcECNwIIQQAgCEEIajYC", + "4JXBAkEAIAI2AtyVwQJBACAHNgLYlcECQQBBADYC5JXBAiAIQRhqIQADQCAAQQc2AgQgAEEIaiEHIABBBGo", + "hACAHIAVJDQALIAggBEYNACAIIAgoAgRBfnE2AgQgBCAIIARrIgdBAXI2AgQgCCAHNgIAAkAgB0H/AUsNAC", + "AHQXhxQcCSwQJqIQACQAJAQQAoApiSwQIiBUEBIAdBA3Z0IgdxDQBBACAFIAdyNgKYksECIAAhBQwBCyAAK", + "AIIIQULIAAgBDYCCCAFIAQ2AgwgBCAANgIMIAQgBTYCCAwBC0EfIQACQCAHQf///wdLDQAgB0EmIAdBCHZn", + "IgBrdkEBcSAAQQF0a0E+aiEACyAEIAA2AhwgBEIANwIQIABBAnRByJTBAmohBQJAAkACQEEAKAKcksECIgh", + "BASAAdCICcQ0AQQAgCCACcjYCnJLBAiAFIAQ2AgAgBCAFNgIYDAELIAdBAEEZIABBAXZrIABBH0YbdCEAIA", + "UoAgAhCANAIAgiBSgCBEF4cSAHRg0CIABBHXYhCCAAQQF0IQAgBSAIQQRxaiICQRBqKAIAIggNAAsgAkEQa", + "iAENgIAIAQgBTYCGAsgBCAENgIMIAQgBDYCCAwBCyAFKAIIIgAgBDYCDCAFIAQ2AgggBEEANgIYIAQgBTYC", + "DCAEIAA2AggLQQAoAqSSwQIiACADTQ0AQQAgACADayIENgKkksECQQBBACgCsJLBAiIAIANqIgU2ArCSwQI", + "gBSAEQQFyNgIEIAAgA0EDcjYCBCAAQQhqIQAMCAsQD0EwNgIAQQAhAAwHC0EAIQcLIAlFDQACQAJAIAIgAi", + "gCHCIFQQJ0QciUwQJqIgQoAgBHDQAgBCAHNgIAIAcNAUEAQQAoApySwQJBfiAFd3E2ApySwQIMAgsgCUEQQ", + "RQgCSgCECACRhtqIAc2AgAgB0UNAQsgByAJNgIYAkAgAigCECIERQ0AIAcgBDYCECAEIAc2AhgLIAJBFGoo", + "AgAiBEUNACAHQRRqIAQ2AgAgBCAHNgIYCyAGIABqIQAgAiAGaiICKAIEIQQLIAIgBEF+cTYCBCADIABBAXI", + "2AgQgAyAAaiAANgIAAkAgAEH/AUsNACAAQXhxQcCSwQJqIQQCQAJAQQAoApiSwQIiBUEBIABBA3Z0IgBxDQ", + "BBACAFIAByNgKYksECIAQhAAwBCyAEKAIIIQALIAQgAzYCCCAAIAM2AgwgAyAENgIMIAMgADYCCAwBC0EfI", + "QQCQCAAQf///wdLDQAgAEEmIABBCHZnIgRrdkEBcSAEQQF0a0E+aiEECyADIAQ2AhwgA0IANwIQIARBAnRB", + "yJTBAmohBQJAAkACQEEAKAKcksECIgdBASAEdCIIcQ0AQQAgByAIcjYCnJLBAiAFIAM2AgAgAyAFNgIYDAE", + "LIABBAEEZIARBAXZrIARBH0YbdCEEIAUoAgAhBwNAIAciBSgCBEF4cSAARg0CIARBHXYhByAEQQF0IQQgBS", + "AHQQRxaiIIQRBqKAIAIgcNAAsgCEEQaiADNgIAIAMgBTYCGAsgAyADNgIMIAMgAzYCCAwBCyAFKAIIIgAgA", + "zYCDCAFIAM2AgggA0EANgIYIAMgBTYCDCADIAA2AggLIAtBCGohAAwCCwJAIAtFDQACQAJAIAggCCgCHCIF", + "QQJ0QciUwQJqIgAoAgBHDQAgACAHNgIAIAcNAUEAIAZBfiAFd3EiBjYCnJLBAgwCCyALQRBBFCALKAIQIAh", + "GG2ogBzYCACAHRQ0BCyAHIAs2AhgCQCAIKAIQIgBFDQAgByAANgIQIAAgBzYCGAsgCEEUaigCACIARQ0AIA", + "dBFGogADYCACAAIAc2AhgLAkACQCAEQQ9LDQAgCCAEIANqIgBBA3I2AgQgCCAAaiIAIAAoAgRBAXI2AgQMA", + "QsgCCADQQNyNgIEIAggA2oiByAEQQFyNgIEIAcgBGogBDYCAAJAIARB/wFLDQAgBEF4cUHAksECaiEAAkAC", + "QEEAKAKYksECIgVBASAEQQN2dCIEcQ0AQQAgBSAEcjYCmJLBAiAAIQQMAQsgACgCCCEECyAAIAc2AgggBCA", + "HNgIMIAcgADYCDCAHIAQ2AggMAQtBHyEAAkAgBEH///8HSw0AIARBJiAEQQh2ZyIAa3ZBAXEgAEEBdGtBPm", + "ohAAsgByAANgIcIAdCADcCECAAQQJ0QciUwQJqIQUCQAJAAkAgBkEBIAB0IgNxDQBBACAGIANyNgKcksECI", + "AUgBzYCACAHIAU2AhgMAQsgBEEAQRkgAEEBdmsgAEEfRht0IQAgBSgCACEDA0AgAyIFKAIEQXhxIARGDQIg", + "AEEddiEDIABBAXQhACAFIANBBHFqIgJBEGooAgAiAw0ACyACQRBqIAc2AgAgByAFNgIYCyAHIAc2AgwgByA", + "HNgIIDAELIAUoAggiACAHNgIMIAUgBzYCCCAHQQA2AhggByAFNgIMIAcgADYCCAsgCEEIaiEADAELAkAgCk", + "UNAAJAAkAgByAHKAIcIgVBAnRByJTBAmoiACgCAEcNACAAIAg2AgAgCA0BQQAgCUF+IAV3cTYCnJLBAgwCC", + "yAKQRBBFCAKKAIQIAdGG2ogCDYCACAIRQ0BCyAIIAo2AhgCQCAHKAIQIgBFDQAgCCAANgIQIAAgCDYCGAsg", + "B0EUaigCACIARQ0AIAhBFGogADYCACAAIAg2AhgLAkACQCAEQQ9LDQAgByAEIANqIgBBA3I2AgQgByAAaiI", + "AIAAoAgRBAXI2AgQMAQsgByADQQNyNgIEIAcgA2oiBSAEQQFyNgIEIAUgBGogBDYCAAJAIAZFDQAgBkF4cU", + "HAksECaiEDQQAoAqySwQIhAAJAAkBBASAGQQN2dCIIIAJxDQBBACAIIAJyNgKYksECIAMhCAwBCyADKAIII", + "QgLIAMgADYCCCAIIAA2AgwgACADNgIMIAAgCDYCCAtBACAFNgKsksECQQAgBDYCoJLBAgsgB0EIaiEACyAB", + "QRBqJAAgAAuDDQEHfwJAIABFDQAgAEF4aiIBIABBfGooAgAiAkF4cSIAaiEDAkAgAkEBcQ0AIAJBA3FFDQE", + "gASABKAIAIgJrIgFBACgCqJLBAiIESQ0BIAIgAGohAAJAAkACQCABQQAoAqySwQJGDQACQCACQf8BSw0AIA", + "EoAggiBCACQQN2IgVBA3RBwJLBAmoiBkYaAkAgASgCDCICIARHDQBBAEEAKAKYksECQX4gBXdxNgKYksECD", + "AULIAIgBkYaIAQgAjYCDCACIAQ2AggMBAsgASgCGCEHAkAgASgCDCIGIAFGDQAgASgCCCICIARJGiACIAY2", + "AgwgBiACNgIIDAMLAkAgAUEUaiIEKAIAIgINACABKAIQIgJFDQIgAUEQaiEECwNAIAQhBSACIgZBFGoiBCg", + "CACICDQAgBkEQaiEEIAYoAhAiAg0ACyAFQQA2AgAMAgsgAygCBCICQQNxQQNHDQJBACAANgKgksECIAMgAk", + "F+cTYCBCABIABBAXI2AgQgAyAANgIADwtBACEGCyAHRQ0AAkACQCABIAEoAhwiBEECdEHIlMECaiICKAIAR", + "w0AIAIgBjYCACAGDQFBAEEAKAKcksECQX4gBHdxNgKcksECDAILIAdBEEEUIAcoAhAgAUYbaiAGNgIAIAZF", + "DQELIAYgBzYCGAJAIAEoAhAiAkUNACAGIAI2AhAgAiAGNgIYCyABQRRqKAIAIgJFDQAgBkEUaiACNgIAIAI", + "gBjYCGAsgASADTw0AIAMoAgQiAkEBcUUNAAJAAkACQAJAAkAgAkECcQ0AAkAgA0EAKAKwksECRw0AQQAgAT", + "YCsJLBAkEAQQAoAqSSwQIgAGoiADYCpJLBAiABIABBAXI2AgQgAUEAKAKsksECRw0GQQBBADYCoJLBAkEAQ", + "QA2AqySwQIPCwJAIANBACgCrJLBAkcNAEEAIAE2AqySwQJBAEEAKAKgksECIABqIgA2AqCSwQIgASAAQQFy", + "NgIEIAEgAGogADYCAA8LIAJBeHEgAGohAAJAIAJB/wFLDQAgAygCCCIEIAJBA3YiBUEDdEHAksECaiIGRho", + "CQCADKAIMIgIgBEcNAEEAQQAoApiSwQJBfiAFd3E2ApiSwQIMBQsgAiAGRhogBCACNgIMIAIgBDYCCAwECy", + "ADKAIYIQcCQCADKAIMIgYgA0YNACADKAIIIgJBACgCqJLBAkkaIAIgBjYCDCAGIAI2AggMAwsCQCADQRRqI", + "gQoAgAiAg0AIAMoAhAiAkUNAiADQRBqIQQLA0AgBCEFIAIiBkEUaiIEKAIAIgINACAGQRBqIQQgBigCECIC", + "DQALIAVBADYCAAwCCyADIAJBfnE2AgQgASAAQQFyNgIEIAEgAGogADYCAAwDC0EAIQYLIAdFDQACQAJAIAM", + "gAygCHCIEQQJ0QciUwQJqIgIoAgBHDQAgAiAGNgIAIAYNAUEAQQAoApySwQJBfiAEd3E2ApySwQIMAgsgB0", + "EQQRQgBygCECADRhtqIAY2AgAgBkUNAQsgBiAHNgIYAkAgAygCECICRQ0AIAYgAjYCECACIAY2AhgLIANBF", + "GooAgAiAkUNACAGQRRqIAI2AgAgAiAGNgIYCyABIABBAXI2AgQgASAAaiAANgIAIAFBACgCrJLBAkcNAEEA", + "IAA2AqCSwQIPCwJAIABB/wFLDQAgAEF4cUHAksECaiECAkACQEEAKAKYksECIgRBASAAQQN2dCIAcQ0AQQA", + "gBCAAcjYCmJLBAiACIQAMAQsgAigCCCEACyACIAE2AgggACABNgIMIAEgAjYCDCABIAA2AggPC0EfIQICQC", + "AAQf///wdLDQAgAEEmIABBCHZnIgJrdkEBcSACQQF0a0E+aiECCyABIAI2AhwgAUIANwIQIAJBAnRByJTBA", + "mohBAJAAkACQAJAQQAoApySwQIiBkEBIAJ0IgNxDQBBACAGIANyNgKcksECIAQgATYCACABIAQ2AhgMAQsg", + "AEEAQRkgAkEBdmsgAkEfRht0IQIgBCgCACEGA0AgBiIEKAIEQXhxIABGDQIgAkEddiEGIAJBAXQhAiAEIAZ", + "BBHFqIgNBEGooAgAiBg0ACyADQRBqIAE2AgAgASAENgIYCyABIAE2AgwgASABNgIIDAELIAQoAggiACABNg", + "IMIAQgATYCCCABQQA2AhggASAENgIMIAEgADYCCAtBAEEAKAK4ksECQX9qIgFBfyABGzYCuJLBAgsLMQEBf", + "yAAQQEgABshAQJAA0AgARARIgANAQJAECIiAEUNACAAEQMADAELCxAAAAsgAAsGACAAEBILBAAgAAsLACAA", + "KAI8EBUQAgsVAAJAIAANAEEADwsQDyAANgIAQX8L4wIBB38jAEEgayIDJAAgAyAAKAIcIgQ2AhAgACgCFCE", + "FIAMgAjYCHCADIAE2AhggAyAFIARrIgE2AhQgASACaiEGIANBEGohBEECIQcCQAJAAkACQAJAIAAoAjwgA0", + "EQakECIANBDGoQAxAXRQ0AIAQhBQwBCwNAIAYgAygCDCIBRg0CAkAgAUF/Sg0AIAQhBQwECyAEIAEgBCgCB", + "CIISyIJQQN0aiIFIAUoAgAgASAIQQAgCRtrIghqNgIAIARBDEEEIAkbaiIEIAQoAgAgCGs2AgAgBiABayEG", + "IAUhBCAAKAI8IAUgByAJayIHIANBDGoQAxAXRQ0ACwsgBkF/Rw0BCyAAIAAoAiwiATYCHCAAIAE2AhQgACA", + "BIAAoAjBqNgIQIAIhAQwBC0EAIQEgAEEANgIcIABCADcDECAAIAAoAgBBIHI2AgAgB0ECRg0AIAIgBSgCBG", + "shAQsgA0EgaiQAIAELNwEBfyMAQRBrIgMkACAAIAEgAkH/AXEgA0EIahAwEBchAiADKQMIIQEgA0EQaiQAQ", + "n8gASACGwsNACAAKAI8IAEgAhAZCwIACwIACw4AQZCWwQIQG0GUlsECCwkAQZCWwQIQHAsEAEEBCwIACwcA", + "IAAoAgALCQBBnJbBAhAhCwYAIAAkAQsEACMBCwQAIwALBgAgACQACxIBAn8jACAAa0FwcSIBJAAgAQsEACM", + "ACxMAQYCAwAIkA0EAQQ9qQXBxJAILBwAjACMCawsEACMDCwQAIwILuAIBA38CQCAADQBBACEBAkBBACgCmJ", + "bBAkUNAEEAKAKYlsECEC0hAQsCQEEAKAKYkcECRQ0AQQAoApiRwQIQLSABciEBCwJAEB0oAgAiAEUNAANAQ", + "QAhAgJAIAAoAkxBAEgNACAAEB8hAgsCQCAAKAIUIAAoAhxGDQAgABAtIAFyIQELAkAgAkUNACAAECALIAAo", + "AjgiAA0ACwsQHiABDwtBACECAkAgACgCTEEASA0AIAAQHyECCwJAAkACQCAAKAIUIAAoAhxGDQAgAEEAQQA", + "gACgCJBEHABogACgCFA0AQX8hASACDQEMAgsCQCAAKAIEIgEgACgCCCIDRg0AIAAgASADa6xBASAAKAIoEQ", + "QAGgtBACEBIABBADYCHCAAQgA3AxAgAEIANwIEIAJFDQELIAAQIAsgAQsNACABIAIgAyAAEQQACyMBAX4gA", + "CABIAKtIAOtQiCGhCAEEC4hBSAFQiCIpxAjIAWnCxMAIAAgAacgAUIgiKcgAiADEAQLC7aSgYAABABBgIDA", + "AguAkAEAAAAAAAAAADGyfhfBM8W4CfdqdtFBU0U4RRRhEHKW/RLu1eyig6aKI1yr+2OwYzIbGb+ac8L1zyq", + "rwY2y8TB3T088gRYhlCF+/UKW1xJRmUa4VvfHYMdkdwoo4AZTAtxdoelttKIyq2wTl3p1kfcTVFaDG2XjYe", + "5l5P0MpNCkVp6eeAItQihDrywGFexx7fuXaRJ0/AN7BqbbbGM9ML6+jHCt7o/Bjsm9wtP5TvJLcYWHx5heg", + "N2MtDW5j5+zGDTR0USDO2O8YuBjOpT6UHna2CYu9eoi7yfplFDiKxEqn8M/kW+Z4Bro8o3veFjT31DKyPsZ", + "SKFJrft6hQ6JkowVPD3xBFqEUIYNj48Tm7eVPjXKm3KLxQPDBHjlZUr2xnsu0yTo+Af2DB9hWv85NDO0JyR", + "OnilGpUkWljCJ6HVg8XNyzYVMpcSnQsCzko2WAR96hafzneSX4ks32eRc11JaYZwYae4mYi1QLmZ+LxWnlW", + "hrch8/ZzFoWdkMCP5U9NCio4kGd8Z4xZMR9xG29b19q1TjcKaHK4Ca5p1nZ7TuOLBNXOrVRd5Pgf8i/RR2G", + "/e5ujacBASNCogISIvFN0iy7ey1h2Hn7OTcXsuQoNQpXOQb3/Gwpr+h1amh5nGVehn/AmBrw2RKbs6wHnwC", + "V4/W9vUKHRIlGSvHR3QK0xbckxPpdVHnLng4IlsLRiYdvYAaHh8nNm8rfSusYTD3XO7FAQegvUWt3rIwtd6", + "qhJ4bCgjwysuU7I33OUK03FXfSE9cpknQ8Q/sGW0UN8cwPCmhVVEjpiBOv1xk412x4X165E5InDxTjEqTf/", + "riK5K/jytHv/ZKgs0Z1nYNiF1D/txujXcNU8psUHu8xXNEC1+Vw4SAZyUbLQM+tTIZMtoexoafmdi/aO/28", + "a4rpqip3DNJlm6yybmupbSn3MzeeJ1gDMI4MdLcTcRa84pPxR1+AeLLz1ukDQyXH/p9JbPMP1Kn0NbkPn7O", + "YtDhZJopv/2naNkhjkivjzGV6JPwX2689C0v1IRVvaoovh5m+kJ8me0GJiPuI2zre/sXkZA0rdi+Qz06Ubk", + "fKY40DIgvrt4aS4w0zTvPzmjdcQV/RdgPWxjJYJu41KuLvJ9RKcbDarh5J2ls0qJ6yu/aWN6stbv5KmJydW", + "04CQgaFUPHEy/IO9+te4IHTthJSVBKMHlZGXqM6LFK/FeQ6AD9gPiCQFHbxUW4vZYhQalTuIkP6DaAmpYAo", + "6QpuzJrpneSFles81hjz6pTQ83jKvUym+E92iIZMIr+BcDWhsmU3M+3vsFH+lFk9/KqoFeIx5nGQNS3lrsC", + "IezrFTokSjJW3VlrLeV59+7lHH9M9QthE9SuAVs0OKSrJtLros5d8HAXYJW1D241yC8lgdQfHKM1Hpf/w94", + "vZo00PD5ObN5W+gWOQFmt7ZNCPctUOL2fBb8MeSovfKzAB2md1yPYfGRRWC+pNBlPoelgar1VCT03FFHYw0", + "LIDvKse3MCz3r/wttKwXzYu8wHY3KEaLmrvpGeQzYWrmqNVCa4TJOg4x/YM4n+7bciLB2Lsbv51jJei3aAC", + "YfB821OzqqiRkxBnH65mxA4W4CvuwGjVSw6kN0t/JLnUi1R7uhE9wOvIfU+TBLGsdE2NA2Jqv70xVckfx9X", + "z0a7QOVM2u/l7XrNV73qmNRfBNqWji8g7BoQu4b8ud3dqG6sR898ZRrvGqaU2aD2K11ksVXqZU4TGHDQRZj", + "zsyKqDseEqzYLCAHPSjZaBnw5s7Fd92nDxAH2pTznG1U5METbKyYokIFVoCYngvg012QSWDBDy/FvXFdMUV", + "O5Z5Jt5TJGkoqiKkdO88sge5JddvyN3OFIV+VOuZm98TrBGH8L56owCQSghHFipLmbiLW1wxyzeKhNDY2GC", + "NJo2tvwvDR2xanpHkiWn7dIGxguP6ctyV/aK+uHn2jdPspZfXqu2qMpC2q4wss+XiWvuhyU+owgMm6J2SzC", + "yTRTfvtP0fN7SkS/yIpp2dCLyQ05uh7oYvXezAp/ptAn4b/ceOlb4ZWfqB1LLOM1O57zKXOISASJ4OToQE3", + "wPMz0hfgy2w0NfoqSOQEetSfVSx+L8C7CFmc1CErD63ouIiFpWrF9hx+QX36bgrg/enSicj9SHGlLxtxl/m", + "HZ0XODyATuE08sQjG2Ey8gipRomneendG641koCYlc4n9bYW0d6EyQ6aZQ32P/jaMsHqul5vEEMaALmheY5", + "sUCZbOiUoyH1XDzTpPg8pAUQzb2uUszHaayBoGI+U0KZ4HDObC8WWt381XEgQ4nfLbAkHzk6tpwEhA0KtVY", + "pGfTI/GS7R2wBsNRZ2/cr84RAmKi1/YED5ywk5Kgx7Zxi3GgVxj/82XqYdLB5c5BG/2g4QRdCQZv93P32M4", + "4tBHgssQddgDxBYGitouLMUN7lmOFTjMb6Lob0XR+RCpaxAwQR7v8Eh/QbQA1LQEjra56wQbouUZJU3Zl1k", + "zvd/stYaTliVdPvjkAtJcfqn4MRxd1pNoSVKeGmsdV6mVlFfiNBmYv3V1Q7OwWFLkgbOKS+9cnfJiXmBf1X", + "rXwjaYqaeKfhjU1nm99g4/0o8iv3QOUTsdmcIV2whn8NlYHtMS8Dj0Fk7+MgahvLXcFQr0z1njsRMD62Ncr", + "dEiUZKzpZVVjiaehFNEgQQKZ1Tfp4JI/FVjm8lHKOf6Y6hfCJvuLgI8rJAeew86U7jtWkWPyfOr5+mVU2wA", + "AAAAAAAAASEfgaLc09/b7HVeJPU832bNat+GKe8Avnag5Sii4t4bV79kin4xAcGa1bsMV94BfLvKOq6LDd6", + "lRwuTMA1a2ORmFBKS0YkHPqt+zRT4ZgeDimFMtiS12Fsxq3YYr7gG/hC097pza9kk3d4oPFqE2Zn8wamehl", + "cGQooTJmQesbHPqwynxsJibhVmZnhA641uqEd5+eI3XrFw/LPDTLxTb9XdrELuYICwDxDGnWhJb7CyMdkcy", + "pW8b2vNGLVUE+tpKuwHNPbPOLbwIW3rcObXtk0AcmrSOgRplbu4UHyxCbcwmqfR3m3aaOpXzQ5YRDVoV3bS", + "j/qY5reNECZMzD1jZ5gxOc1u4bC4QvxTEujIX7j/3UyTShSMZydmhqnkn4G5gkeZKEZDUmZYivP3wGq9ZuW", + "r7HZitm65PFct3/wwOb99djJeXuzqYKe7WIHYxQVgGppHAHoZ1r/CIY061JLbYWcAkrt2Tgi+vc34ZPBn57", + "4A7OflUrs0YduaNWqoI9LWVrsq6wr/AQmMdkA0jNbuCTFXX7UuCj3W6eyVj4CBMAhMzYoOIl3j15YA4NGkd", + "AzXKyH/UAao3wjy3T75mC6IDrP8IXg68lvRaTFLp7zbtNHUEFQmHgdnDgyrnhywjGrQqYqBnRJQuQ9zR+tC", + "lHlWD85m9MM2pYXQF44GxP02Wa/mrxlFX+qKcDxic5rZw2VwgUNsG3sftq9Z+KYh1ZS7cfzZuaB3SGiuJhT", + "Tf/Fhh66bNcz+U71UcULJDVfNOwN3A+gS1m/n0KjZJXgJ6c4/qGQEZ4hLEux3vL+tsuWZ4akZnrIzR0Uyds", + "NT2OzBbN12fnLHbWOwDqmlBBXimSjoHiglCmM79DvB8uhgvL3d1MFPyX89HwEHHpdytQexigrAMlOqhhNW2", + "R/onsBZlX82H1W/39g3o+XAjEMecaklssbNYgHwC/lhGRevay+N0I4Zqo50ri8MXcZyNb6UgYdQGNcUoRUj", + "W4PHDdnLyqVybMew+NRLB66/GGqeIIgxCzrIf78/CZPX6RelclXWFf4GFxhTSle3ItXIwOiAbRmp2BZlyZ/", + "su3ULyb8E9TM9XOTJAiXqsp+ANxbb2SsbAQZgEJr4NJqj2rPPQDVeRSXzXM/9FEHEhy+PECWvi/4ppILOgI", + "6Uf4t4URFaQ/6gDVG+Eedi4SGvjW3OPBQzrlUVi3mxNSwv98lYpmv4RvBx4Lem1tlZcdM8ZHkOYpNLfbdpp", + "6tDjMrfa7p4cY7mFVlCVXjMr/mU+56GpxVTOD1lGNGhVHInvMfEAn6Ov01jQe3tfjOeUuLjMT6h6yWY2E26", + "M39OBIdZ72bgoJTJ7YZpTw+gKejyB8uT3H/ytkPQnyQoOxuXXFE9+PvkwVo2jrvRFOR8eykPGQ3HO6TA4zW", + "3hsrlAeH8tBVaGTrbLJZrk3P2OmYNieoxryXlv/FIQ68pcuP+0FfCDfWhPCQdPR2L3E48mTwinCkAneNBh+", + "imh4uQPeSm9yclV0PiPmud+KN+rOKDSoJ5AaJ/PVg8UPb7OpmK1R1Pd1nmSlUP0CWo38+lVbLxOil9E3aKa", + "krwE9OYe1TPa++ScUSoixWmhU33bUeLqIeazFWxlFRxe1tlyzfDUjBaRORp6xCN6pcuO+/C/41XtjG6TR4s", + "Uo8N+4DjlSGMKizkAUFJ8lPw4Y7ex2AdU03AkV9lvM6Ml6ZlnFMZS1yCh3od8cWYg1hKEMJ37HeD5WsPQ9U", + "wpFw90MV5e7upgpjx2vjZZ3pdQjywJ19OlV3/Ha+m/ZJGgibhbg9jFBGEZ8BxjsHIwlu9DRtRR+EtWwAsBN", + "DlPf6E2JfO6ku281p9ttFr6Woghad7u7RvQ8+FGlqkNc2fHFrBLHa6Nwf67UwNaTuV2ykylsAD5BPyxjIr4", + "RxlsS4V7fNa1l8fpRgzVnvJ3r15y+yMtqMBO1Ak7DGXvICZjPcz6Gt9KQcKoDWpSmKopdZz6nOHCHcj/5zq", + "zqYX9oEjTzUWHd3ML6hC67M8wk2NdJE0afGokgtdfjTU0LcTqYGt6w04RRRiEnGU/BlalcDOoksm1DBKRud", + "NS5v1L8vkO56UQ07l8Uqwk0rmb/pw6GxAlTyikK9uRa+VgYOPLsyZfEpYf06HUh8rTBleUQbww/iTw5M72X", + "bqF5N+siRY1DbETKYJ7mJ6vcmSAyjx49hhGk3Z5Zs8Xkj1TWTEhL38lCaSv7JWMgYMwCUyk0mzpNAT+uheI", + "2wi+fz6VX887YAlLyWNxPbXLq4i+yjl6VaMcvEk8iiDiQpbHiRPCZwIqIfN+5b1XaE2AZr919RCIJTdSSIN", + "GSj/EvSmIrA4N36wKHX9aIP9RB6jeCPNouLFvH+r/BdviBo6VkT8qk6Xm5iKlyNwKGNYri8S82UJfNkM88E", + "sv8QWBoraLiwC5QmHKAb989pew72GjfAtf3/cPCRRI/KlsrbjonjM8hiTqWIApB8twW9oy54iSCuATndKPP", + "6b9FqDHZW613T056ICFBgLpys/GcgutoCq9Zo4168UXHkqQPW9cJJ1lir91KLxMKlF9SaicH7KMaNCq4Nv/", + "2jtcJ1xTgUg7sSfncxvGqFMGExCFNTQm+KTQZyx9c8aQE+SQ2s4pcXGZn1D1hm6RGS6rpwP5Xvt+jz5mk7E", + "ZGxY4CpFlAkOs97JxUUpKBEyfBUWmvGT2wjSnhtEVLLEiXBCyJuOf65W9msnmzNesddUt/RE6AAAAAAAAAA", + "BdMxKlPcGwcbpmJEp7gmHj51U270ZD0ZIfXt/MpSIa8kJtzWmY46qDpTj7ht6gexH4C+kj42HLYFUvKcEYY", + "+3QCBw7ZCWiXaHvSQ2LY+GMM7J6Hy5eIDxCSnH2Db1B9yIXQuSogIBHU/AX0kfGw5bBrSTA4vsCJrDBzcXa", + "YuADlZz+139fIbPke6vhkBliYnYmmPM1JKPSB96TGhbHwhlng6AIs/oDqRZk9T5cvEB4hDnGLPmBgcj1lOL", + "sG3qD7kXJ0f6+R0JeNC6EyFEBAY+mc7fa9DzAP9eLvDPX36H0t9aPIXLiYETGMdoXnaQjlVRs6QU4meIlJe", + "kIHO2W5t4etDsOSKsnbm9Tbjin7WS//Q5dKgLQpQ+M9lbDITPExOyrZdGEDgV0nUww52tIRqUPEQP1znWHF", + "X68JzUsjoUzzuEUJ4mzRIO/BkERZvUHUi1bcgPDyMbiXKN56uArpyk8/kr4RRZmmU0ZH86qUCVI30Qs3A9t", + "5PiuKMXZN/QG3Yt19suSycdt+pKj/X2PhLxoz5Dv2LJFDBk3mwb7USTHeWqoFF5s5XcIjf0isSqmpprQzjA", + "UF2cW633q8PbsZTBbINniU9GkgCrHjNS8l+dRuJq/xhmqJuHJYrQvOklHKqk/hz2fdIaa2NjSC3AyxUtKhe", + "EZ1Q8E+zvSETjaLc29PY8iKn8QDA1MaHcckFZP3N41RA41a45sr81P5xaI76fPkHz1s7UuF753KcNc823GL", + "Coa0fnOrHZdhz4RGzWuUO3aDQO+CG/gnD1YNVFOLDEOYGsn9HPtgX+YYM7XkIxKH8VT3HKtTfpuIgbqnesO", + "K/x/Nfg41s+bjRPc/QBPLb6oTu/vpXLsDtmputlKNK/fS/SJy+8Jbm86DIIizOoPpFpRsTBp184UK7bkBoa", + "RjcW569cUI6xMdchG89TBV05TeBvAxmRqj+MJ/JXwiyzMMpuhpuIuEQ2C6lmtCw3ybEmKBJ4ZqM+t+fvjyy", + "9Hie4oab74PeK0L5gYOxkkN7srYyNmKjaShurTUoF/AH3AqQLA3EwS2P1osrEkR/v7Hgl50Xl06V4jyMmgn", + "iHfsWWLGDLDEs0UWEqoQ242DfajSI7zMwUfU56JPoLUUCm82MrvEIljOxnlC19hcWjSOgZqlAEsW8CfO6sk", + "cMsO9nB96PXilj3k1UApRZP61OHt2ctgtqfn80jkCtDHQLLFp6JJAVUdgdcCn4ixJOWKPiF86XpEuLkshEE", + "oyjVf7BprB2sbpwLfCM46qqvWr/vILMGojWbyyNqJ/Gk9FxWd7Ga6KuyFSK7+w4frXPSwpRfgZIqXlO2WBU", + "VZSyflCsMzqh8I9ndX8CEPIslGBqQjcLRbmnt7+RBiEWZbywoeRVT+IBgamEN2Rlsd2arpu32veP64YYnmT", + "r3dw3nR+AEbizKFOgBqXCiZl7j7sBvxDFl1Q/mWq6w/S9B+OCbaS2p9Pzh790gWWW+aBbpHOe5Shrnm24xZ", + "s2GUHNsaPChUNKLznVntugkHsFagmF3LZe61bjl6eO443afLBLvIn9+IkSRC+BkNgruDgX85qXx6sGqinFh", + "iHCeDeAehmdJtwNZO6OfaA/+d5VxN2huzjjDBnK8hGZU+bfKOChzYJU+Kp7jlWpv03deUqkBnWkSsL59DY4", + "Q7j8xyrFHGufo/vZX5Zyn/ue4vyMp1jMJ4Xl5NK2xZzXylZRAYfvzwvRUU901IE7b+xIaqflq2iz9091J1s", + "5VoXr+XD0ahMFWfD+boE5ffE9zedLUghXouHW4FGARFmNUfSLVFN1c96N74xKJiYdKunSlW/1Fzd5NcmScH", + "WppUcD1SR1ppiPFN/OI2vTy+Hgu/M6TgD6y7Nn6D1YzmqYOvnKbw0dW7JpJdFoE2gI3J1B7HE2uzn2zp33d", + "ik7h2Twq+vALOi2TqN38McyneUgVxPN3hdO1AoEz9bZDZyYBCt/9LIIT6kueKPvtRY6+kCMx9KsM+nLat8b", + "yassaXX44S3VHSm6RNKy8c4aN88XvEaV8wMSHCaWFUnoBAdjJIbnZXxkYrAVrLS5Z2N8xUbCQN1aelkWd+g", + "TAUF9RpbJei03XctDRfhQfutGzF0wqz6Kj3vVeOOaFNlTYNJiMdYa9uNCuWfi5zClP1m+eZe0XlFbZKdcRI", + "V0Aod/oEPEO+Y8sWMWRhcKzG9teBFYYlmimwlFCH2xaIjI1V4Pa3/420FLfF0+rMnxEpdnWiDZmp/m81pDB", + "QqrtbUvQUQaihUnixld8h9ZJA3YxUb1ASx3Yyyhe+wk/0ZJf31g6z4tCkdQzUKAO/47bQMRWYcli2gD93Vk", + "ngBYWSmkqX+ZH9jnu5qfYy8aC9aRyUN4KAR+hf89J0UxIa201W77XjY586VIPgsRhYwglGJt1wqCklXHDJm", + "zN5u3hvYmym8snKgGSLT0WTAqrdV5nqeFKy2zoCrwU+EWNJZzG9oAPQ0zjKFX1C+NL1iJcmb+fFE0X5cHNZ", + "CINQlGstQEutvpEkGtVLoo5d8O96iHiwK2AxXwtvLYbEJnKOmTIelGEbsz7oXveRWYJRG80DxIP8v5CrvOS", + "RtRP503ouuaKntsQSyl9BqU6VJ3MBPxyaXDAasrFO+89q31zxYNym/Hh6YTDQrQvYuJiaMvYdVuuqPafzRm", + "yxvpzS4bCX/uyNjnfccSePFIZnVD8Q7O9JtXXxAtFcnq7gQx5Eko0M89NRu3lTPX0AAAAAAAAAAF6RFQ9Ib", + "Nu/17G8RsP+b0uJIKlJi5K09K5jeY2G/d+W8PJsgs6RBCl50sXLRQOw3SdD0MQNb2tiN1RlQl7dZhlpxXBN", + "FrG9puDl2QSdIwlSvnTMC9VP0u2ZNxzP2CC5j8emCcCQTGIwToagiRve1sQQF7WGU7INe26oyoS8us0yMDn", + "fi/TWFo25GXbCf0SieeeIY803KHnGwMuzCTpHEqSeWqYGcivJGxd6D0/5uX3vSesaQLHVplBZ/K/G4merKw", + "dtusmqC3CUjk0TgCGZxGDQ3AaPafUf3/ef1ktkmnS9qQ7DRCz2rwIgLmoNp2Qb9n6/fwLvCMBJ3FCVCXl1m", + "2WCwYAGMRlA2gvhKU+6i/QuVXA8QPLnL5FyM+yE/4hE8yyi+Yu35J9MpYJQwjx2K7j7E0XNdBrwB+sE8Esn", + "qP18tZXlRG/EJsM8tUwN5FaSN2IkWQKsOkmIRWeJxqFVIuob9pzJ6Tn5VZLWNYBiq02hzEcgjyrHlh6y+F+", + "Nxc9WV+xpSoKNo43oZUnjywYxORw72PbETl3ioxybJgBDMonBQgozDwteUn7LKppGgMzmipW7j0nIoD01ha", + "w6z5sSME7bPS/A037r8VIdholY7F8FDIyThhCAhLorz0NCHe/v2HVeVk1VgzRn/H7/BN4RgJOi7+oLln1bL", + "LihKhPy6jbL5jA/HLqG7XRvEJZVMRRZgDGBg1p5eII/FsJTnnQX6V1IU0aRPHsy4sFz79i36YYWn+L61/+F", + "XamP9U9RrDdQ0tFkWl7kW4ttWETzF2/JP5kG1eYYJ6XkJiGWNtwqyo9Efwcj02KmVPv2J4qa6TTgD6i2n5W", + "hWDuw1gngl05Q+/mImPWYBjwgRgG4XNGNrpSyXylJ3sXCTw14apkayK0kbyb7jBWAwf/Qr9slXAtTSyTxSj", + "BTQz+Qm+FdhdUQjZ3gv8yQ2ljhRl827DmT03Pyq2h9LJybHykUTz78WJZwQnYRr+lX3hyZyZiPQB5Vji09x", + "h5VER3i9oJk8b8ai5+trjpgqhXD83YRs0ADXEhhwuXt0RZTAA0ZWsqSxpcNYnI4lAPTmEUOqYcdI3rRzpwd", + "c0Oyb96G8MbMU6XaWNVCy7cNNM9XnS4QCIQUZh4WvKT82oVzEV7Qf0P9xqPVU78UIaNXttob08+eKncfk5B", + "Be2p05gqc2C2g1QpZdZ43JWCcVMhgkX9JuyPd6MnY9NsP14N53Ne8t9RopDoME7HYvwr6qxkc+bRktXOLsF", + "VyJtBBLRqlWjpKC/49DRDcafgGhWOcBdMhlN066rysmqoGac60LbmV4mqycZNuaVHvBdkTzf98XqdpAqxE3", + "9UXLPu2WBpOwBhkl23nG9DCfrfztKJFQddx/59vHcxhfjh0DdvpkvBrNzxhAFa1s7vzMQ5rNOsirvx5YrCL", + "YgIHtfLwBH88kxK6upzfwCyEpzzpLtK7chWyM6FCCQT7NRt6KtC98KWkDnVivGZPgufesW/TDS3cdsu+J7/", + "WklVWYvesLWJmC8d3+ORBudl1eAj6C0l5kCvpHfVDJaIvosm0vMi3Ftv8WKGzgNvNZNsbcXeNtKYGhYpkeM", + "XYfbkMqs0xTkrJTVI72D4GJhLyQixtuFWUH4kcvXi3HfjENpWd0f6WanDCywzE8d4Gq33sTxQ102nAH7LeA", + "TqbBRugO/6ocxCXr1Rlb718WPt068eAV3fOhi/HmRFCeIbq9HgQMesxDXhAjE6g/j5FFJszaeMu+kh78FE3", + "cjv1ABcr7r5SkryLhZ8a4MOHs8PpRKXw1DI1kFtJ3q5FJzrYN5JhJ2WOc1OlJpV59Jt8G8n9Kl63S7gWppZ", + "IACZet17KTfeJBvf+1Vj5A9eX4vGdNCK8qSid83I84vX3uYj8OlA5Sn6ZIbWxwo2+IAg0uvmuVgEHS+R+9M", + "E9Y1na8XG8rebc0PpYODc/UiiOa003f1OJl558+LEs4YTswO3tvmSNX1NJzUT37x/rpxdcUfinczAYMB+BP", + "KocW3pujpQz4nCAxeeuPXpp4jQxuT8odSGO746jcehtRRmCaf3g/WINdVnWdMBUK4bn7SIqUUEkzos2nQ0S", + "keDD5F3/U4OE74uIhkDaoy2mABoytIQyOKlIdukLlCWNLxvE5HDKtJggU6g/z0OUMWnYOos7HQUkZpBWUIQ", + "6RvSinTk75mTX4a3VVeBZ7fdI5F7HVK2zZl3rFquPEs3ZIun5o09bk0g35rHPlOQaaJ6vOl0gEET5i6ByMf", + "uvY7pbZH9ekM09K05rNzJLcrQL5yK8oP+G6pryLfTMJDn6jUerp34pQqQcUqTvEvL9LTz77WSARglzre7iL", + "OydtlTuPiYhg/bUCn8rKWnvLWuDX4Jg4n2Zn93Ol2+qEUIgfyF9ZDxsGQwhsGhrdADCs6iQwSL/knZH9gHU", + "Lbf+rfjRQgTpupHGmo/TEeby/R0lBvO4r3lvqdFYYq2gMQNybkh1GCZisX8VFuQNKSrdpKqfxKRgoU8QXsF", + "VsW/pI8vh5hZhq+RMoIO4h3SkrCB7PDGn3e0nss/IbzbI4m/eFHcRibfggNbUPk8You/Iug+BxjgLpkMou3", + "WYqR6pC0Rgyr/qzm0GKwuo4XvbYk5H0BdoW3IrxdVk4zbKZySNub9cJt3Sot4Lsid4TMetlmdpmPFsbuQd9", + "d1sr/1761WZBtOIvqsvWPZtsdYvviAQmrYOXw8XaZsIAvoBngJm02TZRQAAAAAAAAAAdw3hKr0Wpj7uGsJV", + "ei1MfZkXI3/HO+pD3DWEq/RamPqrOGWBSUw+xDIvRv6Od9SHRSKn1DNhcrnT+J8PupPpwaT1fiUHhU//PeJ", + "dWsC+pbxK77xwfagDgg/NG6ROyXE7eMD6jvPf1wXh19nxNOQ9RpbaONuJ8pt4zWKoRycBCre6b0ltmhesiS", + "N4ahJdLEbKVHWLOOA64PQRVyzs01uSTWZazcZuTTRz/03uual23jCIQA+TFGB4Dh6aN0idkuN2aZfWYiCER", + "UjwgPUd57+vC4eNFDdaqQk1wq+z42nIe4y1olLJ1N7dsiy1cbYT5TfxW7iQnK7zkc/xVsfXHSTNWoZbJv2g", + "MmtkH0wFgmcJgSdoQeSo2h8nGS1jQ3zpflWgWm6iVlRo857DeYEpk1MZ3bR0YAMuRb/jIq5Y2Ke3JJtVo7n", + "yGqGCpcy0mo3dmmjmu7l7p2CMztj+m9xzU+28YYmWPVnu+xpfEIEeJinA8BxnjP8MlNZWIjw0b5A6JcftSz", + "mOuoczYdPSLq3FQAiLkKUjTO/9Hi2u4AHrO85/XxeXDAoRc2n5KQ4bKW60UhNqeRbIRAlEtVTvzPCfgLYuL", + "JjBEbU9oIgSAdYyyvqbYlF229PgR43EbzP5dDR07LbWRPSVHsn6EOjd47ZhDsH6q6ruV0uz11yV4q2OrztI", + "mrWVoG+Fhl48iwy3TPpBZdbIe7qt0PxzcPY+mAoEzxICT0mV6y5yBKRx0ILIUbU/TjKnjyl7CCnoDDFVEaC", + "B23N0RljwijzN1UrfT9P1+/Y/CahCMt9G4Jk37WCVC3WB646abXQhyJdNsAN6V14PrKfzdHe2dLK6Ac0vzy", + "boHEmQAljCx8KhXzY8wdXkvWZk3H+22AWX23J6QfP6okPoEwj4hPdDaVUFrsYd4GAWkj5EhWrtgTwvKOK7/", + "De556baecOLOljNG8zf/RIte7Lc9zW+ZSCamGHhk4AgAj1MUoDhOVcP3GbvlkcHzhj/GSitrUS5FR4zlbsL", + "ehP7SXgmbFfvZPaoUpt68dH94YstXEEbkorsagfhV72sz87N09I2zxW4wyz5byBpKyHUD4aoG4NoVtnurBU", + "NJVbAA9Z3nP++LrcON10h6RgQLhkUIubS8lNZFPUIW8RUbRw2UtxopSbUazuz9tWzgOryLJCJEohqqYUhca", + "OvnsyX3pnhPwFtXViplAAVvHv7ZjCDI2p7QBElR47CQMZWtxsCrGWU9TfFonWhhL5IIWOc7LanwY8aid+bu", + "0brMgwv4Q1hfjC7/rSZemyfGgboEqfje7xlwdP45JR2XU98xV7a0VT6m0+kLGOmWRux8rKKXT9OOM41iWAe", + "SEPZ5IifxiCvyIoHJLbtX9jFay2ZoEthQdJIUl6boSI236l4440HHHP9DqzQ7HWlBPDvhm3605ud58z5qsE", + "52OrqLdMX15/mfDAVCJ4lBJ4LPfQiIzOioJIq113kCEjj5Sc2d1ke7t2gBZGjan+cZNcIcInXaTpaTh9T9h", + "BS0Bk5ErLcrUR2J2KqIkADt+foFafDar6hQdaMsOAVeZqrlfu9AT/EjA2rvp+m6/ftfxLJkkfBSvvZLFCFZ", + "L6NwDNvJ4iFlDDWlVGxUr1PuSQOKcZfXGUEMqgXX0h/GsMJQlQoRZ4wfh/kam1nOeRNfpbTGmrYzvBoMO2D", + "ffuxN1ParvRwGpuKRXyQXp5N0DmSIAUpk6z6hISGO7CEj4VDv2x4x4lur/6pykaCq8l7zci4//WmKFFw3h7", + "BbLELLrfl9IIbvOoECvNSvI1m0t+DAcnE+msz9T4Xb/pjfBCK+SyFuRRx8aBEOiOHUVNWdHdbUT4mXrdeyk", + "33AL9JlCENdh1DyER1C7Bgu32T/OWXHpMqsuTxBL2jhYyMfeYnwmS+Zs8K68bo2ajA8U/JYTzqybJIOMSAF", + "lffFHah06NpkOT+NdbeQkMt8lgLQAR6mKQAw3M3CZuyGRZlTa4euM3eLY8O2RNZ52M7KTCcMf4zUFpbies8", + "HxntTP23cis8Zip3F/QFJt1Ml2Gxyk1lBKgf/nfqOmjlgqLo0dSjf8b9ZdM7l9RyJ9fYxZ2pkVCAA+uk7xD", + "mXWEpVrJJLn9KQlaRiaNtCEejfCyfBVOenZunpW2eK+mQeo0YezgVcIdZ8t9A0lYHirjYYlZ0aEKoHwxRNw", + "bRNaX+JuwhoO+sst1ZKxpKrNu/PHOWDOySgAes7zj/fV33Ck3FhenbY24dbrpC0jEgGRCPkP/Elx5cMihEz", + "KXlpys/yW5xs0OZsijqEbaIqdrFJQs7C54P5FP/M+CCbJScJPLSyj96MqK95fG1+EHY4croEJ9FV37fj8q3", + "S3Y2DGb4x1ZhyyCqWGHQdR4MG0AbFt2UNLEN5iW8M8N/Atq6sMs+IlW/zByOUikBKnj39s0lJOAAxeFQ82A", + "GR9T2gCJKFwum/kuWhHSOHIWBjK1uN/kRZKsxu8gJb8tccLhJU3EYxr1aBV/1T4HRniXCZB8M9tx/D39yuT", + "Kz/tjbTBPLi8TzOfHxBW21XeQajjY+h/Yq6fukiyghyHFRazgl27AHBlyKEpjNFjmfS6ltX/b8euhGSEfi4", + "FpErWTvk9GBKP3aaQ65bJeOw0N+LcarrGSANHPM7Ba6wr6iqfQ3n0hZxtWkFR0iXv/4TLM2YuVlFbs7vtdI", + "WHOzhX6ccJxrEsE8CZGRttYEZwKQhrLJET+NQeeLU+OsKSt/AAAAAAAAAADlUZmWzImUFsqjMi2ZEyktL/K", + "ru1WavTuUR2VaMidSWnEW/Mz+rsZMXuRXd6s0e3e7tc7hZ73vYSiPyrRkTqS0zd5TIqjHMKLiLPiZ/V2NmQ", + "d9YQ8x1BmPvMiv7lZp9u5ZmTZ4muBi+HZrncPPet/DkzoEVQPzS9U7jQIxmrqRXd7cm6dWMwVL8S4wHAOpu", + "HAUf6mKzyAsZq/KZ2uoncMHSpv+/WQUVxFlaVVGMY7qKoA4zND9B348EwLIhf70Nen2U1ETMn2h/9mh+qhn", + "5xzEPPBjPqtuiNKHRa3fzNNns2IUNEkAWvOlTeaf8lXATp6otwZkmUnaiHYaBWI0dSO7k0uc9Pj8t628uTd", + "PrWYKllnortlh756A4l1gOAZSceEHDPmuytvl9yj+UhWfQVjMza/Lg1PIzNpelc/WUDuHD7vEVkCcshMZlD", + "b9+8koriJxZ2RtBaE6NMrSqoxiHNVVL4MzGq6VQUMAcZih+w/8eOUgATc3hmhuTZcHU67Psuaoxp7FYkYm8", + "Ic0NX433JvLYmWs6PtVD93Z0GIJnOjgvDyB+59QYXSqE3NQJAX7yZH2IsmyyXJdh2UYzefKgRZSgElUcQYI", + "gkSvu//KU5I/f0rqZlyfG6tp8V+ovfimRAgUDjErNC/QHjv8mpBhtW0l3q0DBq08+TOHp52cO8yfQmL2BAr", + "3RQtUTQSvsaLftm+oVTYnblYieRPg+MYJ680Y9rFhUMViWQ7ZQ8rrkPjkNTwSU31ccXAjryhXKF+CO/ZKec", + "6+kwuv4GWLZQXGkRLbgNr8kwoYhs07bzJybaVprN4+q+ShLP268cwAX/S2QIEUnZnJOD/Ul7wqn62hdg4fW", + "XsGO23/mgl2ia2AOGUnMpPYNBb07LMkKG3695NRXEXNPGNhX9jIU+LOyNoKQnVoB59RTMbL4X6UpVUZxTiq", + "q3H0zI8JsT69XgZnNFwrg4a7V/6ikKIXkADiMEP3H/jx5bOp1TuWbOfKQQJubgzR3C8Qm/iihUXK8b2Y/g+", + "5vPkU7AFowzAo7zseqtOWqpXU3k8zRVojAcJl+v2kPZ7uo4CrZDLxF3q1r1nPiaSNx45KCFYfaARTmNkyUk", + "pr9xhNPGPL3Kd+jFsTkWBn8uQxYPbA+fE+baV2TXU3EFnQSheoJK6GlVneAYfWBT3Aw2M6YoecqwxK9yzKM", + "JrPlQMtpC9hA1lZirmyAJOo4gwQBInlwjF0wJmQn153/5WnJH/+uyZmA2ut6+iU1M24PjdW03GFVC7yvsLF", + "4r9Qe/FNiRAH7sntPcQdBigcYlZoXqA9zU37wKTXNCt2+DUhw2rbSpOprLcP409cvFsHDFp58mdZCp6alvB", + "mcQ5POzl3mD+F6x6ir7sRq5PE7AkU7osWqCG9kIIiAoK+mgheY0W/bd9/Wcf1iTb5yVCrbE7crETytfr12B", + "Al0OQmwPGNE9abMcORaBvfXw8n7GPDoIrFshwJMlo2RkwmCrKHlNch8clrV9YNQe14XX14JKb6uOLgRp11P", + "2x0a3RQNcI5CO0irtjQk6CeIas6zv9hCyV0MYf1GjCSs7i4E+OhhVxS3wX8gkTUxcQTjGiUayZuf0YW1a+O", + "d/fpip9BuR1N87yJbAps+BxqKkXlnnrX7sGREH8jQTK/WAfc9rdXiQqW5rtLWDZsWw9wd8LMIEOppMsiWHE", + "bpvg9Xe7R5Q14VT5bQ+0cPp0Ep82PZIgosvYMdtr+NRNXp5XgFnehBewSWwFxyk5kCUPCl71D2nImsWks6N", + "lnScPg8LokUPNfUNr07yejuIq1i2156yosnJp5xsK+sJGnfyhfVHI5BbHEnZG1FYTq0CHMCCPZDX7GDj6jm", + "IyXw/3rbzoOQB5X60PYPGrZV41jpoml/BXeGXWJew5HQESkTmwql9GMzTBY159ZMOtw3zkyzsCmJ/lLLx08", + "ax1yY/YU+G3yi77qYgJrV/bevRkp144Gb0hxkL3BofTE8yQKAPpEpV1l6IOU7P8Qk4SPPnuNGkEKEkO375s", + "1s6GpFi1SoNDiOD/apMa2ieimpUxUoMdsuT8zgN000UNLlIjVR4nqphoNHhnOHfwdr8P/fnPynfj+Wmmy+m", + "aL1wzx0udg27AyXWhEK+lPpqFnbBEoGgRzRDb1h+STkGVrxF48sQktXo6Vx6p9gLlINSAJSxo9VinQcZDd1", + "rTCP/+DO2aDLn8EGtKi8E+n6xKyZaSU1u4xmlc0PQIaZ6WMeMaWuU/9GLedlw8vg3SMoSYiwc7kyWPAw3NY", + "WChA99bsgfPjfdpK7QnQanWxU977mupuILKglS5/u/e2fikBOFBJXA0rs7wDtRjFm+c6KBUOrQt6gIfHdOv", + "8kuxMDlNixA45VxmU7lkhX6DB1R16T//yo8d4IYN8GqM6UbSoF2o1UZHq4TKqUdAACHwtuz5Ha7XGnUoG0S", + "aO5F8Lho9FMKEW9LDTFfgLREdtJh+cbB3XfWlzHG8nyDIs8OXQ5rPeHd5bXoV8DuX4j8LISfWa80M6DCkuS", + "HWSpmuVv+LB4YSJmT4Et1tcv2zIp5J70sipxH+h9uKbEiEhLjhgLhKGNw7ck9t7iDsM640KTbcBrxpQOMSs", + "0LxAe7VpXTocNdRtmpv2gUmvaVZ/ym8XhSb9QOzwa0KG1baVCaHy1EpcIoMmU1lvH8afuMMCwPnTTwuueLc", + "OGLTy5M+d5peOeHtw2bIUPDUt4c3iV0Wlo+FoWfQAAAAAAAAAAH+du6PRNu0K/jp3R6Nt2hWBp8zkcls3H/", + "x17o5G27Qrg+hVLZftWSECT5nJ5bZuPn3SImo0gIM0+OvcHY22aVeHdme+XICEXQbRq1ou27NCeUwQ+f/tX", + "kgEnjKTy23dfHsDiTAaWzB2+qRF1GgAB2mFOf53uTbqY/DXuTsabdOuj0oCmMtbPqQO7c58uQAJu3Fwdd9o", + "NuSxDKJXtVy2Z4VzP+wWjYCKj/KYIPL/272QjQWbUS7tUJoIPGUml9u6+Xeh3oVG7Vfz9gYSYTS2YOyJm6n", + "C5YCN5vRJi6jRAA7Si9QwCwA249gKc/zvcm3Ux3XuR0yjWznNizzkL2f8f2n0oV+MtsqSY3UGk2jEkaV8Cp", + "soyxWnSHZ3SQqhISfLQgjUsQLwESZIiXN95oJKEVf27sZFU3z8XXPXODLqShY+DEqDkTt8+zSN7U91SSfMK", + "/Jw9NaYESEhj6LWvKyRohXwP20ffadPH3GYofsP/HgADgUaWN7KlQp7610UfZGsxwR25resp0HNhdEqU978", + "dtL6TJHwD8qb2Iees5o7Shjs+AMIOep89eZ5pMTdmCfC+QY5f35JES/zgwCBCfAnxZD8nTqqIREomn069k5", + "TSh+FAqdN7YJ88o9/dW+HtvxxuwDo1CRnypyxgU8YwBWRq67+0qNjxKdGpBZ5yF/O+P/SaeRz/B/OEtjoQ7", + "8YbZUlx5feBLu8o8jN6gwm0YgjS/mVkZ1yWRWm8xQ2UZYrTpHsa6vqNfp4fObukhRCQ06WhZEPr+GSeHuPE", + "KhjBeAjTJBvNdimMRWhmhLn+swFlSKubXpBb9Sjz6Ts3Y2Lpvj4u5NANih3zhWx5q5xZNSVLHyZM8rHBaPB", + "dhiUBiN3+PZpZwm9gKbOG2Ma25/qkk6YV2VGJElDeHVd5OHorTEjQkKbfFMO4BWvSB5FrXlZI0UrYdgW2og", + "VqCHgf9o++k6fPp/iYZ0reHI04jBD9x/48QCdrfhUzs4cChwKNLC8lSsVY5ePE22jxh+dRSxwqQSAu+LYl9", + "N4Mm2xY39bNwppWq4c4uCU21+3pGEwwv7v3zSQHq15XT7p2ZqfCrW5TLLuheCXDhqdhAOPZa7wbSSy6ewaM", + "0vO9YQE5puUhyqH3zP55Ak8iVbp3vOZ2x7jYmldx+ZGpUCzX7DNZ+FppMEEh9IYfNIHEDJq2G2SlUuzaVMV", + "Eg8u6GJfvh+TqOIMEASJAOw1Wa/BMmQKked7xfWy5z7uesBmJIQKNG/dDIJW3z0rEEC3IYfp0CGVeUlWPt8", + "6Qurk8vXv6ddIa0M+EZ2y4FcU3oWyTIQNXWkMp9h4BI5pFpEce6kyY2OXNtCf22lUfOirazwKX7l2R2EH58", + "/XJpE4/LxEHuHLm7lbcKBsuvyExsbLA72MEY67FOlpiQySusSJUspYOn+wRS6eLiphSK86syWN+1elpb+K2", + "/pCYU/GwBdgWZNXosxBsKy94QyV0z4tFx4wOnjZQ/81dAS6++08Yo7X1YwW573FQjOn1yH4wlj5kHbhzPK3", + "tr7c1br1P8grBX8EjBg1SYzJm3bXLyo2EXI4p+HCIEvDUFKTYUEUNF7r8UJXrB61+ScVMAybAcpknLbhOnY", + "LT11iwVgMnGgwwNliiTpxYrFnFYb7YUZ9zvquJSpXq3ezKIxPHtcoQ8y1N+zP4cVJTRL7CL268lYyj0CrbI", + "wfXMxd48ioK1n4s8BYa3kdtPIyZ5SPC0aD7U36LyzacG7nMCgNRu7w7dNPtbblP8YA2c4SegFNnTfGsY/Bo", + "pyr2sw0tj/VJZ0wr0srhHb0q92lyoxIkobw6rq1EfMxV8YHsMjD0VtjRoSEt15q+LJwaY42+aYcwCtekUlk", + "Hb8RHbObPIpa87JGilZDF+FQY3BnXMKwLbQRK1BDvS2WF8AdvUnA/7R99J0+fb9iD94lq9N3PsXDOlfw5Gh", + "BWHiZhsYJYsRhhu4/8OMBu/w9Te7GDgs6W/GpnJ05FEXGSgpNq9QeOBRoYHkrVypHidPDqB26IMYuHyfaRo", + "0/ubOkhAtwYDVRGM+4AS/ZQy6FdBvQGTRJryK4/6JCA1bQvwNcc3TuXK1tITZH9G1o0vCalZbCgGJTV1Zx5", + "Jm3fSzK7dI1r1p3qfMTpYyZsBTWbqgGXa9dHlfJZOIv9GoBKFTfQf7ChwtVhv0rykIEPyobRogbdOk1q7yK", + "bGkv3irUITHPuBkzIKHPdoMbQgrt3lLNIMp05+df9QHEuC/Q+CBoumdpGT3yXbqYDV2ZvsYiJyOujK9TzKO", + "A70r+9GTT3B1U6S/CidlZJKqelvRjuia5ET1Hwo6wpx7d2TWZua/Yg2Z65K9UpaVRRBDQL9eR2sz/swEZOp", + "tbazNXc0INhCT2iPSidOCO2iQrl2bTpiqluZA0t+VLICQeXNDFvnw/W4PncxSIkTUmUcUZIAgSAVnMfrrxP", + "v8L2GuyXoNlyBSn9gn9UlMlHiLP94rrZc99XVJMKTpTInfc9YDNSAgVaKNoO26ZPvhi3roZBK2+e1ahJ6Kn", + "fIiWXCCAbkMO06FDXx3V4N/lTEkq85KsfL51hFVuKQ+tiJiO1Mnl69/Tr5GrVF5IDuVCm9aGfCI6ZcGvqRv", + "HgetTLKUovAtlmQgbulchsMZIPvaw0hhOsfEIHNOthfUSID7x2SwiOfZSZcbGU7+CVYNTK8wubaA/t9Oo+F", + "HwG5xm5UXy0FfXeBS+cu2vymzbxYif5wAAAAAAAAAAAPUEklguvLBreZ584nqhVWuMmu66VB3l1vI8+cT1Q", + "qvWBzhrnNv+G72LooUmj+P+vX6mF36hX07Hdu6q2s1cYseD6jiC4+DSrA9w1ji3/Tes+nREYJlBhxGE0lMe", + "OB7JEXHWwUYWonl6/Uwv/EK/nHoISL2kbAMsju3cVbWbucSOGNjH7bUFdOWUQilX4RiR5WFGuw/PpCFYH+C", + "scW77b1jq5D4pQEffM2Z+0JMUWjozk3pCyzrmikmbMv9vVuWmSW42bTd4WRYi4qyDjSxE8yIXqBHVAvhDn2", + "kOBqujpw2fnAqU840bvfQQkHpJ2QZY9OWU6BH3uuh3SC7zORGqvXe9KmFhPxYNHDGwj9trC+gcxLQdg0W3W", + "KG6Egr95OgWoU8WmKXKVKbKw4x2H55JQ8o2iORHsPXzsD7AWePc9t+wy8TLu/JKb9tHXiUBpleK27Jat1mI", + "6zpmzPygJym0dGY5+DJ/BwjEDbVi3MVTFSENQGZOnX2pkfml8qaMihN5+VD2NNSkr8mS3GzabvCyLJIpaEg", + "23g6cL1fOX0h/UdIvosrNEFHtYkQuUCOqBfCHRNtUsfIrTDc+0xwMVkdPGz4mGJ4OafOrVaqCcLQ97k5VX4", + "bi7BNS/ughIPWSsg2w6NQkZ8qcsQCDWL6JcMis5YOtuhso5hBVhQPLviAEjU+F9s8seCox/+56VcLCfiwa7", + "o9RUJpQkKpT8fdH5PHP5FME89W833NUOIhpOwaLbrE4fW2pXqXSAUJ1JRT6ydEtQoAhhqLnbZ0pDLtoGLNw", + "eCn5v/pAnczIlIcZ7T48k4aUch1/ZhIvNv/+h5HcRjLT/wuDA4RojmML7hfrlZ80iwsbE3nNsYg7YJeJl3f", + "lld5gYo0FL8spbt0cKxJRanYg3ekvgAlEypC2ZbVusxDXdbaQsfzrPmvFzJj5QU9SaOnMbf3TF3zUWafhZz", + "2tKMm8pxRjr/UGdQwaasW4i6cqQhqfwSrTiZbycRNbxGndixdx5l9WMfM3p/JL5U0ZFSfy8r7h30E7m0KZM", + "nsx+2+Gp5nHf6OjQToXJLnZtN3gZVkkTN0mhc7Z6U/AR8g/msQMTzVDWme0eLw1PQvnw9h7kDXID3Wb9scg", + "XkSVmyGi2sVesZEJeYxmdePPNx4HLTk74zozjF8DhYuItqli5VeYbohDrfC9eSTefKY5GKyOnjZ8Uz2K9KA", + "ihhffp2RO9D9jFyqj9hbag9OqVAXhaHvcnaqhAXMwVWAtwS2bnYoBfcjB2J8P0i/BeLvQ17J2Q8JUuyXTIC", + "5tfuTQqUnOlDljAdBcTVzMF9+xbSLrS7K2gP9t1+/Z6pg8TwZbdTdQzCGqBq5xpQjinRoKB5Z9QQganwryk", + "u8ZJqYvYX4IAaNyu8phiwyT+1wHetz1qoSF/Vg03ACuFt3T5IS3jDT4Z4f5Ybd5MGo/qUXRzXF415vFRv3N", + "hHxFw+v6TaYI5qt5v+eopv3iOSGRWxgbg0QuXzAEVht2QLwHHrjmcPraUr1KpQNwD97A5WQZs4TqSij0k6N", + "bhB9Ouqy9H+vvk9RUFukCDu9m0MZOx76+Uhh20TBm4fBS7XJDaEhdQDlh6K3SHEClOZTsP4oy/BVDnKSCLl", + "7/OUNpoBB2cEOJKOU6/swkXmwoED5slAri3JVumHvqq72SlZuc6bKFASL+FwYHCNEcx/7iApVQ/6B3fU+4j", + "ngZsCJ9urwcIDcMkhY2JvKaYxF3FsMiYMJNrcervYR3vOzyiatIgOXkwk45wMQaC16WU9zAMR6ZBrjvbLo5", + "ViSi1OxAusxStvr6UPDRQMhYQK5NFdG1zMoYgPGlbMtq3WYhrutsPm5PPg8SWwey9KGEWw++B0fwM9x1sw7", + "zomTbzYIJ5vNXYEmVrLVWmNv6py/4qLOYLv41d9YUAyVQWCIJd0tNJaVcsFFZ9/1OKcZe6w3qGE7cwsyzI1", + "aoNNSKcRdPVYQ0IY7jT2HpNF+tFA31NfTRX1gQn60bSGHiJraI07oXL+LTshqLlKufiV8o9DHAtnqJqixma", + "e4Kyo8EXcNhDJfQj/FZUTkiK2DkfcO/g3Y2heSIxy3bWIo1WfZhOqX51XtZA2Wo/ddpyzKP/0ZHg3QuMnr7", + "1B+tyJ5IcrNpu8HLskiHt/vj73cCIwstFVm7aucj/imHAZXWV56Aj5B/NIkZnnWLAicaNan1+RHsnU4oTPU", + "MFX7FYJT8AemBltSXLhQBHIUEjLmSpGqQH+o27Y9BamUbeG7DM/HXG71vEGJsv9fuuf1ITNAPvGIjE/IYze", + "q8lyeBqjZxWsafbzwOWnJ2xmprrlZ0zsat5vFA7CDTI60T9dK0Dm+TEG1TxcqvMN0QmFdXkoGMbXsUzbko1", + "ZGIe+HJK3D7LTj4THMwWB09bfi5d6IAM4HdkzXtTLpnnDiTwOne4kkgiC6+T8mc6H/GLktLW8TGw3ZFx9G1", + "fpLek0Uy1ScmvGIjPzqdmoLQYQ8/z5kI2v7dv1RDA+ZgqsBaVLYHdDiEfOrpyKFjRiUjpOk9pfEeC58UgrE", + "/H6RfgvGCRDuN/HE+QXahr2XthoSpdlSr97WoOBkd2DEZD/wl/B0tNYtX0plMoFOTnClzxgKgppcOcV16ss", + "sqDeDLCWdXy98JcpMn2+ex10HPN0vYy7EiRV1vZWR72q7fs9UxeZ7aW9shjR/FLmclfTbzvppgZ9B5pKuQJ", + "tAMXONKEcQ7NQyp59hJ6oeFAAAAAAAAAAB5iTUwyPBuf/ISa2CQ4d3+i5teUFgRs4GPtkGYc+ViyfY/dKi7", + "FQy2faQq+OMEvzcELR/IK/TRSHX+FGi07BymDHchWHwcctmH7H8IJA3BWP5lSjjs/a8n+khV8McJfm+DwWD", + "AD/kQEAhaPpBX6KORcdMLoJ8Yze6Bb76IO//gePjmi7jzD44Hc33V6KsePYYK9ODYY+5T+Q7Z/xBIGoKxd1", + "DKIIDq7M78y5Rw2PtfT4VCoUAQCzEw9JGq4I8T/N6NGJ/QR+OSoQaDwYAf8iEgfwr0sNcCT197J+t4/PaeF", + "wKu3kg0BvBoiTWAGGwXQ+nwvLUopOctlgLffBF3/sHxe1ZJIb8Or47wzRdx5x8cD4lEIkEv73JwjWk9iQQb", + "ozj04Ai5zOvNR397VumU+n7GBvJj2VwKELl3IWh5wxLdVw6oXUkL4rMohTMDGVPzAKn8ujYpmwNu1viXKeG", + "w97+egR4c0XgH0eEKhUKBIBZiYHMMd7Ho5gwfg7DCmUwBIYn6OfephPFP9nGiqfnc4Px3CCucyRQQkggMBo", + "MBP+RDQHWPtjH3FC0//hToYa8Fnr6Hnd1RZ/XwwfZO1vH47T0vj8fjwTAdU1AEXL2RaAzg0X3ViKGg/I6ue", + "fiXaYsIX+YAcaJZQ/gxmYvq/Akb6YIY8mPJOdMZ7GdvLW56vdpa1xakW0p1KjSonT8FGi07hynktjAq5cvp", + "VuCbL+LOPzgemRIa0gbPVmESiUSCXt7l4GsAcbKWLoufGtN6Egk2RnFjWk8iwcYoDujBEXKZ15uPkUgkQlE", + "n9fCVZTuKetMkuOzsDrqyI0rHZ3dQ6uoy+UYe/mXaIsKXOe5C0PKGJbqvl8vlwk7V1NAcULuSFsRnUWXZjq", + "LeNAkuYfSRavXA2GYYfaRaPTC2GZPm+gplIQWY6m/POq3Ra+ebvMSaMsmmCeI18ar6Och2aa6v+qIoe/cQJ", + "5rKatgViBQKhQJBLMTAbYOwMoncqr/mGO5i0c0ZPp+R21IZPXdBbfISa8okmyYUeydbAtT1WZ/geQtaxUbY", + "5mlMO5I1KKfiRFPzucH575vNZsNxMZeQEFY4kykgJBFp3w2j4dBKbhgMBgN+yIeAYYUzM7Y46f/qHm1j7il", + "afpOXWFMm2TQBl7pHmw0t5UnuM3Krxd2LNmWoLPudzDi3HCEZy1U8Vsjsnazj8dt7XpUUmdM5KxUhHo/Hg2", + "E6pqBnBvKzqcrI32Mr7XuCPhmXGqLYS0rOd+iROYYbEt/EaeiwsyvaL6oWmWO4i0U3Z/jg6o27jccJh2tx0", + "+vV1roGEvjm2x0m1HkW1fkTNtIFMW9czCP+ImtO5MeSc6Yz2M+dTqdDbsO2sLXJS6wpk2yazEB+nOFjAuVH", + "2yDMuXKxZD5SFfxxgt8bOn8KNFp2DlND9j8EkoZgLMhtYVTKl9OtseRUZAJnvdLAN1/EnX9wPLm+avRVjx5", + "DMiU0pA2ercJLrAGUxW7DvU+BHlzumhL1NggrbCZqfIq9k3U8fnvPC8QaQAy2i6F0NKb1JBJsjOJNL8AU2p", + "zinca0nkSCjVEcvz2rdEp9P2O7ELS8YYnuK8KZgYypeYBUSQLf3PFoM9Uwi+rsOZhdqkFY4UymgJBEONHUf", + "G5w/juzSoosNmFNusrDvxz+kSPFzu6g1NVl8o23Z5XkHZWc8jz8y7RFhC9zRXX+hI10QQy3Fje9Xm2ta86f", + "Ao2WncMURQRc3c6McJU8jWntBnwe6jigdiUtiM+iQSlDFeV4od3Ksh1FvWkSXLM7KHV1mXwjwugj1eqBsc2", + "7YRblInHfsjD6SLV6YGwzSXN9hbKQAkxNXmJNmWTTBDTXV31RlL17v0wJLQmFDvrGxTwdwXVghTZ5iTVlkk", + "0TT/C8Ba1iI2zEa+JV9XOQ7b3i12U9g/6Suc/IrRZ3L9rARv2d3odBpUvdo82GlvIkMlSW/U5mnFtDh51d0", + "X5RtToOqG0Zjj/KsZX2PUGfjEvIHMMNiW/iNMwx3MWimzN8tbjp9WprXQM+I7elMnrugkeqgpX6ioD92uQl", + "1pRJNk2jbRDmXLlYMij2TrYEqOuzUX97hsxYhcxVUmRO56xUhCzbUX4vXDr7p0APLndNiXreyToev73nBa8", + "aMb4gpSrr1pMEjuhVRJRdCFresET3FSSBb+54tJlqIKxwJlNASCJZJUUWm7AmXdK+G0bDoZXcqzcudgtR+6", + "Nbi5ter7bWNSICrm5nRrhKqZnwPj9XC8vQEMUO96dltNQ92sbcU7T8rbTv9hSj2oMmL7GmTLJpAl+mhJaEQ", + "gd9LnWPNhtaypNX/LoG06qk7Nxn5FaLuxdtpe7RZkNLeRKhw86uaL+oWthK+56gT8YlU9GlzvhedaQqWJD+", + "MK4b29g7Wcfjt/e8obJs9ytHmcMqKTKnc1YqQlOgB5e7pkQ9V40YX5BSlXUuBC1vWKL7CqWfcz8As0iL3BZ", + "GD8hDJvStxU2vV1vrGtRMeJ+fq4VlX9cmz8e6NuQmXhP/D0pYmyJzDDckvonTW/o5B+xO56zQYWdXtF9ULa", + "noUmd8rzpSWVTnT9hIF8Qg3dJ/ELh5u6tGjC9Iqco60s+5H4BZpEXW4qbXq611Da9rk+djXRtyJPDNtztMq", + "PNdefiH87zGjCyq8ydspAtiVSPGF6RUZR3euJhH/EXWnKcxrXc0tbjjoxyyvx9BaavalYeP17EH1FEO2d+P", + "oLRVKIfs70dQ2ioAQYCQwQILnAEgS1AAAAAAAAUAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAIAAAADAAAAEEtQAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAD//////////wAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhIUAAAQZyRwQILFCRpb", + "nRBcnJheUZyb21TdHJpbmcAAEGwkcECC2Ioc2l6ZV90IGlkeCwgc2l6ZV90IHNpemUpPDo6PnsgdGhyb3cg", + "J0FycmF5IGluZGV4ICcgKyBpZHggKyAnIG91dCBvZiBib3VuZHM6IFswLCcgKyBzaXplICsgJyknOyB9AA==" + ].join(""); + function _base64ToArrayBuffer(base64) { + var binary_string = window.atob(base64); + var len = binary_string.length; + var bytes = new Uint8Array(len); + for (var i = 0; i < len; i++) { + bytes[i] = binary_string.charCodeAt(i); + } + return bytes; + } + function getBinary2(file) { + if (typeof Buffer == "function") { + return Buffer.from(binaryInString, "base64"); + } else { + return _base64ToArrayBuffer(binaryInString); + } + } + function getBinaryPromise() { + return Promise.resolve().then(function() { + return getBinary2(wasmBinaryFile); + }); + } + function createWasm() { + var info8 = { + "env": asmLibraryArg, + "wasi_snapshot_preview1": asmLibraryArg + }; + function receiveInstance(instance8, module3) { + var exports4 = instance8.exports; + Module["asm"] = exports4; + wasmMemory = Module["asm"]["memory"]; + assert(wasmMemory, "memory not found in wasm exports"); + updateGlobalBufferAndViews(wasmMemory.buffer); + wasmTable = Module["asm"]["__indirect_function_table"]; + assert(wasmTable, "table not found in wasm exports"); + addOnInit(Module["asm"]["__wasm_call_ctors"]); + removeRunDependency("wasm-instantiate"); + } + addRunDependency("wasm-instantiate"); + var trueModule = Module; + function receiveInstantiationResult(result) { + assert(Module === trueModule, "the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"); + trueModule = null; + receiveInstance(result["instance"]); + } + function instantiateArrayBuffer(receiver) { + return getBinaryPromise().then(function(binary) { + return WebAssembly.instantiate(binary, info8); + }).then(function(instance8) { + return instance8; + }).then(receiver, function(reason) { + err("failed to asynchronously prepare wasm: " + reason); + if (isFileURI(wasmBinaryFile)) { + err("warning: Loading from a file URI (" + wasmBinaryFile + ") is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing"); + } + abort(reason); + }); + } + function instantiateAsync() { + return instantiateArrayBuffer(receiveInstantiationResult); + } + if (Module["instantiateWasm"]) { + try { + var exports3 = Module["instantiateWasm"](info8, receiveInstance); + return exports3; + } catch (e) { + err("Module.instantiateWasm callback failed with error: " + e); + readyPromiseReject(e); + } + } + instantiateAsync().catch(readyPromiseReject); + return {}; + } + var tempDouble; + var tempI64; + var ASM_CONSTS = {}; + function array_bounds_check_error(idx, size) { + throw "Array index " + idx + " out of bounds: [0," + size + ")"; + } + function ExitStatus(status) { + this.name = "ExitStatus"; + this.message = "Program terminated with exit(" + status + ")"; + this.status = status; + } + function callRuntimeCallbacks(callbacks) { + while (callbacks.length > 0) { + callbacks.shift()(Module); + } + } + function getValue(ptr, type = "i8") { + if (type.endsWith("*")) type = "*"; + switch (type) { + case "i1": + return HEAP8[ptr >> 0]; + case "i8": + return HEAP8[ptr >> 0]; + case "i16": + return HEAP16[ptr >> 1]; + case "i32": + return HEAP32[ptr >> 2]; + case "i64": + return HEAP32[ptr >> 2]; + case "float": + return HEAPF32[ptr >> 2]; + case "double": + return HEAPF64[ptr >> 3]; + case "*": + return HEAPU32[ptr >> 2]; + default: + abort("invalid type for getValue: " + type); + } + return null; + } + function ptrToString(ptr) { + return "0x" + ptr.toString(16).padStart(8, "0"); + } + function setValue(ptr, value, type = "i8") { + if (type.endsWith("*")) type = "*"; + switch (type) { + case "i1": + HEAP8[ptr >> 0] = value; + break; + case "i8": + HEAP8[ptr >> 0] = value; + break; + case "i16": + HEAP16[ptr >> 1] = value; + break; + case "i32": + HEAP32[ptr >> 2] = value; + break; + case "i64": + tempI64 = [value >>> 0, (tempDouble = value, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[ptr >> 2] = tempI64[0], HEAP32[ptr + 4 >> 2] = tempI64[1]; + break; + case "float": + HEAPF32[ptr >> 2] = value; + break; + case "double": + HEAPF64[ptr >> 3] = value; + break; + case "*": + HEAPU32[ptr >> 2] = value; + break; + default: + abort("invalid type for setValue: " + type); + } + } + function warnOnce(text) { + if (!warnOnce.shown) warnOnce.shown = {}; + if (!warnOnce.shown[text]) { + warnOnce.shown[text] = 1; + if (ENVIRONMENT_IS_NODE) text = "warning: " + text; + err(text); + } + } + function _abort() { + abort("native code called abort()"); + } + function getHeapMax() { + return 2147483648; + } + function emscripten_realloc_buffer(size) { + try { + wasmMemory.grow(size - buffer.byteLength + 65535 >>> 16); + updateGlobalBufferAndViews(wasmMemory.buffer); + return 1; + } catch (e) { + err("emscripten_realloc_buffer: Attempted to grow heap from " + buffer.byteLength + " bytes to " + size + " bytes, but got error: " + e); + } + } + function _emscripten_resize_heap(requestedSize) { + var oldSize = HEAPU8.length; + requestedSize = requestedSize >>> 0; + assert(requestedSize > oldSize); + var maxHeapSize = getHeapMax(); + if (requestedSize > maxHeapSize) { + err("Cannot enlarge memory, asked to go up to " + requestedSize + " bytes, but the limit is " + maxHeapSize + " bytes!"); + return false; + } + let alignUp = (x, multiple) => x + (multiple - x % multiple) % multiple; + for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); + overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); + var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)); + var replacement = emscripten_realloc_buffer(newSize); + if (replacement) { + return true; + } + } + err("Failed to grow the heap from " + oldSize + " bytes to " + newSize + " bytes, not enough memory!"); + return false; + } + var SYSCALLS = { varargs: void 0, get: function() { + assert(SYSCALLS.varargs != void 0); + SYSCALLS.varargs += 4; + var ret = HEAP32[SYSCALLS.varargs - 4 >> 2]; + return ret; + }, getStr: function(ptr) { + var ret = UTF8ToString(ptr); + return ret; + } }; + function _fd_close(fd) { + abort("fd_close called without SYSCALLS_REQUIRE_FILESYSTEM"); + } + function convertI32PairToI53Checked(lo, hi) { + assert(lo == lo >>> 0 || lo == (lo | 0)); + assert(hi === (hi | 0)); + return hi + 2097152 >>> 0 < 4194305 - !!lo ? (lo >>> 0) + hi * 4294967296 : NaN; + } + function _fd_seek(fd, offset_low, offset_high, whence, newOffset) { + return 70; + } + var printCharBuffers = [null, [], []]; + function printChar(stream2, curr) { + var buffer2 = printCharBuffers[stream2]; + assert(buffer2); + if (curr === 0 || curr === 10) { + (stream2 === 1 ? out : err)(UTF8ArrayToString(buffer2, 0)); + buffer2.length = 0; + } else { + buffer2.push(curr); + } + } + function flush_NO_FILESYSTEM() { + _fflush(0); + if (printCharBuffers[1].length) printChar(1, 10); + if (printCharBuffers[2].length) printChar(2, 10); + } + function _fd_write(fd, iov, iovcnt, pnum) { + var num = 0; + for (var i = 0; i < iovcnt; i++) { + var ptr = HEAPU32[iov >> 2]; + var len = HEAPU32[iov + 4 >> 2]; + iov += 8; + for (var j = 0; j < len; j++) { + printChar(fd, HEAPU8[ptr + j]); + } + num += len; + } + HEAPU32[pnum >> 2] = num; + return 0; + } + function intArrayFromString(stringy, dontAddNull, length) { + var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1; + var u8array = new Array(len); + var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length); + if (dontAddNull) u8array.length = numBytesWritten; + return u8array; + } + var ASSERTIONS = true; + function checkIncomingModuleAPI() { + ignoredModuleProp("fetchSettings"); + } + var asmLibraryArg = { + "abort": _abort, + "array_bounds_check_error": array_bounds_check_error, + "emscripten_resize_heap": _emscripten_resize_heap, + "fd_close": _fd_close, + "fd_seek": _fd_seek, + "fd_write": _fd_write + }; + var asm = createWasm(); + var ___wasm_call_ctors = Module["___wasm_call_ctors"] = createExportWrapper("__wasm_call_ctors"); + var _emscripten_bind_VoidPtr___destroy___0 = Module["_emscripten_bind_VoidPtr___destroy___0"] = createExportWrapper("emscripten_bind_VoidPtr___destroy___0"); + var _emscripten_bind_Crc64Hash_Crc64Hash_0 = Module["_emscripten_bind_Crc64Hash_Crc64Hash_0"] = createExportWrapper("emscripten_bind_Crc64Hash_Crc64Hash_0"); + var _emscripten_bind_Crc64Hash_OnAppend_2 = Module["_emscripten_bind_Crc64Hash_OnAppend_2"] = createExportWrapper("emscripten_bind_Crc64Hash_OnAppend_2"); + var _emscripten_bind_Crc64Hash_OnFinal_3 = Module["_emscripten_bind_Crc64Hash_OnFinal_3"] = createExportWrapper("emscripten_bind_Crc64Hash_OnFinal_3"); + var _emscripten_bind_Crc64Hash___destroy___0 = Module["_emscripten_bind_Crc64Hash___destroy___0"] = createExportWrapper("emscripten_bind_Crc64Hash___destroy___0"); + var ___errno_location = Module["___errno_location"] = createExportWrapper("__errno_location"); + var _fflush = Module["_fflush"] = createExportWrapper("fflush"); + var _malloc = Module["_malloc"] = createExportWrapper("malloc"); + var _free = Module["_free"] = createExportWrapper("free"); + var _emscripten_stack_init = Module["_emscripten_stack_init"] = function() { + return (_emscripten_stack_init = Module["_emscripten_stack_init"] = Module["asm"]["emscripten_stack_init"]).apply(null, arguments); + }; + var _emscripten_stack_get_free = Module["_emscripten_stack_get_free"] = function() { + return (_emscripten_stack_get_free = Module["_emscripten_stack_get_free"] = Module["asm"]["emscripten_stack_get_free"]).apply(null, arguments); + }; + var _emscripten_stack_get_base = Module["_emscripten_stack_get_base"] = function() { + return (_emscripten_stack_get_base = Module["_emscripten_stack_get_base"] = Module["asm"]["emscripten_stack_get_base"]).apply(null, arguments); + }; + var _emscripten_stack_get_end = Module["_emscripten_stack_get_end"] = function() { + return (_emscripten_stack_get_end = Module["_emscripten_stack_get_end"] = Module["asm"]["emscripten_stack_get_end"]).apply(null, arguments); + }; + var stackSave = Module["stackSave"] = createExportWrapper("stackSave"); + var stackRestore = Module["stackRestore"] = createExportWrapper("stackRestore"); + var stackAlloc = Module["stackAlloc"] = createExportWrapper("stackAlloc"); + var _emscripten_stack_get_current = Module["_emscripten_stack_get_current"] = function() { + return (_emscripten_stack_get_current = Module["_emscripten_stack_get_current"] = Module["asm"]["emscripten_stack_get_current"]).apply(null, arguments); + }; + var dynCall_jiji = Module["dynCall_jiji"] = createExportWrapper("dynCall_jiji"); + var ___start_em_js = Module["___start_em_js"] = 5261488; + var ___stop_em_js = Module["___stop_em_js"] = 5261586; + var unexportedRuntimeSymbols = [ + "run", + "UTF8ArrayToString", + "UTF8ToString", + "stringToUTF8Array", + "stringToUTF8", + "lengthBytesUTF8", + "addOnPreRun", + "addOnInit", + "addOnPreMain", + "addOnExit", + "addOnPostRun", + "addRunDependency", + "removeRunDependency", + "FS_createFolder", + "FS_createPath", + "FS_createDataFile", + "FS_createPreloadedFile", + "FS_createLazyFile", + "FS_createLink", + "FS_createDevice", + "FS_unlink", + "getLEB", + "getFunctionTables", + "alignFunctionTables", + "registerFunctions", + "prettyPrint", + "getCompilerSetting", + "out", + "err", + "callMain", + "abort", + "keepRuntimeAlive", + "wasmMemory", + "stackAlloc", + "stackSave", + "stackRestore", + "getTempRet0", + "setTempRet0", + "writeStackCookie", + "checkStackCookie", + "ptrToString", + "zeroMemory", + "stringToNewUTF8", + "exitJS", + "getHeapMax", + "emscripten_realloc_buffer", + "ENV", + "ERRNO_CODES", + "ERRNO_MESSAGES", + "setErrNo", + "inetPton4", + "inetNtop4", + "inetPton6", + "inetNtop6", + "readSockaddr", + "writeSockaddr", + "DNS", + "getHostByName", + "Protocols", + "Sockets", + "getRandomDevice", + "warnOnce", + "traverseStack", + "UNWIND_CACHE", + "convertPCtoSourceLocation", + "readEmAsmArgsArray", + "readEmAsmArgs", + "runEmAsmFunction", + "runMainThreadEmAsm", + "jstoi_q", + "jstoi_s", + "getExecutableName", + "listenOnce", + "autoResumeAudioContext", + "dynCallLegacy", + "getDynCaller", + "dynCall", + "handleException", + "runtimeKeepalivePush", + "runtimeKeepalivePop", + "callUserCallback", + "maybeExit", + "safeSetTimeout", + "asmjsMangle", + "asyncLoad", + "alignMemory", + "mmapAlloc", + "writeI53ToI64", + "writeI53ToI64Clamped", + "writeI53ToI64Signaling", + "writeI53ToU64Clamped", + "writeI53ToU64Signaling", + "readI53FromI64", + "readI53FromU64", + "convertI32PairToI53", + "convertI32PairToI53Checked", + "convertU32PairToI53", + "getCFunc", + "ccall", + "cwrap", + "uleb128Encode", + "sigToWasmTypes", + "generateFuncType", + "convertJsFunctionToWasm", + "freeTableIndexes", + "functionsInTableMap", + "getEmptyTableSlot", + "updateTableMap", + "addFunction", + "removeFunction", + "reallyNegative", + "unSign", + "strLen", + "reSign", + "formatString", + "setValue", + "getValue", + "PATH", + "PATH_FS", + "intArrayFromString", + "intArrayToString", + "AsciiToString", + "stringToAscii", + "UTF16Decoder", + "UTF16ToString", + "stringToUTF16", + "lengthBytesUTF16", + "UTF32ToString", + "stringToUTF32", + "lengthBytesUTF32", + "allocateUTF8", + "allocateUTF8OnStack", + "writeStringToMemory", + "writeArrayToMemory", + "writeAsciiToMemory", + "SYSCALLS", + "getSocketFromFD", + "getSocketAddress", + "JSEvents", + "registerKeyEventCallback", + "specialHTMLTargets", + "maybeCStringToJsString", + "findEventTarget", + "findCanvasEventTarget", + "getBoundingClientRect", + "fillMouseEventData", + "registerMouseEventCallback", + "registerWheelEventCallback", + "registerUiEventCallback", + "registerFocusEventCallback", + "fillDeviceOrientationEventData", + "registerDeviceOrientationEventCallback", + "fillDeviceMotionEventData", + "registerDeviceMotionEventCallback", + "screenOrientation", + "fillOrientationChangeEventData", + "registerOrientationChangeEventCallback", + "fillFullscreenChangeEventData", + "registerFullscreenChangeEventCallback", + "JSEvents_requestFullscreen", + "JSEvents_resizeCanvasForFullscreen", + "registerRestoreOldStyle", + "hideEverythingExceptGivenElement", + "restoreHiddenElements", + "setLetterbox", + "currentFullscreenStrategy", + "restoreOldWindowedStyle", + "softFullscreenResizeWebGLRenderTarget", + "doRequestFullscreen", + "fillPointerlockChangeEventData", + "registerPointerlockChangeEventCallback", + "registerPointerlockErrorEventCallback", + "requestPointerLock", + "fillVisibilityChangeEventData", + "registerVisibilityChangeEventCallback", + "registerTouchEventCallback", + "fillGamepadEventData", + "registerGamepadEventCallback", + "registerBeforeUnloadEventCallback", + "fillBatteryEventData", + "battery", + "registerBatteryEventCallback", + "setCanvasElementSize", + "getCanvasElementSize", + "demangle", + "demangleAll", + "jsStackTrace", + "stackTrace", + "ExitStatus", + "getEnvStrings", + "checkWasiClock", + "flush_NO_FILESYSTEM", + "dlopenMissingError", + "createDyncallWrapper", + "setImmediateWrapped", + "clearImmediateWrapped", + "polyfillSetImmediate", + "uncaughtExceptionCount", + "exceptionLast", + "exceptionCaught", + "ExceptionInfo", + "exception_addRef", + "exception_decRef", + "Browser", + "setMainLoop", + "wget", + "FS", + "MEMFS", + "TTY", + "PIPEFS", + "SOCKFS", + "_setNetworkCallback", + "tempFixedLengthArray", + "miniTempWebGLFloatBuffers", + "heapObjectForWebGLType", + "heapAccessShiftForWebGLHeap", + "GL", + "emscriptenWebGLGet", + "computeUnpackAlignedImageSize", + "emscriptenWebGLGetTexPixelData", + "emscriptenWebGLGetUniform", + "webglGetUniformLocation", + "webglPrepareUniformLocationsBeforeFirstUse", + "webglGetLeftBracePos", + "emscriptenWebGLGetVertexAttrib", + "writeGLArray", + "AL", + "SDL_unicode", + "SDL_ttfContext", + "SDL_audio", + "SDL", + "SDL_gfx", + "GLUT", + "EGL", + "GLFW_Window", + "GLFW", + "GLEW", + "IDBStore", + "runAndAbortIfError", + "ALLOC_NORMAL", + "ALLOC_STACK", + "allocate" + ]; + unexportedRuntimeSymbols.forEach(unexportedRuntimeSymbol); + var missingLibrarySymbols = [ + "zeroMemory", + "stringToNewUTF8", + "exitJS", + "setErrNo", + "inetPton4", + "inetNtop4", + "inetPton6", + "inetNtop6", + "readSockaddr", + "writeSockaddr", + "getHostByName", + "getRandomDevice", + "traverseStack", + "convertPCtoSourceLocation", + "readEmAsmArgs", + "runEmAsmFunction", + "runMainThreadEmAsm", + "jstoi_q", + "jstoi_s", + "getExecutableName", + "listenOnce", + "autoResumeAudioContext", + "dynCallLegacy", + "getDynCaller", + "dynCall", + "handleException", + "runtimeKeepalivePush", + "runtimeKeepalivePop", + "callUserCallback", + "maybeExit", + "safeSetTimeout", + "asmjsMangle", + "asyncLoad", + "alignMemory", + "mmapAlloc", + "writeI53ToI64", + "writeI53ToI64Clamped", + "writeI53ToI64Signaling", + "writeI53ToU64Clamped", + "writeI53ToU64Signaling", + "readI53FromI64", + "readI53FromU64", + "convertI32PairToI53", + "convertU32PairToI53", + "getCFunc", + "ccall", + "cwrap", + "uleb128Encode", + "sigToWasmTypes", + "generateFuncType", + "convertJsFunctionToWasm", + "getEmptyTableSlot", + "updateTableMap", + "addFunction", + "removeFunction", + "reallyNegative", + "unSign", + "strLen", + "reSign", + "formatString", + "intArrayToString", + "AsciiToString", + "stringToAscii", + "UTF16ToString", + "stringToUTF16", + "lengthBytesUTF16", + "UTF32ToString", + "stringToUTF32", + "lengthBytesUTF32", + "allocateUTF8", + "allocateUTF8OnStack", + "writeStringToMemory", + "writeArrayToMemory", + "writeAsciiToMemory", + "getSocketFromFD", + "getSocketAddress", + "registerKeyEventCallback", + "maybeCStringToJsString", + "findEventTarget", + "findCanvasEventTarget", + "getBoundingClientRect", + "fillMouseEventData", + "registerMouseEventCallback", + "registerWheelEventCallback", + "registerUiEventCallback", + "registerFocusEventCallback", + "fillDeviceOrientationEventData", + "registerDeviceOrientationEventCallback", + "fillDeviceMotionEventData", + "registerDeviceMotionEventCallback", + "screenOrientation", + "fillOrientationChangeEventData", + "registerOrientationChangeEventCallback", + "fillFullscreenChangeEventData", + "registerFullscreenChangeEventCallback", + "JSEvents_requestFullscreen", + "JSEvents_resizeCanvasForFullscreen", + "registerRestoreOldStyle", + "hideEverythingExceptGivenElement", + "restoreHiddenElements", + "setLetterbox", + "softFullscreenResizeWebGLRenderTarget", + "doRequestFullscreen", + "fillPointerlockChangeEventData", + "registerPointerlockChangeEventCallback", + "registerPointerlockErrorEventCallback", + "requestPointerLock", + "fillVisibilityChangeEventData", + "registerVisibilityChangeEventCallback", + "registerTouchEventCallback", + "fillGamepadEventData", + "registerGamepadEventCallback", + "registerBeforeUnloadEventCallback", + "fillBatteryEventData", + "battery", + "registerBatteryEventCallback", + "setCanvasElementSize", + "getCanvasElementSize", + "demangle", + "demangleAll", + "jsStackTrace", + "stackTrace", + "getEnvStrings", + "checkWasiClock", + "createDyncallWrapper", + "setImmediateWrapped", + "clearImmediateWrapped", + "polyfillSetImmediate", + "ExceptionInfo", + "exception_addRef", + "exception_decRef", + "setMainLoop", + "_setNetworkCallback", + "heapObjectForWebGLType", + "heapAccessShiftForWebGLHeap", + "emscriptenWebGLGet", + "computeUnpackAlignedImageSize", + "emscriptenWebGLGetTexPixelData", + "emscriptenWebGLGetUniform", + "webglGetUniformLocation", + "webglPrepareUniformLocationsBeforeFirstUse", + "webglGetLeftBracePos", + "emscriptenWebGLGetVertexAttrib", + "writeGLArray", + "SDL_unicode", + "SDL_ttfContext", + "SDL_audio", + "GLFW_Window", + "runAndAbortIfError", + "ALLOC_NORMAL", + "ALLOC_STACK", + "allocate" + ]; + missingLibrarySymbols.forEach(missingLibrarySymbol); + var calledRun; + dependenciesFulfilled = function runCaller() { + if (!calledRun) run9(); + if (!calledRun) dependenciesFulfilled = runCaller; + }; + function stackCheckInit() { + _emscripten_stack_init(); + writeStackCookie(); + } + function run9(args) { + args = args || arguments_; + if (runDependencies > 0) { + return; + } + stackCheckInit(); + preRun(); + if (runDependencies > 0) { + return; + } + function doRun() { + if (calledRun) return; + calledRun = true; + Module["calledRun"] = true; + if (ABORT) return; + initRuntime(); + readyPromiseResolve(Module); + if (Module["onRuntimeInitialized"]) Module["onRuntimeInitialized"](); + assert(!Module["_main"], 'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'); + postRun(); + } + if (Module["setStatus"]) { + Module["setStatus"]("Running..."); + setTimeout(function() { + setTimeout(function() { + Module["setStatus"](""); + }, 1); + doRun(); + }, 1); + } else { + doRun(); + } + checkStackCookie(); + } + function checkUnflushedContent() { + var oldOut = out; + var oldErr = err; + var has = false; + out = err = (x) => { + has = true; + }; + try { + flush_NO_FILESYSTEM(); + } catch (e) { + } + out = oldOut; + err = oldErr; + if (has) { + warnOnce("stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the FAQ), or make sure to emit a newline when you printf etc."); + warnOnce("(this may also be due to not including full filesystem support - try building with -sFORCE_FILESYSTEM)"); + } + } + if (Module["preInit"]) { + if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]]; + while (Module["preInit"].length > 0) { + Module["preInit"].pop()(); + } + } + run9(); + function WrapperObject() { + } + WrapperObject.prototype = Object.create(WrapperObject.prototype); + WrapperObject.prototype.constructor = WrapperObject; + WrapperObject.prototype.__class__ = WrapperObject; + WrapperObject.__cache__ = {}; + Module["WrapperObject"] = WrapperObject; + function getCache(__class__) { + return (__class__ || WrapperObject).__cache__; + } + Module["getCache"] = getCache; + function wrapPointer(ptr, __class__) { + var cache = getCache(__class__); + var ret = cache[ptr]; + if (ret) return ret; + ret = Object.create((__class__ || WrapperObject).prototype); + ret.ptr = ptr; + return cache[ptr] = ret; + } + Module["wrapPointer"] = wrapPointer; + function castObject(obj, __class__) { + return wrapPointer(obj.ptr, __class__); + } + Module["castObject"] = castObject; + Module["NULL"] = wrapPointer(0); + function destroy(obj) { + if (!obj["__destroy__"]) throw "Error: Cannot destroy object. (Did you create it yourself?)"; + obj["__destroy__"](); + delete getCache(obj.__class__)[obj.ptr]; + } + Module["destroy"] = destroy; + function compare3(obj1, obj2) { + return obj1.ptr === obj2.ptr; + } + Module["compare"] = compare3; + function getPointer(obj) { + return obj.ptr; + } + Module["getPointer"] = getPointer; + function getClass(obj) { + return obj.__class__; + } + Module["getClass"] = getClass; + var ensureCache = { + buffer: 0, + // the main buffer of temporary storage + size: 0, + // the size of buffer + pos: 0, + // the next free offset in buffer + temps: [], + // extra allocations + needed: 0, + // the total size we need next time + prepare: function() { + if (ensureCache.needed) { + for (var i = 0; i < ensureCache.temps.length; i++) { + Module["_free"](ensureCache.temps[i]); + } + ensureCache.temps.length = 0; + Module["_free"](ensureCache.buffer); + ensureCache.buffer = 0; + ensureCache.size += ensureCache.needed; + ensureCache.needed = 0; + } + if (!ensureCache.buffer) { + ensureCache.size += 128; + ensureCache.buffer = Module["_malloc"](ensureCache.size); + assert(ensureCache.buffer); + } + ensureCache.pos = 0; + }, + alloc: function(array2, view) { + assert(ensureCache.buffer); + var bytes = view.BYTES_PER_ELEMENT; + var len = array2.length * bytes; + len = len + 7 & -8; + var ret; + if (ensureCache.pos + len >= ensureCache.size) { + assert(len > 0); + ensureCache.needed += len; + ret = Module["_malloc"](len); + ensureCache.temps.push(ret); + } else { + ret = ensureCache.buffer + ensureCache.pos; + ensureCache.pos += len; + } + return ret; + }, + copy: function(array2, view, offset) { + offset >>>= 0; + var bytes = view.BYTES_PER_ELEMENT; + switch (bytes) { + case 2: + offset >>>= 1; + break; + case 4: + offset >>>= 2; + break; + case 8: + offset >>>= 3; + break; + } + for (var i = 0; i < array2.length; i++) { + view[offset + i] = array2[i]; + } + } + }; + function ensureString(value) { + if (typeof value === "string") { + var intArray = intArrayFromString(value); + var offset = ensureCache.alloc(intArray, HEAP8); + ensureCache.copy(intArray, HEAP8, offset); + return offset; + } + return value; + } + function ensureInt8(value) { + if (typeof value === "object") { + var offset = ensureCache.alloc(value, HEAP8); + ensureCache.copy(value, HEAP8, offset); + return offset; + } + return value; + } + function ensureInt16(value) { + if (typeof value === "object") { + var offset = ensureCache.alloc(value, HEAP16); + ensureCache.copy(value, HEAP16, offset); + return offset; + } + return value; + } + function ensureInt32(value) { + if (typeof value === "object") { + var offset = ensureCache.alloc(value, HEAP32); + ensureCache.copy(value, HEAP32, offset); + return offset; + } + return value; + } + function ensureFloat32(value) { + if (typeof value === "object") { + var offset = ensureCache.alloc(value, HEAPF32); + ensureCache.copy(value, HEAPF32, offset); + return offset; + } + return value; + } + function ensureFloat64(value) { + if (typeof value === "object") { + var offset = ensureCache.alloc(value, HEAPF64); + ensureCache.copy(value, HEAPF64, offset); + return offset; + } + return value; + } + function VoidPtr() { + throw "cannot construct a VoidPtr, no constructor in IDL"; + } + VoidPtr.prototype = Object.create(WrapperObject.prototype); + VoidPtr.prototype.constructor = VoidPtr; + VoidPtr.prototype.__class__ = VoidPtr; + VoidPtr.__cache__ = {}; + Module["VoidPtr"] = VoidPtr; + VoidPtr.prototype["__destroy__"] = VoidPtr.prototype.__destroy__ = /** @suppress {undefinedVars, duplicate} @this{Object} */ + function() { + var self2 = this.ptr; + _emscripten_bind_VoidPtr___destroy___0(self2); + }; + function Crc64Hash() { + this.ptr = _emscripten_bind_Crc64Hash_Crc64Hash_0(); + getCache(Crc64Hash)[this.ptr] = this; } + ; + ; + Crc64Hash.prototype = Object.create(WrapperObject.prototype); + Crc64Hash.prototype.constructor = Crc64Hash; + Crc64Hash.prototype.__class__ = Crc64Hash; + Crc64Hash.__cache__ = {}; + Module["Crc64Hash"] = Crc64Hash; + Crc64Hash.prototype["OnAppend"] = Crc64Hash.prototype.OnAppend = /** @suppress {undefinedVars, duplicate} @this{Object} */ + function(data, length) { + var self2 = this.ptr; + if (data && typeof data === "object") data = data.ptr; + if (length && typeof length === "object") length = length.ptr; + _emscripten_bind_Crc64Hash_OnAppend_2(self2, data, length); + }; + ; + Crc64Hash.prototype["OnFinal"] = Crc64Hash.prototype.OnFinal = /** @suppress {undefinedVars, duplicate} @this{Object} */ + function(data, length, result) { + var self2 = this.ptr; + if (data && typeof data === "object") data = data.ptr; + if (length && typeof length === "object") length = length.ptr; + if (result && typeof result === "object") result = result.ptr; + _emscripten_bind_Crc64Hash_OnFinal_3(self2, data, length, result); + }; + ; + Crc64Hash.prototype["__destroy__"] = Crc64Hash.prototype.__destroy__ = /** @suppress {undefinedVars, duplicate} @this{Object} */ + function() { + var self2 = this.ptr; + _emscripten_bind_Crc64Hash___destroy___0(self2); + }; + return NativeCRC642.ready; }); - } - function padStart2(currentString, targetLength, padString = " ") { - if (String.prototype.padStart) { - return currentString.padStart(targetLength, padString); + })(); + module2.exports = NativeCRC64; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/StorageCRC64Calculator.js +var require_StorageCRC64Calculator = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/StorageCRC64Calculator.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - padString = padString || " "; - if (currentString.length > targetLength) { - return currentString; - } else { - targetLength = targetLength - currentString.length; - if (targetLength > padString.length) { - padString += padString.repeat(targetLength / padString.length); + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageCRC64Calculator_exports = {}; + __export2(StorageCRC64Calculator_exports, { + StorageCRC64Calculator: () => StorageCRC64Calculator + }); + module2.exports = __toCommonJS2(StorageCRC64Calculator_exports); + var import_crc64 = __toESM2(require_crc64()); + var StorageCRC64Calculator = class _StorageCRC64Calculator { + nativeCrc64Hash; + static nativeInstance; + constructor() { + this.nativeCrc64Hash = new _StorageCRC64Calculator.nativeInstance.Crc64Hash(); + } + static initPromise; + /** + * Initialize environment for CRC64 checksum calculator + */ + static async init() { + if (!this.initPromise) { + this.initPromise = (0, import_crc64.default)().then((instance8) => { + this.nativeInstance = instance8; + return; + }); } - return padString.slice(0, targetLength) + currentString; + return this.initPromise; } - } - function sanitizeURL(url2) { - let safeURL = url2; - if (getURLParameter(safeURL, constants_js_1.URLConstants.Parameters.SIGNATURE)) { - safeURL = setURLParameter(safeURL, constants_js_1.URLConstants.Parameters.SIGNATURE, "*****"); + /** + * Append data for CRC64 checksum calculator + * @param body - content to be append + * @param length - length of the content + */ + append(body, length) { + const ptr = _StorageCRC64Calculator.nativeInstance._malloc(length); + _StorageCRC64Calculator.nativeInstance.HEAPU8.set(body, ptr); + this.nativeCrc64Hash.OnAppend(ptr, length); + _StorageCRC64Calculator.nativeInstance._free(ptr); } - return safeURL; + /** + * Complete CRC64 checksum calculating and get the final result. + * @param body - + * @param length - + * @returns + */ + final(body, length) { + const ptr = _StorageCRC64Calculator.nativeInstance._malloc(length); + _StorageCRC64Calculator.nativeInstance.HEAPU8.set(body, ptr); + const result = _StorageCRC64Calculator.nativeInstance._malloc(8); + this.nativeCrc64Hash.OnFinal(ptr, length, result); + _StorageCRC64Calculator.nativeInstance._free(ptr); + const resultArray = new Uint8Array(8); + resultArray.set(_StorageCRC64Calculator.nativeInstance.HEAPU8.subarray(result, result + 8)); + _StorageCRC64Calculator.nativeInstance._free(result); + return resultArray; + } + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/streamHelpers.js +var require_streamHelpers = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/streamHelpers.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var streamHelpers_exports = {}; + __export2(streamHelpers_exports, { + signalStreamEnd: () => signalStreamEnd + }); + module2.exports = __toCommonJS2(streamHelpers_exports); + function signalStreamEnd(pushData) { + pushData(null); } - function sanitizeHeaders(originalHeader) { - const headers = (0, core_rest_pipeline_1.createHttpHeaders)(); - for (const [name, value] of originalHeader) { - if (name.toLowerCase() === constants_js_1.HeaderConstants.AUTHORIZATION.toLowerCase()) { - headers.set(name, "*****"); - } else if (name.toLowerCase() === constants_js_1.HeaderConstants.X_MS_COPY_SOURCE) { - headers.set(name, sanitizeURL(value)); - } else { - headers.set(name, value); + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/StructuredMessageEncoding.js +var require_StructuredMessageEncoding = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/StructuredMessageEncoding.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StructuredMessageEncoding_exports = {}; + __export2(StructuredMessageEncoding_exports, { + FOOTER_LENGTH: () => FOOTER_LENGTH, + MAX_SEGMENT_CONTENT_LENGTH: () => MAX_SEGMENT_CONTENT_LENGTH, + MESSAGE_HEADER_LENGTH: () => MESSAGE_HEADER_LENGTH, + MESSAGE_VERSION: () => MESSAGE_VERSION, + SEGMENT_HEADER_LENGTH: () => SEGMENT_HEADER_LENGTH, + StructuredMessageEncoding: () => StructuredMessageEncoding + }); + module2.exports = __toCommonJS2(StructuredMessageEncoding_exports); + var import_StorageCRC64Calculator = require_StorageCRC64Calculator(); + var import_streamHelpers = require_streamHelpers(); + var MESSAGE_VERSION = 1; + var MESSAGE_HEADER_LENGTH = 13; + var SEGMENT_HEADER_LENGTH = 10; + var FOOTER_LENGTH = 8; + var MAX_SEGMENT_CONTENT_LENGTH = 4 * 1024 * 1024; + var StructuredMessageEncoding = class { + pushData; + contentLength; + messageLength; + constructor(pushData, contentLength) { + this.pushData = pushData; + this.contentLength = contentLength; + this.contentOffset = 0; + this.currentDataOffset = 0; + this.segmentsCount = Math.ceil(this.contentLength / MAX_SEGMENT_CONTENT_LENGTH); + this.messageLength = this.contentLength + MESSAGE_HEADER_LENGTH + (SEGMENT_HEADER_LENGTH + FOOTER_LENGTH) * this.segmentsCount + FOOTER_LENGTH; + this.messageHeaderBuffer = new Uint8Array(MESSAGE_HEADER_LENGTH); + this.segmentNumber = 0; + this.segmentContentLength = 0; + this.segmentContentOffset = 0; + this.state = 0; + this.segmentCrc64 = new import_StorageCRC64Calculator.StorageCRC64Calculator(); + this.messageCrc64 = new import_StorageCRC64Calculator.StorageCRC64Calculator(); + } + currentDataOffset; + contentOffset; + segmentsCount; + messageHeaderBuffer; + segmentNumber; + segmentContentLength; + segmentContentOffset; + segmentCrc64; + messageCrc64; + state; + sourceDataHandler = (data) => { + this.currentDataOffset = 0; + if (this.state === 0) { + this.handlingMessageHeader(); + } + while (this.segmentNumber < this.segmentsCount) { + this.segmentContentLength = Math.min( + MAX_SEGMENT_CONTENT_LENGTH, + this.contentLength - this.contentOffset + ); + if (this.state === 2) { + this.handlingSegmentHeader(); + } + if (this.state === 4) { + this.handlingSegmentContent(data); + } + if (this.state === 3) { + this.handlingSegmentFooter(); + this.contentOffset += this.segmentContentLength; + } + if (this.currentDataOffset === data.length) { + break; + } + } + if (this.state === 1) { + this.handlingMessageFooter(); } + }; + handlingMessageHeader() { + this.messageHeaderBuffer[0] = MESSAGE_VERSION; + this.fillInt64(this.messageHeaderBuffer, 1, this.messageLength); + this.fillInt16(this.messageHeaderBuffer, 9, 1); + this.fillInt16(this.messageHeaderBuffer, 11, this.segmentsCount); + this.pushData(this.messageHeaderBuffer); + this.state = 2; } - return headers; - } - function iEqual(str1, str2) { - return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); - } - function getAccountNameFromUrl(url2) { - const parsedUrl = new URL(url2); - let accountName; - try { - if (parsedUrl.hostname.split(".")[1] === "blob") { - accountName = parsedUrl.hostname.split(".")[0]; - } else if (isIpEndpointStyle(parsedUrl)) { - accountName = parsedUrl.pathname.split("/")[1]; + handlingSegmentHeader() { + const segmentHeaderBuffer = new Uint8Array(SEGMENT_HEADER_LENGTH); + this.fillInt16(segmentHeaderBuffer, 0, this.segmentNumber + 1); + this.fillInt64(segmentHeaderBuffer, 2, this.segmentContentLength); + this.segmentContentOffset = 0; + this.pushData(segmentHeaderBuffer); + this.state = 4; + } + handlingSegmentContent(data) { + const length = Math.min( + this.segmentContentLength - this.segmentContentOffset, + data.length - this.currentDataOffset + ); + if (length !== 0) { + const current_content = Uint8Array.prototype.slice.call( + data, + this.currentDataOffset, + this.currentDataOffset + length + ); + this.messageCrc64.append(current_content, length); + this.segmentCrc64.append(current_content, length); + this.pushData(current_content); + } + this.segmentContentOffset += length; + this.currentDataOffset += length; + if (this.segmentContentOffset === this.segmentContentLength) { + this.state = 3; + } + } + handlingSegmentFooter() { + const crc64Result = this.segmentCrc64.final(new Uint8Array([]), 0); + this.pushData(crc64Result); + this.segmentCrc64 = new import_StorageCRC64Calculator.StorageCRC64Calculator(); + ++this.segmentNumber; + if (this.segmentNumber === this.segmentsCount) { + this.state = 1; } else { - accountName = ""; + this.state = 2; } - return accountName; - } catch (error3) { - throw new Error("Unable to extract accountName with provided information."); } - } - function isIpEndpointStyle(parsedUrl) { - const host = parsedUrl.host; - return /^.*:.*:.*$|^(localhost|host.docker.internal)(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host) || Boolean(parsedUrl.port) && constants_js_1.PathStylePorts.includes(parsedUrl.port); - } - function toBlobTagsString(tags) { - if (tags === void 0) { - return void 0; + handlingMessageFooter() { + const crc64Result = this.messageCrc64.final(new Uint8Array([]), 0); + this.pushData(crc64Result); + (0, import_streamHelpers.signalStreamEnd)(this.pushData); + this.state = 5; } - const tagPairs = []; - for (const key in tags) { - if (Object.prototype.hasOwnProperty.call(tags, key)) { - const value = tags[key]; - tagPairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); + fillInt64(buffer, offset, input) { + if (buffer.length < offset + 8) { + throw new Error("Uint8Array length is not expected."); } + const view = new DataView(buffer.buffer, buffer.byteOffset + offset, 8); + view.setBigUint64(0, BigInt(input), true); } - return tagPairs.join("&"); - } - function toBlobTags(tags) { - if (tags === void 0) { - return void 0; - } - const res = { - blobTagSet: [] - }; - for (const key in tags) { - if (Object.prototype.hasOwnProperty.call(tags, key)) { - const value = tags[key]; - res.blobTagSet.push({ - key, - value - }); + fillInt16(buffer, offset, input) { + if (buffer.length < offset + 2) { + throw new Error("Uint8Array length is not expected."); } + const view = new DataView(buffer.buffer, buffer.byteOffset + offset, 2); + view.setUint16(0, input, true); } - return res; - } - function toTags(tags) { - if (tags === void 0) { - return void 0; + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/StructuredMessageEncodingStream.js +var require_StructuredMessageEncodingStream = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/StructuredMessageEncodingStream.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - const res = {}; - for (const blobTag of tags.blobTagSet) { - res[blobTag.key] = blobTag.value; + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StructuredMessageEncodingStream_exports = {}; + __export2(StructuredMessageEncodingStream_exports, { + structuredMessageEncoding: () => structuredMessageEncoding + }); + module2.exports = __toCommonJS2(StructuredMessageEncodingStream_exports); + var import_abort_controller = require_commonjs11(); + var import_node_stream5 = __toESM2(require("node:stream")); + var import_StructuredMessageEncoding = require_StructuredMessageEncoding(); + function isNodeReadableStream2(source) { + return source !== null && source instanceof import_node_stream5.default && typeof source._read === "function" && typeof source._readableState === "object" && typeof source.pipe === "function"; + } + async function structuredMessageEncoding(source, contentLength) { + if (source === null) { + return { + body: source, + encodedContentLength: contentLength + }; } - return res; - } - function toQuerySerialization(textConfiguration) { - if (textConfiguration === void 0) { - return void 0; + if (isNodeReadableStream2(source)) { + const encodingMessage = new StructuredMessageEncodingStream(source, contentLength, {}); + return { + body: encodingMessage, + encodedContentLength: encodingMessage.messageLength() + }; } - switch (textConfiguration.kind) { - case "csv": - return { - format: { - type: "delimited", - delimitedTextConfiguration: { - columnSeparator: textConfiguration.columnSeparator || ",", - fieldQuote: textConfiguration.fieldQuote || "", - recordSeparator: textConfiguration.recordSeparator, - escapeChar: textConfiguration.escapeCharacter || "", - headersPresent: textConfiguration.hasHeaders || false - } - } - }; - case "json": - return { - format: { - type: "json", - jsonTextConfiguration: { - recordSeparator: textConfiguration.recordSeparator - } - } - }; - case "arrow": - return { - format: { - type: "arrow", - arrowConfiguration: { - schema: textConfiguration.schema - } - } - }; - case "parquet": - return { - format: { - type: "parquet" - } - }; - default: - throw Error("Invalid BlobQueryTextConfiguration."); + if (typeof source === "function") { + const encodingMessage = new StructuredMessageEncodingStream( + source(), + contentLength, + {} + ); + return { + body: encodingMessage, + encodedContentLength: encodingMessage.messageLength() + }; } - } - function parseObjectReplicationRecord(objectReplicationRecord) { - if (!objectReplicationRecord) { - return void 0; + if (source instanceof Blob) { + const encoding = await BrowserStream(source, contentLength); + return { + body: encoding.content, + encodedContentLength: encoding.encodedContentLength + }; } - if ("policy-id" in objectReplicationRecord) { - return void 0; + if (typeof source === "string") { + const s = new import_node_stream5.Readable(); + s._read = () => { + }; + s.push(source); + s.push(null); + const stringContentLength = Buffer.byteLength(source); + const encodingMessage = await new StructuredMessageEncodingStream(s, stringContentLength, {}); + return { + body: encodingMessage, + encodedContentLength: encodingMessage.messageLength() + }; } - const orProperties = []; - for (const key in objectReplicationRecord) { - const ids = key.split("_"); - const policyPrefix = "or-"; - if (ids[0].startsWith(policyPrefix)) { - ids[0] = ids[0].substring(policyPrefix.length); - } - const rule = { - ruleId: ids[1], - replicationStatus: objectReplicationRecord[key] + if (source instanceof ArrayBuffer) { + const stream2 = import_node_stream5.Readable.from(Buffer.from(source)); + const encodingMessage = await new StructuredMessageEncodingStream(stream2, contentLength, {}); + return { + body: encodingMessage, + encodedContentLength: encodingMessage.messageLength() }; - const policyIndex = orProperties.findIndex((policy) => policy.policyId === ids[0]); - if (policyIndex > -1) { - orProperties[policyIndex].rules.push(rule); - } else { - orProperties.push({ - policyId: ids[0], - rules: [rule] - }); - } } - return orProperties; - } - function attachCredential(thing, credential) { - thing.credential = credential; - return thing; - } - function httpAuthorizationToString(httpAuthorization) { - return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : void 0; - } - function BlobNameToString(name) { - if (name.encoded) { - return decodeURIComponent(name.content); - } else { - return name.content; + if (source instanceof Buffer) { + const stream2 = import_node_stream5.Readable.from(source); + const encodingMessage = await new StructuredMessageEncodingStream(stream2, contentLength, {}); + return { + body: encodingMessage, + encodedContentLength: encodingMessage.messageLength() + }; } + if (ArrayBuffer.isView(source)) { + const stream2 = import_node_stream5.Readable.from(Buffer.from(source.buffer, source.byteOffset, source.byteLength)); + const encodingMessage = await new StructuredMessageEncodingStream(stream2, contentLength, {}); + return { + body: encodingMessage, + encodedContentLength: encodingMessage.messageLength() + }; + } + throw new Error("The specified request body type is not supported for CRC64 checksum"); } - function ConvertInternalResponseOfListBlobFlat(internalResponse) { - return { - ...internalResponse, - segment: { - blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { - const blobItem = { - ...blobItemInteral, - name: BlobNameToString(blobItemInteral.name) - }; - return blobItem; - }) + async function pump3(reader, controller, encodingStream) { + const { done, value } = await reader.read(); + if (done) { + controller.close(); + return; + } + encodingStream.sourceDataHandler(Buffer.from(value)); + } + async function BrowserStream(source, contentLength) { + const sourceStream = source instanceof Blob ? source.stream() : source; + const reader = sourceStream.getReader(); + let encodingStream = void 0; + const stream2 = new ReadableStream({ + start(controller) { + encodingStream = new import_StructuredMessageEncoding.StructuredMessageEncoding((data) => { + controller.enqueue(data); + }, contentLength); + }, + pull(controller) { + pump3(reader, controller, encodingStream).then(() => { + return; + }).catch(function(error3) { + controller.error(error3); + }); } - }; - } - function ConvertInternalResponseOfListBlobHierarchy(internalResponse) { + }); + const response = new Response(stream2); return { - ...internalResponse, - segment: { - blobPrefixes: internalResponse.segment.blobPrefixes?.map((blobPrefixInternal) => { - const blobPrefix = { - ...blobPrefixInternal, - name: BlobNameToString(blobPrefixInternal.name) - }; - return blobPrefix; - }), - blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { - const blobItem = { - ...blobItemInteral, - name: BlobNameToString(blobItemInteral.name) - }; - return blobItem; - }) - } + content: await response.blob(), + encodedContentLength: encodingStream.messageLength }; } - function* ExtractPageRangeInfoItems(getPageRangesSegment) { - let pageRange = []; - let clearRange = []; - if (getPageRangesSegment.pageRange) - pageRange = getPageRangesSegment.pageRange; - if (getPageRangesSegment.clearRange) - clearRange = getPageRangesSegment.clearRange; - let pageRangeIndex = 0; - let clearRangeIndex = 0; - while (pageRangeIndex < pageRange.length && clearRangeIndex < clearRange.length) { - if (pageRange[pageRangeIndex].start < clearRange[clearRangeIndex].start) { - yield { - start: pageRange[pageRangeIndex].start, - end: pageRange[pageRangeIndex].end, - isClear: false - }; - ++pageRangeIndex; - } else { - yield { - start: clearRange[clearRangeIndex].start, - end: clearRange[clearRangeIndex].end, - isClear: true - }; - ++clearRangeIndex; - } + var StructuredMessageEncodingStream = class extends import_node_stream5.Readable { + source; + encodingMethods; + constructor(source, contentLength, options) { + super({ highWaterMark: options.highWaterMark }); + this.source = source; + this.encodingMethods = new import_StructuredMessageEncoding.StructuredMessageEncoding((dataToHandle) => { + if (!this.push(dataToHandle)) { + source.pause(); + } + }, contentLength); + this.setSourceEventHandlers(); } - for (; pageRangeIndex < pageRange.length; ++pageRangeIndex) { - yield { - start: pageRange[pageRangeIndex].start, - end: pageRange[pageRangeIndex].end, - isClear: false - }; + messageLength() { + return this.encodingMethods.messageLength; } - for (; clearRangeIndex < clearRange.length; ++clearRangeIndex) { - yield { - start: clearRange[clearRangeIndex].start, - end: clearRange[clearRangeIndex].end, - isClear: true - }; + setSourceEventHandlers() { + this.source.on("data", this.sourceDataHandler); + this.source.on("end", this.sourceErrorOrEndHandler); + this.source.on("error", this.sourceErrorOrEndHandler); + this.source.on("aborted", this.sourceAbortedHandler); } - } - function EscapePath(blobName) { - const split = blobName.split("/"); - for (let i = 0; i < split.length; i++) { - split[i] = encodeURIComponent(split[i]); + removeSourceEventHandlers() { + this.source.removeListener("data", this.sourceDataHandler); + this.source.removeListener("end", this.sourceErrorOrEndHandler); + this.source.removeListener("error", this.sourceErrorOrEndHandler); + this.source.removeListener("aborted", this.sourceAbortedHandler); } - return split.join("/"); - } - function assertResponse(response) { - if (`_response` in response) { - return response; + sourceDataHandler = (data) => { + this.encodingMethods.sourceDataHandler(data); + }; + sourceAbortedHandler = () => { + const abortError = new import_abort_controller.AbortError("The operation was aborted."); + this.destroy(abortError); + }; + sourceErrorOrEndHandler = (err) => { + if (err && err.name === "AbortError") { + this.destroy(err); + return; + } + this.removeSourceEventHandlers(); + }; + _read() { + this.source.resume(); } - throw new TypeError(`Unexpected response object ${response}`); - } - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/policies/StorageRetryPolicyType.js -var require_StorageRetryPolicyType = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/policies/StorageRetryPolicyType.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageRetryPolicyType = void 0; - var StorageRetryPolicyType; - (function(StorageRetryPolicyType2) { - StorageRetryPolicyType2[StorageRetryPolicyType2["EXPONENTIAL"] = 0] = "EXPONENTIAL"; - StorageRetryPolicyType2[StorageRetryPolicyType2["FIXED"] = 1] = "FIXED"; - })(StorageRetryPolicyType || (exports2.StorageRetryPolicyType = StorageRetryPolicyType = {})); + _destroy(error3, callback) { + this.removeSourceEventHandlers(); + this.source.destroy(); + callback(error3 === null ? void 0 : error3); + } + }; } }); -// node_modules/@azure/storage-blob/dist/commonjs/policies/StorageRetryPolicy.js -var require_StorageRetryPolicy = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/policies/StorageRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageRetryPolicy = void 0; - exports2.NewRetryPolicyFactory = NewRetryPolicyFactory; - var abort_controller_1 = require_commonjs11(); - var RequestPolicy_js_1 = require_RequestPolicy(); - var constants_js_1 = require_constants10(); - var utils_common_js_1 = require_utils_common(); - var log_js_1 = require_log5(); - var StorageRetryPolicyType_js_1 = require_StorageRetryPolicyType(); - function NewRetryPolicyFactory(retryOptions) { - return { - create: (nextPolicy, options) => { - return new StorageRetryPolicy(nextPolicy, options, retryOptions); - } - }; - } - var DEFAULT_RETRY_OPTIONS = { - maxRetryDelayInMs: 120 * 1e3, - maxTries: 4, - retryDelayInMs: 4 * 1e3, - retryPolicyType: StorageRetryPolicyType_js_1.StorageRetryPolicyType.EXPONENTIAL, - secondaryHost: "", - tryTimeoutInMs: void 0 - // Use server side default timeout strategy +// node_modules/@azure/storage-common/dist/commonjs/StructuredMessageDecoding.js +var require_StructuredMessageDecoding = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/StructuredMessageDecoding.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); }; - var RETRY_ABORT_ERROR = new abort_controller_1.AbortError("The operation was aborted."); - var StorageRetryPolicy = class extends RequestPolicy_js_1.BaseRequestPolicy { - /** - * RetryOptions. - */ - retryOptions; - /** - * Creates an instance of RetryPolicy. - * - * @param nextPolicy - - * @param options - - * @param retryOptions - - */ - constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS) { - super(nextPolicy, options); - this.retryOptions = { - retryPolicyType: retryOptions.retryPolicyType ? retryOptions.retryPolicyType : DEFAULT_RETRY_OPTIONS.retryPolicyType, - maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1 ? Math.floor(retryOptions.maxTries) : DEFAULT_RETRY_OPTIONS.maxTries, - tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0 ? retryOptions.tryTimeoutInMs : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs, - retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0 ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs) : DEFAULT_RETRY_OPTIONS.retryDelayInMs, - maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0 ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs, - secondaryHost: retryOptions.secondaryHost ? retryOptions.secondaryHost : DEFAULT_RETRY_OPTIONS.secondaryHost - }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - /** - * Sends request. - * - * @param request - - */ - async sendRequest(request3) { - return this.attemptSendRequest(request3, false, 1); + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StructuredMessageDecoding_exports = {}; + __export2(StructuredMessageDecoding_exports, { + StructuredMessageDecoding: () => StructuredMessageDecoding + }); + module2.exports = __toCommonJS2(StructuredMessageDecoding_exports); + var import_StorageCRC64Calculator = require_StorageCRC64Calculator(); + var MESSAGE_VERSION = 1; + var MESSAGE_HEADER_LENGTH = 13; + var SEGMENT_HEADER_LENGTH = 10; + var FOOTER_LENGTH = 8; + var StructuredMessageDecoding = class { + pushData; + segmentsCount; + // private currentState: SMRegion; + currentOffset; + currentDataOffset; + messageHeaderBuffer; + messageHeaderOffset; + segmentNumber; + segmentHeaderOffset; + segmentHeaderBuffer; + segmentContentOffset; + segmentContentLength; + segmentFooterOffset; + segmentFooterBuffer; + messageFooterOffset; + messageFooterBuffer; + segmentCrc64; + messageCrc64; + state; + constructor(pushData) { + this.pushData = pushData; + this.currentOffset = 0; + this.segmentsCount = 0; + this.messageHeaderOffset = 0; + this.messageHeaderBuffer = new Uint8Array(MESSAGE_HEADER_LENGTH); + this.currentDataOffset = 0; + this.segmentNumber = 0; + this.segmentHeaderOffset = 0; + this.segmentHeaderBuffer = new Uint8Array(SEGMENT_HEADER_LENGTH); + this.segmentContentOffset = 0; + this.segmentContentLength = 0; + this.state = 0; + this.segmentFooterOffset = 0; + this.segmentFooterBuffer = new Uint8Array(FOOTER_LENGTH); + this.messageFooterOffset = 0; + this.messageFooterBuffer = new Uint8Array(FOOTER_LENGTH); + this.segmentCrc64 = new import_StorageCRC64Calculator.StorageCRC64Calculator(); + this.messageCrc64 = new import_StorageCRC64Calculator.StorageCRC64Calculator(); } - /** - * Decide and perform next retry. Won't mutate request parameter. - * - * @param request - - * @param secondaryHas404 - If attempt was against the secondary & it returned a StatusNotFound (404), then - * the resource was not found. This may be due to replication delay. So, in this - * case, we'll never try the secondary again for this operation. - * @param attempt - How many retries has been attempted to performed, starting from 1, which includes - * the attempt will be performed by this method call. - */ - async attemptSendRequest(request3, secondaryHas404, attempt) { - const newRequest = request3.clone(); - const isPrimaryRetry = secondaryHas404 || !this.retryOptions.secondaryHost || !(request3.method === "GET" || request3.method === "HEAD" || request3.method === "OPTIONS") || attempt % 2 === 1; - if (!isPrimaryRetry) { - newRequest.url = (0, utils_common_js_1.setURLHost)(newRequest.url, this.retryOptions.secondaryHost); - } - if (this.retryOptions.tryTimeoutInMs) { - newRequest.url = (0, utils_common_js_1.setURLParameter)(newRequest.url, constants_js_1.URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1e3).toString()); + sourceDataHandler = (data) => { + this.currentDataOffset = 0; + if (this.state === 0) { + this.parseMessageHeader(data); } - let response; - try { - log_js_1.logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); - response = await this._nextPolicy.sendRequest(newRequest); - if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { - return response; + while (this.segmentNumber < this.segmentsCount && this.currentDataOffset < data.length) { + if (this.state === 2) { + this.parseSegmentHeader(data); } - secondaryHas404 = secondaryHas404 || !isPrimaryRetry && response.status === 404; - } catch (err) { - log_js_1.logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`); - if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) { - throw err; + if (this.state === 4) { + this.parseSegmentContent(data); + } + if (this.state === 3) { + this.parseSegmentFooter(data); } } - await this.delay(isPrimaryRetry, attempt, request3.abortSignal); - return this.attemptSendRequest(request3, secondaryHas404, ++attempt); - } - /** - * Decide whether to retry according to last HTTP response and retry counters. - * - * @param isPrimaryRetry - - * @param attempt - - * @param response - - * @param err - - */ - shouldRetry(isPrimaryRetry, attempt, response, err) { - if (attempt >= this.retryOptions.maxTries) { - log_js_1.logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions.maxTries}, no further try.`); - return false; + if (this.state === 1) { + this.parseMessageFooter(data); } - const retriableErrors = [ - "ETIMEDOUT", - "ESOCKETTIMEDOUT", - "ECONNREFUSED", - "ECONNRESET", - "ENOENT", - "ENOTFOUND", - "TIMEOUT", - "EPIPE", - "REQUEST_SEND_ERROR" - // For default xhr based http client provided in ms-rest-js - ]; - if (err) { - for (const retriableError of retriableErrors) { - if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || err.code && err.code.toString().toUpperCase() === retriableError) { - log_js_1.logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); - return true; - } - } + }; + parseMessageHeader(data) { + const length = Math.min( + MESSAGE_HEADER_LENGTH - this.messageHeaderOffset, + data.length - this.currentDataOffset + ); + this.messageHeaderBuffer.set( + Uint8Array.prototype.slice.call( + data, + this.currentDataOffset, + this.currentDataOffset + length + ), + this.messageHeaderOffset + ); + this.currentDataOffset += length; + this.messageHeaderOffset += length; + this.currentOffset += length; + if (this.messageHeaderOffset === MESSAGE_HEADER_LENGTH) { + const currentVersion = this.messageHeaderBuffer[0]; + if (currentVersion !== MESSAGE_VERSION) { + throw new Error("Unexpected message version"); + } + this.segmentsCount = this.toInt16( + Uint8Array.prototype.slice.call(this.messageHeaderBuffer, 11, 13) + ); + this.state = 2; } - if (response || err) { - const statusCode = response ? response.status : err ? err.statusCode : 0; - if (!isPrimaryRetry && statusCode === 404) { - log_js_1.logger.info(`RetryPolicy: Secondary access with 404, will retry.`); - return true; + } + parseSegmentHeader(data) { + const length = Math.min( + SEGMENT_HEADER_LENGTH - this.segmentHeaderOffset, + data.length - this.currentDataOffset + ); + this.segmentHeaderBuffer.set( + Uint8Array.prototype.slice.call( + data, + this.currentDataOffset, + this.currentDataOffset + length + ), + this.segmentHeaderOffset + ); + this.currentDataOffset += length; + this.segmentHeaderOffset += length; + this.currentOffset += length; + if (this.segmentHeaderOffset === SEGMENT_HEADER_LENGTH) { + const currentSegmentNumber = this.toInt16( + Uint8Array.prototype.slice.call(this.segmentHeaderBuffer, 0, 2) + ); + if (currentSegmentNumber !== this.segmentNumber + 1) { + throw new Error("Segment number is unexpected."); } - if (statusCode === 503 || statusCode === 500) { - log_js_1.logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); - return true; + this.segmentContentLength = this.toInt64(this.segmentHeaderBuffer, 2); + this.segmentContentOffset = 0; + this.state = 4; + } + } + parseSegmentContent(data) { + const length = Math.min( + this.segmentContentLength - this.segmentContentOffset, + data.length - this.currentDataOffset + ); + const dataToHandle = Uint8Array.prototype.slice.call( + data, + this.currentDataOffset, + this.currentDataOffset + length + ); + this.segmentCrc64.append(dataToHandle, length); + this.messageCrc64.append(dataToHandle, length); + this.pushData(dataToHandle); + this.currentDataOffset += length; + this.segmentContentOffset += length; + this.currentOffset += length; + if (this.segmentContentOffset === this.segmentContentLength) { + this.state = 3; + } + } + parseSegmentFooter(data) { + const length = Math.min( + FOOTER_LENGTH - this.segmentFooterOffset, + data.length - this.currentDataOffset + ); + this.segmentFooterBuffer.set( + Uint8Array.prototype.slice.call( + data, + this.currentDataOffset, + this.currentDataOffset + length + ), + this.segmentFooterOffset + ); + this.currentDataOffset += length; + this.segmentFooterOffset += length; + this.currentOffset += length; + if (this.segmentFooterOffset === FOOTER_LENGTH) { + const crc64Result = this.segmentCrc64.final(new Uint8Array([]), 0); + if (!this.checkCrc64CheckSum(crc64Result, this.segmentFooterBuffer)) { + throw new Error(`Segment check sum mismatch, segmentNumber: ${this.segmentNumber}`); + } + ++this.segmentNumber; + if (this.segmentNumber === this.segmentsCount) { + this.state = 1; + } else { + this.segmentHeaderOffset = 0; + this.segmentFooterOffset = 0; + this.segmentCrc64 = new import_StorageCRC64Calculator.StorageCRC64Calculator(); + this.state = 2; } } - if (response) { - if (response?.status >= 400) { - const copySourceError = response.headers.get(constants_js_1.HeaderConstants.X_MS_CopySourceErrorCode); - if (copySourceError !== void 0) { - switch (copySourceError) { - case "InternalError": - case "OperationTimedOut": - case "ServerBusy": - return true; - } - } + } + parseMessageFooter(data) { + const length = Math.min( + FOOTER_LENGTH - this.messageFooterOffset, + data.length - this.currentDataOffset + ); + this.messageFooterBuffer.set( + Uint8Array.prototype.slice.call( + data, + this.currentDataOffset, + this.currentDataOffset + length + ), + this.messageFooterOffset + ); + this.currentDataOffset += length; + this.messageFooterOffset += length; + this.currentOffset += length; + if (this.messageFooterOffset === FOOTER_LENGTH) { + const crc64Result = this.messageCrc64.final(new Uint8Array([]), 0); + if (!this.checkCrc64CheckSum(crc64Result, this.messageFooterBuffer)) { + throw new Error("Check sum mismatch"); } + this.pushData(null); } - if (err?.code === "PARSE_ERROR" && err?.message.startsWith(`Error "Error: Unclosed root tag`)) { - log_js_1.logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); - return true; + } + toInt64(input, offset) { + if (input.length < offset + 8) { + throw new Error("CRC64 buffer error, something wrong with crc64 calculator"); } - return false; + const view = new DataView(input.buffer, input.byteOffset + offset, 8); + return Number(view.getBigUint64(0, true)); } - /** - * Delay a calculated time between retries. - * - * @param isPrimaryRetry - - * @param attempt - - * @param abortSignal - - */ - async delay(isPrimaryRetry, attempt, abortSignal) { - let delayTimeInMs = 0; - if (isPrimaryRetry) { - switch (this.retryOptions.retryPolicyType) { - case StorageRetryPolicyType_js_1.StorageRetryPolicyType.EXPONENTIAL: - delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); - break; - case StorageRetryPolicyType_js_1.StorageRetryPolicyType.FIXED: - delayTimeInMs = this.retryOptions.retryDelayInMs; - break; + toInt16(input) { + if (input.length !== 2) { + throw new Error("CRC64 buffer error, something wrong with crc64 calculator"); + } + return input[0] + input[1] * 256; + } + checkCrc64CheckSum(first, second) { + if (first.length !== 8 || second.length !== 8) { + throw new Error("CRC64 buffer error, something wrong with crc64 calculator"); + } + for (let index2 = 0; index2 < 8; ++index2) { + if (first[index2] !== second[index2]) { + return false; } - } else { - delayTimeInMs = Math.random() * 1e3; } - log_js_1.logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); - return (0, utils_common_js_1.delay)(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR); + return true; } }; - exports2.StorageRetryPolicy = StorageRetryPolicy; } }); -// node_modules/@azure/storage-blob/dist/commonjs/StorageRetryPolicyFactory.js -var require_StorageRetryPolicyFactory = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/StorageRetryPolicyFactory.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageRetryPolicyFactory = exports2.StorageRetryPolicy = exports2.StorageRetryPolicyType = void 0; - var StorageRetryPolicy_js_1 = require_StorageRetryPolicy(); - Object.defineProperty(exports2, "StorageRetryPolicy", { enumerable: true, get: function() { - return StorageRetryPolicy_js_1.StorageRetryPolicy; - } }); - var StorageRetryPolicyType_js_1 = require_StorageRetryPolicyType(); - Object.defineProperty(exports2, "StorageRetryPolicyType", { enumerable: true, get: function() { - return StorageRetryPolicyType_js_1.StorageRetryPolicyType; - } }); - var StorageRetryPolicyFactory = class { - retryOptions; - /** - * Creates an instance of StorageRetryPolicyFactory. - * @param retryOptions - - */ - constructor(retryOptions) { - this.retryOptions = retryOptions; - } - /** - * Creates a StorageRetryPolicy object. - * - * @param nextPolicy - - * @param options - - */ - create(nextPolicy, options) { - return new StorageRetryPolicy_js_1.StorageRetryPolicy(nextPolicy, options, this.retryOptions); - } +// node_modules/@azure/storage-common/dist/commonjs/StructuredMessageDecodingStream.js +var require_StructuredMessageDecodingStream = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/StructuredMessageDecodingStream.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); }; - exports2.StorageRetryPolicyFactory = StorageRetryPolicyFactory; - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/policies/CredentialPolicy.js -var require_CredentialPolicy = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/policies/CredentialPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CredentialPolicy = void 0; - var RequestPolicy_js_1 = require_RequestPolicy(); - var CredentialPolicy = class extends RequestPolicy_js_1.BaseRequestPolicy { - /** - * Sends out request. - * - * @param request - - */ - sendRequest(request3) { - return this._nextPolicy.sendRequest(this.signRequest(request3)); - } - /** - * Child classes must implement this method with request signing. This method - * will be executed in {@link sendRequest}. - * - * @param request - - */ - signRequest(request3) { - return request3; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.CredentialPolicy = CredentialPolicy; - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/utils/SharedKeyComparator.js -var require_SharedKeyComparator = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/utils/SharedKeyComparator.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.compareHeader = compareHeader; - var table_lv0 = new Uint32Array([ - 0, - 0, - 0, - 0, + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StructuredMessageDecodingStream_exports = {}; + __export2(StructuredMessageDecodingStream_exports, { + structuredMessageDecodingBrowser: () => structuredMessageDecodingBrowser, + structuredMessageDecodingStream: () => structuredMessageDecodingStream + }); + module2.exports = __toCommonJS2(StructuredMessageDecodingStream_exports); + var import_abort_controller = require_commonjs11(); + var import_node_stream5 = require("node:stream"); + var import_StructuredMessageDecoding = require_StructuredMessageDecoding(); + async function structuredMessageDecodingBrowser(source) { + source; + throw new Error("structuredMessageDecodingBrowser is only for Browser"); + } + function structuredMessageDecodingStream(source, options) { + return new StructuredMessageDecodingStream(source, options); + } + var StructuredMessageDecodingStream = class extends import_node_stream5.Readable { + source; + decodingMethods; + constructor(source, options) { + super({ highWaterMark: options.highWaterMark }); + this.source = source; + this.decodingMethods = new import_StructuredMessageDecoding.StructuredMessageDecoding((dataToHandle) => { + if (!this.push(dataToHandle)) { + source.pause(); + } + }); + this.setSourceEventHandlers(); + } + _read() { + this.source.resume(); + } + setSourceEventHandlers() { + this.source.on("data", this.sourceDataHandler); + this.source.on("end", this.sourceErrorOrEndHandler); + this.source.on("error", this.sourceErrorOrEndHandler); + this.source.on("aborted", this.sourceAbortedHandler); + } + removeSourceEventHandlers() { + this.source.removeListener("data", this.sourceDataHandler); + this.source.removeListener("end", this.sourceErrorOrEndHandler); + this.source.removeListener("error", this.sourceErrorOrEndHandler); + this.source.removeListener("aborted", this.sourceAbortedHandler); + } + sourceDataHandler = (data) => { + try { + this.decodingMethods.sourceDataHandler(data); + } catch (err) { + this.destroy(err); + } + }; + sourceAbortedHandler = () => { + const abortError = new import_abort_controller.AbortError("The operation was aborted."); + this.destroy(abortError); + }; + sourceErrorOrEndHandler = (err) => { + if (err) { + this.destroy(err); + return; + } + this.removeSourceEventHandlers(); + }; + _destroy(error3, callback) { + this.removeSourceEventHandlers(); + this.source.destroy(); + callback(error3 === null ? void 0 : error3); + } + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/cache.js +var require_cache4 = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/cache.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var cache_exports = {}; + __export2(cache_exports, { + getCachedDefaultHttpClient: () => getCachedDefaultHttpClient2 + }); + module2.exports = __toCommonJS2(cache_exports); + var import_core_rest_pipeline = require_commonjs6(); + var _defaultHttpClient; + function getCachedDefaultHttpClient2() { + if (!_defaultHttpClient) { + _defaultHttpClient = (0, import_core_rest_pipeline.createDefaultHttpClient)(); + } + return _defaultHttpClient; + } + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/StorageResponseFormat.js +var require_StorageResponseFormat = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/StorageResponseFormat.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageResponseFormat_exports = {}; + __export2(StorageResponseFormat_exports, { + StorageResponseFormat: () => StorageResponseFormat2 + }); + module2.exports = __toCommonJS2(StorageResponseFormat_exports); + var StorageResponseFormat2 = { + /** + * Default. Currently maps to {@link StorageResponseFormat.Xml}, but may be updated in future releases. + */ + Auto: "Auto", + /** + * Use XML to return list results. + */ + Xml: "Xml", + /** + * Use Apache Arrow to return list results. + */ + Arrow: "Arrow" + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/policies/RequestPolicy.js +var require_RequestPolicy = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/policies/RequestPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var RequestPolicy_exports = {}; + __export2(RequestPolicy_exports, { + BaseRequestPolicy: () => BaseRequestPolicy2 + }); + module2.exports = __toCommonJS2(RequestPolicy_exports); + var BaseRequestPolicy2 = class { + /** + * The main method to implement that manipulates a request/response. + */ + constructor(_nextPolicy, _options) { + this._nextPolicy = _nextPolicy; + this._options = _options; + } + _nextPolicy; + _options; + /** + * Get whether or not a log with the provided log level should be logged. + * @param logLevel - The log level of the log that will be logged. + * @returns Whether or not a log with the provided log level should be logged. + */ + shouldLog(logLevel) { + return this._options.shouldLog(logLevel); + } + /** + * Attempt to log the provided message to the provided logger. If no logger was provided or if + * the log level does not meat the logger's threshold, then nothing will be logged. + * @param logLevel - The log level of this log. + * @param message - The message of this log. + */ + log(logLevel, message) { + this._options.log(logLevel, message); + } + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/policies/StorageBrowserPolicy.js +var require_StorageBrowserPolicy = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/policies/StorageBrowserPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageBrowserPolicy_exports = {}; + __export2(StorageBrowserPolicy_exports, { + StorageBrowserPolicy: () => StorageBrowserPolicy2 + }); + module2.exports = __toCommonJS2(StorageBrowserPolicy_exports); + var import_RequestPolicy = require_RequestPolicy(); + var StorageBrowserPolicy2 = class extends import_RequestPolicy.BaseRequestPolicy { + /** + * Creates an instance of StorageBrowserPolicy. + * @param nextPolicy - + * @param options - + */ + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); + } + /** + * Sends out request. + * + * @param request - + */ + async sendRequest(request3) { + return this._nextPolicy.sendRequest(request3); + } + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/StorageBrowserPolicyFactory.js +var require_StorageBrowserPolicyFactory = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/StorageBrowserPolicyFactory.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageBrowserPolicyFactory_exports = {}; + __export2(StorageBrowserPolicyFactory_exports, { + StorageBrowserPolicy: () => import_StorageBrowserPolicy.StorageBrowserPolicy, + StorageBrowserPolicyFactory: () => StorageBrowserPolicyFactory2 + }); + module2.exports = __toCommonJS2(StorageBrowserPolicyFactory_exports); + var import_StorageBrowserPolicy = require_StorageBrowserPolicy(); + var StorageBrowserPolicyFactory2 = class { + /** + * Creates a StorageBrowserPolicyFactory object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new import_StorageBrowserPolicy.StorageBrowserPolicy(nextPolicy, options); + } + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/policies/CredentialPolicy.js +var require_CredentialPolicy = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/policies/CredentialPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var CredentialPolicy_exports = {}; + __export2(CredentialPolicy_exports, { + CredentialPolicy: () => CredentialPolicy2 + }); + module2.exports = __toCommonJS2(CredentialPolicy_exports); + var import_RequestPolicy = require_RequestPolicy(); + var CredentialPolicy2 = class extends import_RequestPolicy.BaseRequestPolicy { + /** + * Sends out request. + * + * @param request - + */ + sendRequest(request3) { + return this._nextPolicy.sendRequest(this.signRequest(request3)); + } + /** + * Child classes must implement this method with request signing. This method + * will be executed in {@link sendRequest}. + * + * @param request - + */ + signRequest(request3) { + return request3; + } + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/policies/AnonymousCredentialPolicy.js +var require_AnonymousCredentialPolicy = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/policies/AnonymousCredentialPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var AnonymousCredentialPolicy_exports = {}; + __export2(AnonymousCredentialPolicy_exports, { + AnonymousCredentialPolicy: () => AnonymousCredentialPolicy2 + }); + module2.exports = __toCommonJS2(AnonymousCredentialPolicy_exports); + var import_CredentialPolicy = require_CredentialPolicy(); + var AnonymousCredentialPolicy2 = class extends import_CredentialPolicy.CredentialPolicy { + /** + * Creates an instance of AnonymousCredentialPolicy. + * @param nextPolicy - + * @param options - + */ + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); + } + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/credentials/Credential.js +var require_Credential = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/credentials/Credential.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var Credential_exports = {}; + __export2(Credential_exports, { + Credential: () => Credential3 + }); + module2.exports = __toCommonJS2(Credential_exports); + var Credential3 = class { + /** + * Creates a RequestPolicy object. + * + * @param _nextPolicy - + * @param _options - + */ + create(_nextPolicy, _options) { + throw new Error("Method should be implemented in children classes."); + } + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/credentials/AnonymousCredential.js +var require_AnonymousCredential = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/credentials/AnonymousCredential.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var AnonymousCredential_exports = {}; + __export2(AnonymousCredential_exports, { + AnonymousCredential: () => AnonymousCredential2 + }); + module2.exports = __toCommonJS2(AnonymousCredential_exports); + var import_AnonymousCredentialPolicy = require_AnonymousCredentialPolicy(); + var import_Credential = require_Credential(); + var AnonymousCredential2 = class extends import_Credential.Credential { + /** + * Creates an {@link AnonymousCredentialPolicy} object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new import_AnonymousCredentialPolicy.AnonymousCredentialPolicy(nextPolicy, options); + } + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/utils/constants.js +var require_constants10 = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/utils/constants.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var constants_exports = {}; + __export2(constants_exports, { + DevelopmentConnectionString: () => DevelopmentConnectionString, + HeaderConstants: () => HeaderConstants, + PathStylePorts: () => PathStylePorts, + SDK_VERSION: () => SDK_VERSION, + URLConstants: () => URLConstants + }); + module2.exports = __toCommonJS2(constants_exports); + var SDK_VERSION = "12.5.0"; + var URLConstants = { + Parameters: { + FORCE_BROWSER_NO_CACHE: "_", + SIGNATURE: "sig", + SNAPSHOT: "snapshot", + VERSIONID: "versionid", + TIMEOUT: "timeout" + } + }; + var HeaderConstants = { + AUTHORIZATION: "Authorization", + AUTHORIZATION_SCHEME: "Bearer", + CONTENT_ENCODING: "Content-Encoding", + CONTENT_ID: "Content-ID", + CONTENT_LANGUAGE: "Content-Language", + CONTENT_LENGTH: "Content-Length", + CONTENT_MD5: "Content-Md5", + CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding", + CONTENT_TYPE: "Content-Type", + COOKIE: "Cookie", + DATE: "date", + IF_MATCH: "if-match", + IF_MODIFIED_SINCE: "if-modified-since", + IF_NONE_MATCH: "if-none-match", + IF_UNMODIFIED_SINCE: "if-unmodified-since", + PREFIX_FOR_STORAGE: "x-ms-", + RANGE: "Range", + USER_AGENT: "User-Agent", + X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id", + X_MS_COPY_SOURCE: "x-ms-copy-source", + X_MS_DATE: "x-ms-date", + X_MS_ERROR_CODE: "x-ms-error-code", + X_MS_VERSION: "x-ms-version", + X_MS_CopySourceErrorCode: "x-ms-copy-source-error-code" + }; + var DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`; + var PathStylePorts = [ + "10000", + "10001", + "10002", + "10003", + "10004", + "10100", + "10101", + "10102", + "10103", + "10104", + "11000", + "11001", + "11002", + "11003", + "11004", + "11100", + "11101", + "11102", + "11103", + "11104" + ]; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/utils/utils.common.js +var require_utils_common = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/utils/utils.common.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var utils_common_exports = {}; + __export2(utils_common_exports, { + EscapePath: () => EscapePath, + appendToURLPath: () => appendToURLPath, + appendToURLQuery: () => appendToURLQuery, + assertResponse: () => assertResponse, + attachCredential: () => attachCredential, + delay: () => delay2, + escapeURLPath: () => escapeURLPath, + extractConnectionStringParts: () => extractConnectionStringParts, + generateBlockID: () => generateBlockID, + getAccountNameFromUrl: () => getAccountNameFromUrl, + getURLParameter: () => getURLParameter, + getURLPath: () => getURLPath, + getURLPathAndQuery: () => getURLPathAndQuery, + getURLQueries: () => getURLQueries, + getURLScheme: () => getURLScheme, + getValueInConnString: () => getValueInConnString, + httpAuthorizationToString: () => httpAuthorizationToString, + iEqual: () => iEqual, + isIpEndpointStyle: () => isIpEndpointStyle, + padStart: () => padStart2, + sanitizeHeaders: () => sanitizeHeaders, + sanitizeURL: () => sanitizeURL, + setURLHost: () => setURLHost, + setURLParameter: () => setURLParameter, + truncatedISO8061Date: () => truncatedISO8061Date + }); + module2.exports = __toCommonJS2(utils_common_exports); + var import_core_rest_pipeline = require_commonjs6(); + var import_core_util = require_commonjs4(); + var import_constants5 = require_constants10(); + function escapeURLPath(url2) { + const urlParsed = new URL(url2); + let path30 = urlParsed.pathname; + path30 = path30 || "/"; + path30 = escape3(path30); + urlParsed.pathname = path30; + return urlParsed.toString(); + } + function getProxyUriFromDevConnString(connectionString) { + let proxyUri = ""; + if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { + const matchCredentials = connectionString.split(";"); + for (const element of matchCredentials) { + if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { + proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; + } + } + } + return proxyUri; + } + function getValueInConnString(connectionString, argument) { + const elements = connectionString.split(";"); + for (const element of elements) { + if (element.trim().startsWith(argument)) { + return element.trim().match(argument + "=(.*)")[1]; + } + } + return ""; + } + function extractConnectionStringParts(connectionString) { + let proxyUri = ""; + if (connectionString.startsWith("UseDevelopmentStorage=true")) { + proxyUri = getProxyUriFromDevConnString(connectionString); + connectionString = import_constants5.DevelopmentConnectionString; + } + let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); + blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; + if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && connectionString.search("AccountKey=") !== -1) { + let defaultEndpointsProtocol = ""; + let accountName = ""; + let accountKey = (0, import_core_util.stringToUint8Array)("accountKey", "base64"); + let endpointSuffix = ""; + accountName = getValueInConnString(connectionString, "AccountName"); + accountKey = (0, import_core_util.stringToUint8Array)(getValueInConnString(connectionString, "AccountKey"), "base64"); + if (!blobEndpoint) { + defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); + const protocol = defaultEndpointsProtocol.toLowerCase(); + if (protocol !== "https" && protocol !== "http") { + throw new Error( + "Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'" + ); + } + endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix"); + if (!endpointSuffix) { + throw new Error("Invalid EndpointSuffix in the provided Connection String"); + } + blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; + } + if (!accountName) { + throw new Error("Invalid AccountName in the provided Connection String"); + } else if (accountKey.length === 0) { + throw new Error("Invalid AccountKey in the provided Connection String"); + } + return { + kind: "AccountConnString", + url: blobEndpoint, + accountName, + accountKey, + proxyUri + }; + } else { + let accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); + let accountName = getValueInConnString(connectionString, "AccountName"); + if (!accountName) { + accountName = getAccountNameFromUrl(blobEndpoint); + } + if (!blobEndpoint) { + throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); + } else if (!accountSas) { + throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); + } + if (accountSas.startsWith("?")) { + accountSas = accountSas.substring(1); + } + return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas }; + } + } + function escape3(text) { + return encodeURIComponent(text).replace(/%2F/g, "/").replace(/'/g, "%27").replace(/\+/g, "%20").replace(/%25/g, "%"); + } + function appendToURLPath(url2, name) { + const urlParsed = new URL(url2); + let path30 = urlParsed.pathname; + path30 = path30 ? path30.endsWith("/") ? `${path30}${name}` : `${path30}/${name}` : name; + urlParsed.pathname = path30; + return urlParsed.toString(); + } + function setURLParameter(url2, name, value) { + const urlParsed = new URL(url2); + const encodedName = encodeURIComponent(name); + const encodedValue = value ? encodeURIComponent(value) : void 0; + const searchString = urlParsed.search === "" ? "?" : urlParsed.search; + const searchPieces = []; + for (const pair of searchString.slice(1).split("&")) { + if (pair) { + const [key] = pair.split("=", 2); + if (key !== encodedName) { + searchPieces.push(pair); + } + } + } + if (encodedValue) { + searchPieces.push(`${encodedName}=${encodedValue}`); + } + urlParsed.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; + return urlParsed.toString(); + } + function getURLParameter(url2, name) { + const urlParsed = new URL(url2); + return urlParsed.searchParams.get(name) ?? void 0; + } + function setURLHost(url2, host) { + const urlParsed = new URL(url2); + urlParsed.hostname = host; + return urlParsed.toString(); + } + function getURLPath(url2) { + try { + const urlParsed = new URL(url2); + return urlParsed.pathname; + } catch (e) { + return void 0; + } + } + function getURLScheme(url2) { + try { + const urlParsed = new URL(url2); + return urlParsed.protocol.endsWith(":") ? urlParsed.protocol.slice(0, -1) : urlParsed.protocol; + } catch (e) { + return void 0; + } + } + function getURLPathAndQuery(url2) { + const urlParsed = new URL(url2); + const pathString = urlParsed.pathname; + if (!pathString) { + throw new RangeError("Invalid url without valid path."); + } + let queryString = urlParsed.search || ""; + queryString = queryString.trim(); + if (queryString !== "") { + queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; + } + return `${pathString}${queryString}`; + } + function getURLQueries(url2) { + let queryString = new URL(url2).search; + if (!queryString) { + return {}; + } + queryString = queryString.trim(); + queryString = queryString.startsWith("?") ? queryString.substring(1) : queryString; + let querySubStrings = queryString.split("&"); + querySubStrings = querySubStrings.filter((value) => { + const indexOfEqual = value.indexOf("="); + const lastIndexOfEqual = value.lastIndexOf("="); + return indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1; + }); + const queries = {}; + for (const querySubString of querySubStrings) { + const splitResults = querySubString.split("="); + const key = splitResults[0]; + const value = splitResults[1]; + queries[key] = value; + } + return queries; + } + function appendToURLQuery(url2, queryParts) { + const urlParsed = new URL(url2); + let query = urlParsed.search; + if (query) { + query += "&" + queryParts; + } else { + query = queryParts; + } + urlParsed.search = query; + return urlParsed.toString(); + } + function truncatedISO8061Date(date, withMilliseconds = true) { + const dateString = date.toISOString(); + return withMilliseconds ? dateString.substring(0, dateString.length - 1) + "0000Z" : dateString.substring(0, dateString.length - 5) + "Z"; + } + function generateBlockID(blockIDPrefix, blockIndex) { + const maxSourceStringLength = 48; + const maxBlockIndexLength = 6; + const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; + if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { + blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); + } + const res = blockIDPrefix + padStart2(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); + return (0, import_core_util.uint8ArrayToString)((0, import_core_util.stringToUint8Array)(res, "utf-8"), "base64"); + } + async function delay2(timeInMs, aborter, abortError) { + return new Promise((resolve15, reject) => { + let timeout; + const abortHandler = () => { + if (timeout !== void 0) { + clearTimeout(timeout); + } + reject(abortError); + }; + const resolveHandler = () => { + if (aborter !== void 0) { + aborter.removeEventListener("abort", abortHandler); + } + resolve15(); + }; + timeout = setTimeout(resolveHandler, timeInMs); + if (aborter !== void 0) { + aborter.addEventListener("abort", abortHandler); + } + }); + } + function padStart2(currentString, targetLength, padString = " ") { + if (String.prototype.padStart) { + return currentString.padStart(targetLength, padString); + } + padString = padString || " "; + if (currentString.length > targetLength) { + return currentString; + } else { + targetLength = targetLength - currentString.length; + if (targetLength > padString.length) { + padString += padString.repeat(targetLength / padString.length); + } + return padString.slice(0, targetLength) + currentString; + } + } + function sanitizeURL(url2) { + let safeURL = url2; + if (getURLParameter(safeURL, import_constants5.URLConstants.Parameters.SIGNATURE)) { + safeURL = setURLParameter(safeURL, import_constants5.URLConstants.Parameters.SIGNATURE, "*****"); + } + return safeURL; + } + function sanitizeHeaders(originalHeader) { + const headers = (0, import_core_rest_pipeline.createHttpHeaders)(); + for (const [name, value] of originalHeader) { + if (name.toLowerCase() === import_constants5.HeaderConstants.AUTHORIZATION.toLowerCase()) { + headers.set(name, "*****"); + } else if (name.toLowerCase() === import_constants5.HeaderConstants.X_MS_COPY_SOURCE) { + headers.set(name, sanitizeURL(value)); + } else { + headers.set(name, value); + } + } + return headers; + } + function iEqual(str1, str2) { + return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); + } + function getAccountNameFromUrl(url2) { + const parsedUrl = new URL(url2); + let accountName; + try { + if (parsedUrl.hostname.split(".")[1] === "blob") { + accountName = parsedUrl.hostname.split(".")[0]; + } else if (isIpEndpointStyle(parsedUrl)) { + accountName = parsedUrl.pathname.split("/")[1]; + } else { + accountName = ""; + } + return accountName; + } catch (error3) { + throw new Error("Unable to extract accountName with provided information."); + } + } + function isIpEndpointStyle(parsedUrl) { + const host = parsedUrl.host; + return /^.*:.*:.*$|^(localhost|host.docker.internal)(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test( + host + ) || Boolean(parsedUrl.port) && import_constants5.PathStylePorts.includes(parsedUrl.port); + } + function attachCredential(thing, credential) { + thing.credential = credential; + return thing; + } + function httpAuthorizationToString(httpAuthorization) { + return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : void 0; + } + function EscapePath(blobName) { + const split = blobName.split("/"); + for (let i = 0; i < split.length; i++) { + split[i] = encodeURIComponent(split[i]); + } + return split.join("/"); + } + function assertResponse(response) { + if (`_response` in response) { + return response; + } + throw new TypeError(`Unexpected response object ${response}`); + } + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/utils/SharedKeyComparator.js +var require_SharedKeyComparator = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/utils/SharedKeyComparator.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var SharedKeyComparator_exports = {}; + __export2(SharedKeyComparator_exports, { + compareHeader: () => compareHeader + }); + module2.exports = __toCommonJS2(SharedKeyComparator_exports); + var table_lv0 = new Uint32Array([ + 0, + 0, + 0, + 0, 0, 0, 0, @@ -47728,8 +61113,7 @@ var require_SharedKeyComparator = __commonJS({ 0 ]); function compareHeader(lhs, rhs) { - if (isLessThan(lhs, rhs)) - return -1; + if (isLessThan(lhs, rhs)) return -1; return 1; } function isLessThan(lhs, rhs) { @@ -47763,17 +61147,36 @@ var require_SharedKeyComparator = __commonJS({ } }); -// node_modules/@azure/storage-blob/dist/commonjs/policies/StorageSharedKeyCredentialPolicy.js +// node_modules/@azure/storage-common/dist/commonjs/policies/StorageSharedKeyCredentialPolicy.js var require_StorageSharedKeyCredentialPolicy = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/policies/StorageSharedKeyCredentialPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageSharedKeyCredentialPolicy = void 0; - var constants_js_1 = require_constants10(); - var utils_common_js_1 = require_utils_common(); - var CredentialPolicy_js_1 = require_CredentialPolicy(); - var SharedKeyComparator_js_1 = require_SharedKeyComparator(); - var StorageSharedKeyCredentialPolicy = class extends CredentialPolicy_js_1.CredentialPolicy { + "node_modules/@azure/storage-common/dist/commonjs/policies/StorageSharedKeyCredentialPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageSharedKeyCredentialPolicy_exports = {}; + __export2(StorageSharedKeyCredentialPolicy_exports, { + StorageSharedKeyCredentialPolicy: () => StorageSharedKeyCredentialPolicy2 + }); + module2.exports = __toCommonJS2(StorageSharedKeyCredentialPolicy_exports); + var import_constants5 = require_constants10(); + var import_utils_common = require_utils_common(); + var import_CredentialPolicy = require_CredentialPolicy(); + var import_SharedKeyComparator = require_SharedKeyComparator(); + var StorageSharedKeyCredentialPolicy2 = class extends import_CredentialPolicy.CredentialPolicy { /** * Reference to StorageSharedKeyCredential which generates StorageSharedKeyCredentialPolicy */ @@ -47794,26 +61197,29 @@ var require_StorageSharedKeyCredentialPolicy = __commonJS({ * @param request - */ signRequest(request3) { - request3.headers.set(constants_js_1.HeaderConstants.X_MS_DATE, (/* @__PURE__ */ new Date()).toUTCString()); + request3.headers.set(import_constants5.HeaderConstants.X_MS_DATE, (/* @__PURE__ */ new Date()).toUTCString()); if (request3.body && (typeof request3.body === "string" || request3.body !== void 0) && request3.body.length > 0) { - request3.headers.set(constants_js_1.HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request3.body)); + request3.headers.set(import_constants5.HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request3.body)); } const stringToSign = [ request3.method.toUpperCase(), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_LANGUAGE), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_ENCODING), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_LENGTH), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_MD5), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_TYPE), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.DATE), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_MODIFIED_SINCE), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_MATCH), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_NONE_MATCH), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_UNMODIFIED_SINCE), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.RANGE) + this.getHeaderValueToSign(request3, import_constants5.HeaderConstants.CONTENT_LANGUAGE), + this.getHeaderValueToSign(request3, import_constants5.HeaderConstants.CONTENT_ENCODING), + this.getHeaderValueToSign(request3, import_constants5.HeaderConstants.CONTENT_LENGTH), + this.getHeaderValueToSign(request3, import_constants5.HeaderConstants.CONTENT_MD5), + this.getHeaderValueToSign(request3, import_constants5.HeaderConstants.CONTENT_TYPE), + this.getHeaderValueToSign(request3, import_constants5.HeaderConstants.DATE), + this.getHeaderValueToSign(request3, import_constants5.HeaderConstants.IF_MODIFIED_SINCE), + this.getHeaderValueToSign(request3, import_constants5.HeaderConstants.IF_MATCH), + this.getHeaderValueToSign(request3, import_constants5.HeaderConstants.IF_NONE_MATCH), + this.getHeaderValueToSign(request3, import_constants5.HeaderConstants.IF_UNMODIFIED_SINCE), + this.getHeaderValueToSign(request3, import_constants5.HeaderConstants.RANGE) ].join("\n") + "\n" + this.getCanonicalizedHeadersString(request3) + this.getCanonicalizedResourceString(request3); const signature = this.factory.computeHMACSHA256(stringToSign); - request3.headers.set(constants_js_1.HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`); + request3.headers.set( + import_constants5.HeaderConstants.AUTHORIZATION, + `SharedKey ${this.factory.accountName}:${signature}` + ); return request3; } /** @@ -47828,7 +61234,7 @@ var require_StorageSharedKeyCredentialPolicy = __commonJS({ if (!value) { return ""; } - if (headerName === constants_js_1.HeaderConstants.CONTENT_LENGTH && value === "0") { + if (headerName === import_constants5.HeaderConstants.CONTENT_LENGTH && value === "0") { return ""; } return value; @@ -47848,10 +61254,10 @@ var require_StorageSharedKeyCredentialPolicy = __commonJS({ */ getCanonicalizedHeadersString(request3) { let headersArray = request3.headers.headersArray().filter((value) => { - return value.name.toLowerCase().startsWith(constants_js_1.HeaderConstants.PREFIX_FOR_STORAGE); + return value.name.toLowerCase().startsWith(import_constants5.HeaderConstants.PREFIX_FOR_STORAGE); }); headersArray.sort((a, b) => { - return (0, SharedKeyComparator_js_1.compareHeader)(a.name.toLowerCase(), b.name.toLowerCase()); + return (0, import_SharedKeyComparator.compareHeader)(a.name.toLowerCase(), b.name.toLowerCase()); }); headersArray = headersArray.filter((value, index2, array2) => { if (index2 > 0 && value.name.toLowerCase() === array2[index2 - 1].name.toLowerCase()) { @@ -47872,10 +61278,10 @@ var require_StorageSharedKeyCredentialPolicy = __commonJS({ * @param request - */ getCanonicalizedResourceString(request3) { - const path30 = (0, utils_common_js_1.getURLPath)(request3.url) || "/"; + const path30 = (0, import_utils_common.getURLPath)(request3.url) || "/"; let canonicalizedResourceString = ""; canonicalizedResourceString += `/${this.factory.accountName}${path30}`; - const queries = (0, utils_common_js_1.getURLQueries)(request3.url); + const queries = (0, import_utils_common.getURLQueries)(request3.url); const lowercaseQueries = {}; if (queries) { const queryKeys = []; @@ -47895,41 +61301,38 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; return canonicalizedResourceString; } }; - exports2.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; } }); -// node_modules/@azure/storage-blob/dist/commonjs/credentials/Credential.js -var require_Credential = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/credentials/Credential.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Credential = void 0; - var Credential2 = class { - /** - * Creates a RequestPolicy object. - * - * @param _nextPolicy - - * @param _options - - */ - create(_nextPolicy, _options) { - throw new Error("Method should be implemented in children classes."); +// node_modules/@azure/storage-common/dist/commonjs/credentials/StorageSharedKeyCredential.js +var require_StorageSharedKeyCredential = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/credentials/StorageSharedKeyCredential.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.Credential = Credential2; - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/credentials/StorageSharedKeyCredential.js -var require_StorageSharedKeyCredential = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/credentials/StorageSharedKeyCredential.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageSharedKeyCredential = void 0; - var node_crypto_1 = require("node:crypto"); - var StorageSharedKeyCredentialPolicy_js_1 = require_StorageSharedKeyCredentialPolicy(); - var Credential_js_1 = require_Credential(); - var StorageSharedKeyCredential = class extends Credential_js_1.Credential { + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageSharedKeyCredential_exports = {}; + __export2(StorageSharedKeyCredential_exports, { + StorageSharedKeyCredential: () => StorageSharedKeyCredential2 + }); + module2.exports = __toCommonJS2(StorageSharedKeyCredential_exports); + var import_node_crypto = require("node:crypto"); + var import_StorageSharedKeyCredentialPolicy = require_StorageSharedKeyCredentialPolicy(); + var import_Credential = require_Credential(); + var StorageSharedKeyCredential2 = class extends import_Credential.Credential { /** * Azure Storage account name; readonly. */ @@ -47955,7 +61358,7 @@ var require_StorageSharedKeyCredential = __commonJS({ * @param options - */ create(nextPolicy, options) { - return new StorageSharedKeyCredentialPolicy_js_1.StorageSharedKeyCredentialPolicy(nextPolicy, options, this); + return new import_StorageSharedKeyCredentialPolicy.StorageSharedKeyCredentialPolicy(nextPolicy, options, this); } /** * Generates a hash signature for an HTTP request or for a SAS. @@ -47963,559 +61366,1043 @@ var require_StorageSharedKeyCredential = __commonJS({ * @param stringToSign - */ computeHMACSHA256(stringToSign) { - return (0, node_crypto_1.createHmac)("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64"); + return (0, import_node_crypto.createHmac)("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64"); } }; - exports2.StorageSharedKeyCredential = StorageSharedKeyCredential; } }); -// node_modules/@azure/storage-blob/dist/commonjs/policies/AnonymousCredentialPolicy.js -var require_AnonymousCredentialPolicy = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/policies/AnonymousCredentialPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AnonymousCredentialPolicy = void 0; - var CredentialPolicy_js_1 = require_CredentialPolicy(); - var AnonymousCredentialPolicy = class extends CredentialPolicy_js_1.CredentialPolicy { - /** - * Creates an instance of AnonymousCredentialPolicy. - * @param nextPolicy - - * @param options - - */ - // The base class has a protected constructor. Adding a public one to enable constructing of this class. - /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ - constructor(nextPolicy, options) { - super(nextPolicy, options); +// node_modules/@azure/storage-common/dist/commonjs/log.js +var require_log6 = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/log.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.AnonymousCredentialPolicy = AnonymousCredentialPolicy; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var log_exports = {}; + __export2(log_exports, { + logger: () => logger2 + }); + module2.exports = __toCommonJS2(log_exports); + var import_logger = require_commonjs2(); + var logger2 = (0, import_logger.createClientLogger)("storage-common"); } }); -// node_modules/@azure/storage-blob/dist/commonjs/credentials/AnonymousCredential.js -var require_AnonymousCredential = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/credentials/AnonymousCredential.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AnonymousCredential = void 0; - var AnonymousCredentialPolicy_js_1 = require_AnonymousCredentialPolicy(); - var Credential_js_1 = require_Credential(); - var AnonymousCredential = class extends Credential_js_1.Credential { - /** - * Creates an {@link AnonymousCredentialPolicy} object. - * - * @param nextPolicy - - * @param options - - */ - create(nextPolicy, options) { - return new AnonymousCredentialPolicy_js_1.AnonymousCredentialPolicy(nextPolicy, options); +// node_modules/@azure/storage-common/dist/commonjs/policies/StorageRetryPolicyType.js +var require_StorageRetryPolicyType = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/policies/StorageRetryPolicyType.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.AnonymousCredential = AnonymousCredential; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageRetryPolicyType_exports = {}; + __export2(StorageRetryPolicyType_exports, { + StorageRetryPolicyType: () => StorageRetryPolicyType2 + }); + module2.exports = __toCommonJS2(StorageRetryPolicyType_exports); + var StorageRetryPolicyType2 = /* @__PURE__ */ ((StorageRetryPolicyType22) => { + StorageRetryPolicyType22[StorageRetryPolicyType22["EXPONENTIAL"] = 0] = "EXPONENTIAL"; + StorageRetryPolicyType22[StorageRetryPolicyType22["FIXED"] = 1] = "FIXED"; + return StorageRetryPolicyType22; + })(StorageRetryPolicyType2 || {}); } }); -// node_modules/@azure/storage-common/dist/commonjs/BuffersStream.js -var require_BuffersStream = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/BuffersStream.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BuffersStream = void 0; - var node_stream_1 = require("node:stream"); - var BuffersStream = class extends node_stream_1.Readable { - buffers; - byteLength; +// node_modules/@azure/storage-common/dist/commonjs/policies/StorageRetryPolicy.js +var require_StorageRetryPolicy = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/policies/StorageRetryPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageRetryPolicy_exports = {}; + __export2(StorageRetryPolicy_exports, { + NewRetryPolicyFactory: () => NewRetryPolicyFactory2, + StorageRetryPolicy: () => StorageRetryPolicy2 + }); + module2.exports = __toCommonJS2(StorageRetryPolicy_exports); + var import_abort_controller = require_commonjs11(); + var import_RequestPolicy = require_RequestPolicy(); + var import_constants5 = require_constants10(); + var import_utils_common = require_utils_common(); + var import_log = require_log6(); + var import_StorageRetryPolicyType = require_StorageRetryPolicyType(); + function NewRetryPolicyFactory2(retryOptions) { + return { + create: (nextPolicy, options) => { + return new StorageRetryPolicy2(nextPolicy, options, retryOptions); + } + }; + } + var DEFAULT_RETRY_OPTIONS = { + maxRetryDelayInMs: 120 * 1e3, + maxTries: 4, + retryDelayInMs: 4 * 1e3, + retryPolicyType: import_StorageRetryPolicyType.StorageRetryPolicyType.EXPONENTIAL, + secondaryHost: "", + tryTimeoutInMs: void 0 + // Use server side default timeout strategy + }; + var RETRY_ABORT_ERROR = new import_abort_controller.AbortError("The operation was aborted."); + var StorageRetryPolicy2 = class extends import_RequestPolicy.BaseRequestPolicy { /** - * The offset of data to be read in the current buffer. + * RetryOptions. */ - byteOffsetInCurrentBuffer; + retryOptions; /** - * The index of buffer to be read in the array of buffers. + * Creates an instance of RetryPolicy. + * + * @param nextPolicy - + * @param options - + * @param retryOptions - */ - bufferIndex; + constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS) { + super(nextPolicy, options); + this.retryOptions = { + retryPolicyType: retryOptions.retryPolicyType ? retryOptions.retryPolicyType : DEFAULT_RETRY_OPTIONS.retryPolicyType, + maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1 ? Math.floor(retryOptions.maxTries) : DEFAULT_RETRY_OPTIONS.maxTries, + tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0 ? retryOptions.tryTimeoutInMs : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs, + retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0 ? Math.min( + retryOptions.retryDelayInMs, + retryOptions.maxRetryDelayInMs ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs + ) : DEFAULT_RETRY_OPTIONS.retryDelayInMs, + maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0 ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs, + secondaryHost: retryOptions.secondaryHost ? retryOptions.secondaryHost : DEFAULT_RETRY_OPTIONS.secondaryHost + }; + } /** - * The total length of data already read. + * Sends request. + * + * @param request - */ - pushedBytesLength; + async sendRequest(request3) { + return this.attemptSendRequest(request3, false, 1); + } /** - * Creates an instance of BuffersStream that will emit the data - * contained in the array of buffers. + * Decide and perform next retry. Won't mutate request parameter. * - * @param buffers - Array of buffers containing the data - * @param byteLength - The total length of data contained in the buffers + * @param request - + * @param secondaryHas404 - If attempt was against the secondary & it returned a StatusNotFound (404), then + * the resource was not found. This may be due to replication delay. So, in this + * case, we'll never try the secondary again for this operation. + * @param attempt - How many retries has been attempted to performed, starting from 1, which includes + * the attempt will be performed by this method call. */ - constructor(buffers, byteLength, options) { - super(options); - this.buffers = buffers; - this.byteLength = byteLength; - this.byteOffsetInCurrentBuffer = 0; - this.bufferIndex = 0; - this.pushedBytesLength = 0; - let buffersLength = 0; - for (const buf of this.buffers) { - buffersLength += buf.byteLength; + async attemptSendRequest(request3, secondaryHas404, attempt) { + const newRequest = request3.clone(); + const isPrimaryRetry = secondaryHas404 || !this.retryOptions.secondaryHost || !(request3.method === "GET" || request3.method === "HEAD" || request3.method === "OPTIONS") || attempt % 2 === 1; + if (!isPrimaryRetry) { + newRequest.url = (0, import_utils_common.setURLHost)(newRequest.url, this.retryOptions.secondaryHost); } - if (buffersLength < this.byteLength) { - throw new Error("Data size shouldn't be larger than the total length of buffers."); + if (this.retryOptions.tryTimeoutInMs) { + newRequest.url = (0, import_utils_common.setURLParameter)( + newRequest.url, + import_constants5.URLConstants.Parameters.TIMEOUT, + Math.floor(this.retryOptions.tryTimeoutInMs / 1e3).toString() + ); + } + let response; + try { + import_log.logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); + response = await this._nextPolicy.sendRequest(newRequest); + if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { + return response; + } + secondaryHas404 = secondaryHas404 || !isPrimaryRetry && response.status === 404; + } catch (err) { + import_log.logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`); + if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) { + throw err; + } } + await this.delay(isPrimaryRetry, attempt, request3.abortSignal); + return this.attemptSendRequest(request3, secondaryHas404, ++attempt); } /** - * Internal _read() that will be called when the stream wants to pull more data in. + * Decide whether to retry according to last HTTP response and retry counters. * - * @param size - Optional. The size of data to be read + * @param isPrimaryRetry - + * @param attempt - + * @param response - + * @param err - */ - _read(size) { - if (this.pushedBytesLength >= this.byteLength) { - this.push(null); - } - if (!size) { - size = this.readableHighWaterMark; + shouldRetry(isPrimaryRetry, attempt, response, err) { + if (attempt >= this.retryOptions.maxTries) { + import_log.logger.info( + `RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions.maxTries}, no further try.` + ); + return false; } - const outBuffers = []; - let i = 0; - while (i < size && this.pushedBytesLength < this.byteLength) { - const remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength; - const remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer; - const remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers); - if (remaining > size - i) { - const end = this.byteOffsetInCurrentBuffer + size - i; - outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); - this.pushedBytesLength += size - i; - this.byteOffsetInCurrentBuffer = end; - i = size; - break; - } else { - const end = this.byteOffsetInCurrentBuffer + remaining; - outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); - if (remaining === remainingCapacityInThisBuffer) { - this.byteOffsetInCurrentBuffer = 0; - this.bufferIndex++; - } else { - this.byteOffsetInCurrentBuffer = end; + const retriableErrors = [ + "ETIMEDOUT", + "ESOCKETTIMEDOUT", + "ECONNREFUSED", + "ECONNRESET", + "ENOENT", + "ENOTFOUND", + "TIMEOUT", + "EPIPE", + "REQUEST_SEND_ERROR" + // For default xhr based http client provided in ms-rest-js + ]; + if (err) { + for (const retriableError of retriableErrors) { + if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || err.code && err.code.toString().toUpperCase() === retriableError) { + import_log.logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); + return true; } - this.pushedBytesLength += remaining; - i += remaining; } } - if (outBuffers.length > 1) { - this.push(Buffer.concat(outBuffers)); - } else if (outBuffers.length === 1) { - this.push(outBuffers[0]); + if (response || err) { + const statusCode = response ? response.status : err ? err.statusCode : 0; + if (!isPrimaryRetry && statusCode === 404) { + import_log.logger.info(`RetryPolicy: Secondary access with 404, will retry.`); + return true; + } + if (statusCode === 503 || statusCode === 500) { + import_log.logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); + return true; + } } - } - }; - exports2.BuffersStream = BuffersStream; - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/PooledBuffer.js -var require_PooledBuffer = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/PooledBuffer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PooledBuffer = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var BuffersStream_js_1 = require_BuffersStream(); - var node_buffer_1 = tslib_1.__importDefault(require("node:buffer")); - var maxBufferLength = node_buffer_1.default.constants.MAX_LENGTH; - var PooledBuffer = class { - /** - * Internal buffers used to keep the data. - * Each buffer has a length of the maxBufferLength except last one. - */ - buffers = []; - /** - * The total size of internal buffers. - */ - capacity; - /** - * The total size of data contained in internal buffers. - */ - _size; - /** - * The size of the data contained in the pooled buffers. - */ - get size() { - return this._size; - } - constructor(capacity, buffers, totalLength) { - this.capacity = capacity; - this._size = 0; - const bufferNum = Math.ceil(capacity / maxBufferLength); - for (let i = 0; i < bufferNum; i++) { - let len = i === bufferNum - 1 ? capacity % maxBufferLength : maxBufferLength; - if (len === 0) { - len = maxBufferLength; + if (response) { + if (response?.status >= 400) { + const copySourceError = response.headers.get(import_constants5.HeaderConstants.X_MS_CopySourceErrorCode); + if (copySourceError !== void 0) { + switch (copySourceError) { + case "InternalError": + case "OperationTimedOut": + case "ServerBusy": + return true; + } + } } - this.buffers.push(Buffer.allocUnsafe(len)); } - if (buffers) { - this.fill(buffers, totalLength); + if (err?.code === "PARSE_ERROR" && err?.message.startsWith(`Error "Error: Unclosed root tag`)) { + import_log.logger.info( + "RetryPolicy: Incomplete XML response likely due to service timeout, will retry." + ); + return true; } + return false; } /** - * Fill the internal buffers with data in the input buffers serially - * with respect to the total length and the total capacity of the internal buffers. - * Data copied will be shift out of the input buffers. - * - * @param buffers - Input buffers containing the data to be filled in the pooled buffer - * @param totalLength - Total length of the data to be filled in. + * Delay a calculated time between retries. * + * @param isPrimaryRetry - + * @param attempt - + * @param abortSignal - */ - fill(buffers, totalLength) { - this._size = Math.min(this.capacity, totalLength); - let i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0; - while (totalCopiedNum < this._size) { - const source = buffers[i]; - const target = this.buffers[j]; - const copiedNum = source.copy(target, targetOffset, sourceOffset); - totalCopiedNum += copiedNum; - sourceOffset += copiedNum; - targetOffset += copiedNum; - if (sourceOffset === source.length) { - i++; - sourceOffset = 0; - } - if (targetOffset === target.length) { - j++; - targetOffset = 0; + async delay(isPrimaryRetry, attempt, abortSignal) { + let delayTimeInMs = 0; + if (isPrimaryRetry) { + switch (this.retryOptions.retryPolicyType) { + case import_StorageRetryPolicyType.StorageRetryPolicyType.EXPONENTIAL: + delayTimeInMs = Math.min( + (Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, + this.retryOptions.maxRetryDelayInMs + ); + break; + case import_StorageRetryPolicyType.StorageRetryPolicyType.FIXED: + delayTimeInMs = this.retryOptions.retryDelayInMs; + break; } + } else { + delayTimeInMs = Math.random() * 1e3; } - buffers.splice(0, i); - if (buffers.length > 0) { - buffers[0] = buffers[0].slice(sourceOffset); - } - } - /** - * Get the readable stream assembled from all the data in the internal buffers. - * - */ - getReadableStream() { - return new BuffersStream_js_1.BuffersStream(this.buffers, this.size); + import_log.logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); + return (0, import_utils_common.delay)(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR); } }; - exports2.PooledBuffer = PooledBuffer; } }); -// node_modules/@azure/storage-common/dist/commonjs/BufferScheduler.js -var require_BufferScheduler = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/BufferScheduler.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BufferScheduler = void 0; - var events_1 = require("events"); - var PooledBuffer_js_1 = require_PooledBuffer(); - var BufferScheduler = class { - /** - * Size of buffers in incoming and outgoing queues. This class will try to align - * data read from Readable stream into buffer chunks with bufferSize defined. - */ - bufferSize; - /** - * How many buffers can be created or maintained. - */ - maxBuffers; - /** - * A Node.js Readable stream. - */ - readable; - /** - * OutgoingHandler is an async function triggered by BufferScheduler when there - * are available buffers in outgoing array. - */ - outgoingHandler; - /** - * An internal event emitter. - */ - emitter = new events_1.EventEmitter(); - /** - * Concurrency of executing outgoingHandlers. (0 lesser than concurrency lesser than or equal to maxBuffers) - */ - concurrency; - /** - * An internal offset marker to track data offset in bytes of next outgoingHandler. - */ - offset = 0; - /** - * An internal marker to track whether stream is end. - */ - isStreamEnd = false; - /** - * An internal marker to track whether stream or outgoingHandler returns error. - */ - isError = false; - /** - * How many handlers are executing. - */ - executingOutgoingHandlers = 0; - /** - * Encoding of the input Readable stream which has string data type instead of Buffer. - */ - encoding; - /** - * How many buffers have been allocated. - */ - numBuffers = 0; - /** - * Because this class doesn't know how much data every time stream pops, which - * is defined by highWaterMarker of the stream. So BufferScheduler will cache - * data received from the stream, when data in unresolvedDataArray exceeds the - * blockSize defined, it will try to concat a blockSize of buffer, fill into available - * buffers from incoming and push to outgoing array. - */ - unresolvedDataArray = []; - /** - * How much data consisted in unresolvedDataArray. - */ - unresolvedLength = 0; - /** - * The array includes all the available buffers can be used to fill data from stream. - */ - incoming = []; +// node_modules/@azure/storage-common/dist/commonjs/StorageRetryPolicyFactory.js +var require_StorageRetryPolicyFactory = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/StorageRetryPolicyFactory.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageRetryPolicyFactory_exports = {}; + __export2(StorageRetryPolicyFactory_exports, { + NewRetryPolicyFactory: () => import_StorageRetryPolicy.NewRetryPolicyFactory, + StorageRetryPolicy: () => import_StorageRetryPolicy.StorageRetryPolicy, + StorageRetryPolicyFactory: () => StorageRetryPolicyFactory2, + StorageRetryPolicyType: () => import_StorageRetryPolicyType.StorageRetryPolicyType + }); + module2.exports = __toCommonJS2(StorageRetryPolicyFactory_exports); + var import_StorageRetryPolicy = require_StorageRetryPolicy(); + var import_StorageRetryPolicyType = require_StorageRetryPolicyType(); + var StorageRetryPolicyFactory2 = class { + retryOptions; /** - * The array (queue) includes all the buffers filled from stream data. + * Creates an instance of StorageRetryPolicyFactory. + * @param retryOptions - */ - outgoing = []; + constructor(retryOptions) { + this.retryOptions = retryOptions; + } /** - * Creates an instance of BufferScheduler. + * Creates a StorageRetryPolicy object. * - * @param readable - A Node.js Readable stream - * @param bufferSize - Buffer size of every maintained buffer - * @param maxBuffers - How many buffers can be allocated - * @param outgoingHandler - An async function scheduled to be - * triggered when a buffer fully filled - * with stream data - * @param concurrency - Concurrency of executing outgoingHandlers (>0) - * @param encoding - [Optional] Encoding of Readable stream when it's a string stream + * @param nextPolicy - + * @param options - */ - constructor(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) { - if (bufferSize <= 0) { - throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`); + create(nextPolicy, options) { + return new import_StorageRetryPolicy.StorageRetryPolicy(nextPolicy, options, this.retryOptions); + } + }; + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/policies/StorageBrowserPolicyV2.js +var require_StorageBrowserPolicyV2 = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/policies/StorageBrowserPolicyV2.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageBrowserPolicyV2_exports = {}; + __export2(StorageBrowserPolicyV2_exports, { + storageBrowserPolicy: () => storageBrowserPolicy, + storageBrowserPolicyName: () => storageBrowserPolicyName + }); + module2.exports = __toCommonJS2(StorageBrowserPolicyV2_exports); + var storageBrowserPolicyName = "storageBrowserPolicy"; + function storageBrowserPolicy() { + return { + name: storageBrowserPolicyName, + async sendRequest(request3, next) { + return next(request3); } - if (maxBuffers <= 0) { - throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`); + }; + } + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/policies/StorageCorrectContentLengthPolicy.js +var require_StorageCorrectContentLengthPolicy = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/policies/StorageCorrectContentLengthPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageCorrectContentLengthPolicy_exports = {}; + __export2(StorageCorrectContentLengthPolicy_exports, { + storageCorrectContentLengthPolicy: () => storageCorrectContentLengthPolicy, + storageCorrectContentLengthPolicyName: () => storageCorrectContentLengthPolicyName + }); + module2.exports = __toCommonJS2(StorageCorrectContentLengthPolicy_exports); + var import_constants5 = require_constants10(); + var storageCorrectContentLengthPolicyName = "StorageCorrectContentLengthPolicy"; + function storageCorrectContentLengthPolicy() { + function correctContentLength(request3) { + if (request3.body && (typeof request3.body === "string" || Buffer.isBuffer(request3.body)) && request3.body.length > 0) { + request3.headers.set(import_constants5.HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request3.body)); } - if (concurrency <= 0) { - throw new RangeError(`concurrency must be larger than 0, current is ${concurrency}`); + } + return { + name: storageCorrectContentLengthPolicyName, + async sendRequest(request3, next) { + correctContentLength(request3); + return next(request3); } - this.bufferSize = bufferSize; - this.maxBuffers = maxBuffers; - this.readable = readable; - this.outgoingHandler = outgoingHandler; - this.concurrency = concurrency; - this.encoding = encoding; + }; + } + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/policies/StorageRetryPolicyV2.js +var require_StorageRetryPolicyV2 = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/policies/StorageRetryPolicyV2.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - /** - * Start the scheduler, will return error when stream of any of the outgoingHandlers - * returns error. - * - */ - async do() { - return new Promise((resolve14, reject) => { - this.readable.on("data", (data) => { - data = typeof data === "string" ? Buffer.from(data, this.encoding) : data; - this.appendUnresolvedData(data); - if (!this.resolveData()) { - this.readable.pause(); - } - }); - this.readable.on("error", (err) => { - this.emitter.emit("error", err); - }); - this.readable.on("end", () => { - this.isStreamEnd = true; - this.emitter.emit("checkEnd"); - }); - this.emitter.on("error", (err) => { - this.isError = true; - this.readable.pause(); - reject(err); - }); - this.emitter.on("checkEnd", () => { - if (this.outgoing.length > 0) { - this.triggerOutgoingHandlers(); - return; + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageRetryPolicyV2_exports = {}; + __export2(StorageRetryPolicyV2_exports, { + storageRetryPolicy: () => storageRetryPolicy, + storageRetryPolicyName: () => storageRetryPolicyName + }); + module2.exports = __toCommonJS2(StorageRetryPolicyV2_exports); + var import_abort_controller = require_commonjs11(); + var import_core_rest_pipeline = require_commonjs6(); + var import_core_util = require_commonjs4(); + var import_StorageRetryPolicyFactory = require_StorageRetryPolicyFactory(); + var import_constants5 = require_constants10(); + var import_utils_common = require_utils_common(); + var import_log = require_log6(); + var storageRetryPolicyName = "storageRetryPolicy"; + var DEFAULT_RETRY_OPTIONS = { + maxRetryDelayInMs: 120 * 1e3, + maxTries: 4, + retryDelayInMs: 4 * 1e3, + retryPolicyType: import_StorageRetryPolicyFactory.StorageRetryPolicyType.EXPONENTIAL, + secondaryHost: "", + tryTimeoutInMs: void 0 + // Use server side default timeout strategy + }; + var retriableErrors = [ + "ETIMEDOUT", + "ESOCKETTIMEDOUT", + "ECONNREFUSED", + "ECONNRESET", + "ENOENT", + "ENOTFOUND", + "TIMEOUT", + "EPIPE", + "REQUEST_SEND_ERROR" + ]; + var RETRY_ABORT_ERROR = new import_abort_controller.AbortError("The operation was aborted."); + function storageRetryPolicy(options = {}) { + const retryPolicyType = options.retryPolicyType ?? DEFAULT_RETRY_OPTIONS.retryPolicyType; + const maxTries = options.maxTries ?? DEFAULT_RETRY_OPTIONS.maxTries; + const retryDelayInMs = options.retryDelayInMs ?? DEFAULT_RETRY_OPTIONS.retryDelayInMs; + const maxRetryDelayInMs = options.maxRetryDelayInMs ?? DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs; + const secondaryHost = options.secondaryHost ?? DEFAULT_RETRY_OPTIONS.secondaryHost; + const tryTimeoutInMs = options.tryTimeoutInMs ?? DEFAULT_RETRY_OPTIONS.tryTimeoutInMs; + function shouldRetry({ + isPrimaryRetry, + attempt, + response, + error: error3 + }) { + if (attempt >= maxTries) { + import_log.logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${maxTries}, no further try.`); + return false; + } + if (error3) { + for (const retriableError of retriableErrors) { + if (error3.name.toUpperCase().includes(retriableError) || error3.message.toUpperCase().includes(retriableError) || error3.code && error3.code.toString().toUpperCase() === retriableError) { + import_log.logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); + return true; } - if (this.isStreamEnd && this.executingOutgoingHandlers === 0) { - if (this.unresolvedLength > 0 && this.unresolvedLength < this.bufferSize) { - const buffer = this.shiftBufferFromUnresolvedDataArray(); - this.outgoingHandler(() => buffer.getReadableStream(), buffer.size, this.offset).then(resolve14).catch(reject); - } else if (this.unresolvedLength >= this.bufferSize) { - return; - } else { - resolve14(); + } + if (error3?.code === "PARSE_ERROR" && error3?.message.startsWith(`Error "Error: Unclosed root tag`)) { + import_log.logger.info( + "RetryPolicy: Incomplete XML response likely due to service timeout, will retry." + ); + return true; + } + } + if (response || error3) { + const statusCode = response?.status ?? error3?.statusCode ?? 0; + if (!isPrimaryRetry && statusCode === 404) { + import_log.logger.info(`RetryPolicy: Secondary access with 404, will retry.`); + return true; + } + if (statusCode === 503 || statusCode === 500) { + import_log.logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); + return true; + } + } + if (response) { + if (response?.status >= 400) { + const copySourceError = response.headers.get(import_constants5.HeaderConstants.X_MS_CopySourceErrorCode); + if (copySourceError !== void 0) { + switch (copySourceError) { + case "InternalError": + case "OperationTimedOut": + case "ServerBusy": + return true; } } - }); - }); - } - /** - * Insert a new data into unresolved array. - * - * @param data - - */ - appendUnresolvedData(data) { - this.unresolvedDataArray.push(data); - this.unresolvedLength += data.length; + } + } + return false; } - /** - * Try to shift a buffer with size in blockSize. The buffer returned may be less - * than blockSize when data in unresolvedDataArray is less than bufferSize. - * - */ - shiftBufferFromUnresolvedDataArray(buffer) { - if (!buffer) { - buffer = new PooledBuffer_js_1.PooledBuffer(this.bufferSize, this.unresolvedDataArray, this.unresolvedLength); + function calculateDelay(isPrimaryRetry, attempt) { + let delayTimeInMs = 0; + if (isPrimaryRetry) { + switch (retryPolicyType) { + case import_StorageRetryPolicyFactory.StorageRetryPolicyType.EXPONENTIAL: + delayTimeInMs = Math.min( + (Math.pow(2, attempt - 1) - 1) * retryDelayInMs, + maxRetryDelayInMs + ); + break; + case import_StorageRetryPolicyFactory.StorageRetryPolicyType.FIXED: + delayTimeInMs = retryDelayInMs; + break; + } } else { - buffer.fill(this.unresolvedDataArray, this.unresolvedLength); + delayTimeInMs = Math.random() * 1e3; } - this.unresolvedLength -= buffer.size; - return buffer; + import_log.logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); + return delayTimeInMs; } - /** - * Resolve data in unresolvedDataArray. For every buffer with size in blockSize - * shifted, it will try to get (or allocate a buffer) from incoming, and fill it, - * then push it into outgoing to be handled by outgoing handler. - * - * Return false when available buffers in incoming are not enough, else true. - * - * @returns Return false when buffers in incoming are not enough, else true. - */ - resolveData() { - while (this.unresolvedLength >= this.bufferSize) { - let buffer; - if (this.incoming.length > 0) { - buffer = this.incoming.shift(); - this.shiftBufferFromUnresolvedDataArray(buffer); - } else { - if (this.numBuffers < this.maxBuffers) { - buffer = this.shiftBufferFromUnresolvedDataArray(); - this.numBuffers++; - } else { - return false; + return { + name: storageRetryPolicyName, + async sendRequest(request3, next) { + if (tryTimeoutInMs) { + request3.url = (0, import_utils_common.setURLParameter)( + request3.url, + import_constants5.URLConstants.Parameters.TIMEOUT, + String(Math.floor(tryTimeoutInMs / 1e3)) + ); + } + const primaryUrl = request3.url; + const secondaryUrl = secondaryHost ? (0, import_utils_common.setURLHost)(request3.url, secondaryHost) : void 0; + let secondaryHas404 = false; + let attempt = 1; + let retryAgain = true; + let response; + let error3; + while (retryAgain) { + const isPrimaryRetry = secondaryHas404 || !secondaryUrl || !["GET", "HEAD", "OPTIONS"].includes(request3.method) || attempt % 2 === 1; + request3.url = isPrimaryRetry ? primaryUrl : secondaryUrl; + response = void 0; + error3 = void 0; + try { + import_log.logger.info( + `RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}` + ); + response = await next(request3); + secondaryHas404 = secondaryHas404 || !isPrimaryRetry && response.status === 404; + } catch (e) { + if ((0, import_core_rest_pipeline.isRestError)(e)) { + import_log.logger.error(`RetryPolicy: Caught error, message: ${e.message}, code: ${e.code}`); + error3 = e; + } else { + import_log.logger.error(`RetryPolicy: Caught error, message: ${(0, import_core_util.getErrorMessage)(e)}`); + throw e; + } + } + retryAgain = shouldRetry({ isPrimaryRetry, attempt, response, error: error3 }); + if (retryAgain) { + await (0, import_utils_common.delay)( + calculateDelay(isPrimaryRetry, attempt), + request3.abortSignal, + RETRY_ABORT_ERROR + ); } + attempt++; } - this.outgoing.push(buffer); - this.triggerOutgoingHandlers(); + if (response) { + return response; + } + throw error3 ?? new import_core_rest_pipeline.RestError("RetryPolicy failed without known error."); } - return true; + }; + } + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/policies/StorageSharedKeyCredentialPolicyV2.js +var require_StorageSharedKeyCredentialPolicyV2 = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/policies/StorageSharedKeyCredentialPolicyV2.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - /** - * Try to trigger a outgoing handler for every buffer in outgoing. Stop when - * concurrency reaches. - */ - async triggerOutgoingHandlers() { - let buffer; - do { - if (this.executingOutgoingHandlers >= this.concurrency) { - return; + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageSharedKeyCredentialPolicyV2_exports = {}; + __export2(StorageSharedKeyCredentialPolicyV2_exports, { + storageSharedKeyCredentialPolicy: () => storageSharedKeyCredentialPolicy, + storageSharedKeyCredentialPolicyName: () => storageSharedKeyCredentialPolicyName + }); + module2.exports = __toCommonJS2(StorageSharedKeyCredentialPolicyV2_exports); + var import_node_crypto = require("node:crypto"); + var import_constants5 = require_constants10(); + var import_utils_common = require_utils_common(); + var import_SharedKeyComparator = require_SharedKeyComparator(); + var storageSharedKeyCredentialPolicyName = "storageSharedKeyCredentialPolicy"; + function storageSharedKeyCredentialPolicy(options) { + function signRequest(request3) { + request3.headers.set(import_constants5.HeaderConstants.X_MS_DATE, (/* @__PURE__ */ new Date()).toUTCString()); + if (request3.body && (typeof request3.body === "string" || Buffer.isBuffer(request3.body)) && request3.body.length > 0) { + request3.headers.set(import_constants5.HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request3.body)); + } + const stringToSign = [ + request3.method.toUpperCase(), + getHeaderValueToSign(request3, import_constants5.HeaderConstants.CONTENT_LANGUAGE), + getHeaderValueToSign(request3, import_constants5.HeaderConstants.CONTENT_ENCODING), + getHeaderValueToSign(request3, import_constants5.HeaderConstants.CONTENT_LENGTH), + getHeaderValueToSign(request3, import_constants5.HeaderConstants.CONTENT_MD5), + getHeaderValueToSign(request3, import_constants5.HeaderConstants.CONTENT_TYPE), + getHeaderValueToSign(request3, import_constants5.HeaderConstants.DATE), + getHeaderValueToSign(request3, import_constants5.HeaderConstants.IF_MODIFIED_SINCE), + getHeaderValueToSign(request3, import_constants5.HeaderConstants.IF_MATCH), + getHeaderValueToSign(request3, import_constants5.HeaderConstants.IF_NONE_MATCH), + getHeaderValueToSign(request3, import_constants5.HeaderConstants.IF_UNMODIFIED_SINCE), + getHeaderValueToSign(request3, import_constants5.HeaderConstants.RANGE) + ].join("\n") + "\n" + getCanonicalizedHeadersString(request3) + getCanonicalizedResourceString(request3); + const signature = (0, import_node_crypto.createHmac)("sha256", options.accountKey).update(stringToSign, "utf8").digest("base64"); + request3.headers.set( + import_constants5.HeaderConstants.AUTHORIZATION, + `SharedKey ${options.accountName}:${signature}` + ); + } + function getHeaderValueToSign(request3, headerName) { + const value = request3.headers.get(headerName); + if (!value) { + return ""; + } + if (headerName === import_constants5.HeaderConstants.CONTENT_LENGTH && value === "0") { + return ""; + } + return value; + } + function getCanonicalizedHeadersString(request3) { + let headersArray = []; + for (const [name, value] of request3.headers) { + if (name.toLowerCase().startsWith(import_constants5.HeaderConstants.PREFIX_FOR_STORAGE)) { + headersArray.push({ name, value }); } - buffer = this.outgoing.shift(); - if (buffer) { - this.triggerOutgoingHandler(buffer); + } + headersArray.sort((a, b) => { + return (0, import_SharedKeyComparator.compareHeader)(a.name.toLowerCase(), b.name.toLowerCase()); + }); + headersArray = headersArray.filter((value, index2, array2) => { + if (index2 > 0 && value.name.toLowerCase() === array2[index2 - 1].name.toLowerCase()) { + return false; } - } while (buffer); + return true; + }); + let canonicalizedHeadersStringToSign = ""; + headersArray.forEach((header) => { + canonicalizedHeadersStringToSign += `${header.name.toLowerCase().trimRight()}:${header.value.trimLeft()} +`; + }); + return canonicalizedHeadersStringToSign; } - /** - * Trigger a outgoing handler for a buffer shifted from outgoing. - * - * @param buffer - - */ - async triggerOutgoingHandler(buffer) { - const bufferLength = buffer.size; - this.executingOutgoingHandlers++; - this.offset += bufferLength; - try { - await this.outgoingHandler(() => buffer.getReadableStream(), bufferLength, this.offset - bufferLength); - } catch (err) { - this.emitter.emit("error", err); - return; + function getCanonicalizedResourceString(request3) { + const path30 = (0, import_utils_common.getURLPath)(request3.url) || "/"; + let canonicalizedResourceString = ""; + canonicalizedResourceString += `/${options.accountName}${path30}`; + const queries = (0, import_utils_common.getURLQueries)(request3.url); + const lowercaseQueries = {}; + if (queries) { + const queryKeys = []; + for (const key in queries) { + if (Object.prototype.hasOwnProperty.call(queries, key)) { + const lowercaseKey = key.toLowerCase(); + lowercaseQueries[lowercaseKey] = queries[key]; + queryKeys.push(lowercaseKey); + } + } + queryKeys.sort(); + for (const key of queryKeys) { + canonicalizedResourceString += ` +${key}:${decodeURIComponent(lowercaseQueries[key])}`; + } } - this.executingOutgoingHandlers--; - this.reuseBuffer(buffer); - this.emitter.emit("checkEnd"); + return canonicalizedResourceString; } - /** - * Return buffer used by outgoing handler into incoming. - * - * @param buffer - - */ - reuseBuffer(buffer) { - this.incoming.push(buffer); - if (!this.isError && this.resolveData() && !this.isStreamEnd) { - this.readable.resume(); + return { + name: storageSharedKeyCredentialPolicyName, + async sendRequest(request3, next) { + signRequest(request3); + return next(request3); } + }; + } + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/policies/StorageRedirectRangeHeaderPolicy.js +var require_StorageRedirectRangeHeaderPolicy = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/policies/StorageRedirectRangeHeaderPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BufferScheduler = BufferScheduler; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageRedirectRangeHeaderPolicy_exports = {}; + __export2(StorageRedirectRangeHeaderPolicy_exports, { + storageRedirectRangeHeaderPolicy: () => storageRedirectRangeHeaderPolicy, + storageRedirectRangeHeaderPolicyName: () => storageRedirectRangeHeaderPolicyName + }); + module2.exports = __toCommonJS2(StorageRedirectRangeHeaderPolicy_exports); + var storageRedirectRangeHeaderPolicyName = "storageRedirectRangeHeaderPolicy"; + function storageRedirectRangeHeaderPolicy() { + return { + name: storageRedirectRangeHeaderPolicyName, + async sendRequest(request3, next) { + if (request3.headers.has("range")) { + request3.headers.set("x-ms-range", request3.headers.get("range")); + request3.headers.delete("range"); + } + return next(request3); + } + }; + } } }); -// node_modules/@azure/storage-common/dist/commonjs/cache.js -var require_cache2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/cache.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getCachedDefaultHttpClient = getCachedDefaultHttpClient; - var core_rest_pipeline_1 = require_commonjs6(); - var _defaultHttpClient; - function getCachedDefaultHttpClient() { - if (!_defaultHttpClient) { - _defaultHttpClient = (0, core_rest_pipeline_1.createDefaultHttpClient)(); +// node_modules/@azure/storage-common/dist/commonjs/policies/StorageRequestFailureDetailsParserPolicy.js +var require_StorageRequestFailureDetailsParserPolicy = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/policies/StorageRequestFailureDetailsParserPolicy.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - return _defaultHttpClient; + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageRequestFailureDetailsParserPolicy_exports = {}; + __export2(StorageRequestFailureDetailsParserPolicy_exports, { + storageRequestFailureDetailsParserPolicy: () => storageRequestFailureDetailsParserPolicy, + storageRequestFailureDetailsParserPolicyName: () => storageRequestFailureDetailsParserPolicyName + }); + module2.exports = __toCommonJS2(StorageRequestFailureDetailsParserPolicy_exports); + var storageRequestFailureDetailsParserPolicyName = "storageRequestFailureDetailsParserPolicy"; + function storageRequestFailureDetailsParserPolicy() { + return { + name: storageRequestFailureDetailsParserPolicyName, + async sendRequest(request3, next) { + try { + const response = await next(request3); + if (response.status === 400 && response.bodyAsText?.includes("InvalidHeaderValue") && response.bodyAsText.includes("x-ms-version")) { + response.bodyAsText = response.bodyAsText.replace( + /.*<\/Message>/s, + "The provided service version is not enabled on this storage account. Please see https://learn.microsoft.com/rest/api/storageservices/versioning-for-the-azure-storage-services for additional information." + ); + } + return response; + } catch (err) { + if (typeof err === "object" && err !== null && err.response && err.response.parsedBody) { + if (err.response.parsedBody.code === "InvalidHeaderValue" && err.response.parsedBody.HeaderName === "x-ms-version") { + err.message = "The provided service version is not enabled on this storage account. Please see https://learn.microsoft.com/rest/api/storageservices/versioning-for-the-azure-storage-services for additional information.\n"; + } + } + throw err; + } + } + }; } } }); -// node_modules/@azure/storage-common/dist/commonjs/policies/RequestPolicy.js -var require_RequestPolicy2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/policies/RequestPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BaseRequestPolicy = void 0; - var BaseRequestPolicy = class { - _nextPolicy; - _options; +// node_modules/@azure/storage-common/dist/commonjs/credentials/UserDelegationKeyCredential.js +var require_UserDelegationKeyCredential = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/credentials/UserDelegationKeyCredential.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var UserDelegationKeyCredential_exports = {}; + __export2(UserDelegationKeyCredential_exports, { + UserDelegationKeyCredential: () => UserDelegationKeyCredential + }); + module2.exports = __toCommonJS2(UserDelegationKeyCredential_exports); + var import_node_crypto = require("node:crypto"); + var UserDelegationKeyCredential = class { /** - * The main method to implement that manipulates a request/response. + * Azure Storage account name; readonly. */ - constructor(_nextPolicy, _options) { - this._nextPolicy = _nextPolicy; - this._options = _options; - } + accountName; /** - * Get whether or not a log with the provided log level should be logged. - * @param logLevel - The log level of the log that will be logged. - * @returns Whether or not a log with the provided log level should be logged. + * Azure Storage user delegation key; readonly. */ - shouldLog(logLevel) { - return this._options.shouldLog(logLevel); + userDelegationKey; + /** + * Key value in Buffer type. + */ + key; + /** + * Creates an instance of UserDelegationKeyCredential. + * @param accountName - + * @param userDelegationKey - + */ + constructor(accountName, userDelegationKey) { + this.accountName = accountName; + this.userDelegationKey = userDelegationKey; + this.key = Buffer.from(userDelegationKey.value, "base64"); } /** - * Attempt to log the provided message to the provided logger. If no logger was provided or if - * the log level does not meat the logger's threshold, then nothing will be logged. - * @param logLevel - The log level of this log. - * @param message - The message of this log. + * Generates a hash signature for an HTTP request or for a SAS. + * + * @param stringToSign - */ - log(logLevel, message) { - this._options.log(logLevel, message); + computeHMACSHA256(stringToSign) { + return (0, import_node_crypto.createHmac)("sha256", this.key).update(stringToSign, "utf8").digest("base64"); } }; - exports2.BaseRequestPolicy = BaseRequestPolicy; } }); -// node_modules/@azure/storage-common/dist/commonjs/utils/constants.js +// node_modules/@azure/storage-common/dist/commonjs/indexPlatform.js +var require_indexPlatform = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/indexPlatform.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var indexPlatform_exports = {}; + __export2(indexPlatform_exports, { + BaseRequestPolicy: () => import_RequestPolicy.BaseRequestPolicy, + createBlobFromData: () => import_bufferHelpers_common.createBlobFromData, + getCachedDefaultHttpClient: () => import_cache.getCachedDefaultHttpClient + }); + module2.exports = __toCommonJS2(indexPlatform_exports); + __reExport(indexPlatform_exports, require_BufferScheduler(), module2.exports); + __reExport(indexPlatform_exports, require_bufferHelpers(), module2.exports); + var import_bufferHelpers_common = require_bufferHelpers_common(); + __reExport(indexPlatform_exports, require_StructuredMessageEncodingStream(), module2.exports); + __reExport(indexPlatform_exports, require_StructuredMessageDecodingStream(), module2.exports); + __reExport(indexPlatform_exports, require_StorageCRC64Calculator(), module2.exports); + var import_cache = require_cache4(); + __reExport(indexPlatform_exports, require_StorageResponseFormat(), module2.exports); + __reExport(indexPlatform_exports, require_StorageBrowserPolicyFactory(), module2.exports); + __reExport(indexPlatform_exports, require_AnonymousCredential(), module2.exports); + __reExport(indexPlatform_exports, require_Credential(), module2.exports); + __reExport(indexPlatform_exports, require_StorageSharedKeyCredential(), module2.exports); + __reExport(indexPlatform_exports, require_StorageRetryPolicyFactory(), module2.exports); + var import_RequestPolicy = require_RequestPolicy(); + __reExport(indexPlatform_exports, require_AnonymousCredentialPolicy(), module2.exports); + __reExport(indexPlatform_exports, require_CredentialPolicy(), module2.exports); + __reExport(indexPlatform_exports, require_StorageBrowserPolicyV2(), module2.exports); + __reExport(indexPlatform_exports, require_StorageCorrectContentLengthPolicy(), module2.exports); + __reExport(indexPlatform_exports, require_StorageRetryPolicyV2(), module2.exports); + __reExport(indexPlatform_exports, require_StorageSharedKeyCredentialPolicy(), module2.exports); + __reExport(indexPlatform_exports, require_StorageSharedKeyCredentialPolicyV2(), module2.exports); + __reExport(indexPlatform_exports, require_StorageRedirectRangeHeaderPolicy(), module2.exports); + __reExport(indexPlatform_exports, require_StorageRequestFailureDetailsParserPolicy(), module2.exports); + __reExport(indexPlatform_exports, require_UserDelegationKeyCredential(), module2.exports); + } +}); + +// node_modules/@azure/storage-common/dist/commonjs/index.js +var require_commonjs12 = __commonJS({ + "node_modules/@azure/storage-common/dist/commonjs/index.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var src_exports = {}; + module2.exports = __toCommonJS2(src_exports); + __reExport(src_exports, require_indexPlatform(), module2.exports); + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/utils/constants.js var require_constants11 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/utils/constants.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PathStylePorts = exports2.DevelopmentConnectionString = exports2.HeaderConstants = exports2.URLConstants = exports2.SDK_VERSION = void 0; - exports2.SDK_VERSION = "1.0.0"; - exports2.URLConstants = { + "node_modules/@azure/storage-blob/dist/commonjs/utils/constants.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var constants_exports = {}; + __export2(constants_exports, { + ApacheArrowContentType: () => ApacheArrowContentType, + BATCH_MAX_PAYLOAD_IN_BYTES: () => BATCH_MAX_PAYLOAD_IN_BYTES, + BATCH_MAX_REQUEST: () => BATCH_MAX_REQUEST, + BLOCK_BLOB_MAX_BLOCKS: () => BLOCK_BLOB_MAX_BLOCKS, + BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES: () => BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES, + BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES: () => BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES, + BlobDoesNotUseCustomerSpecifiedEncryption: () => BlobDoesNotUseCustomerSpecifiedEncryption, + BlobUsesCustomerSpecifiedEncryptionMsg: () => BlobUsesCustomerSpecifiedEncryptionMsg, + DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES: () => DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES, + DEFAULT_BLOCK_BUFFER_SIZE_BYTES: () => DEFAULT_BLOCK_BUFFER_SIZE_BYTES, + DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS: () => DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS, + DevelopmentConnectionString: () => DevelopmentConnectionString, + ETagAny: () => ETagAny, + ETagNone: () => ETagNone, + EncryptionAlgorithmAES25: () => EncryptionAlgorithmAES25, + HTTPURLConnection: () => HTTPURLConnection, + HTTP_LINE_ENDING: () => HTTP_LINE_ENDING, + HTTP_VERSION_1_1: () => HTTP_VERSION_1_1, + HeaderConstants: () => HeaderConstants, + PathStylePorts: () => PathStylePorts, + REQUEST_TIMEOUT: () => REQUEST_TIMEOUT, + SDK_VERSION: () => SDK_VERSION, + SERVICE_VERSION: () => SERVICE_VERSION, + SIZE_1_MB: () => SIZE_1_MB, + StorageBlobLoggingAllowedHeaderNames: () => StorageBlobLoggingAllowedHeaderNames, + StorageBlobLoggingAllowedQueryParameters: () => StorageBlobLoggingAllowedQueryParameters, + StorageOAuthScopes: () => StorageOAuthScopes2, + URLConstants: () => URLConstants + }); + module2.exports = __toCommonJS2(constants_exports); + var SDK_VERSION = "12.34.0"; + var SERVICE_VERSION = "2026-10-06"; + var BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; + var BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4e3 * 1024 * 1024; + var BLOCK_BLOB_MAX_BLOCKS = 5e4; + var DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; + var DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; + var DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5; + var REQUEST_TIMEOUT = 100 * 1e3; + var StorageOAuthScopes2 = "https://storage.azure.com/.default"; + var ApacheArrowContentType = "application/vnd.apache.arrow.stream"; + var URLConstants = { Parameters: { FORCE_BROWSER_NO_CACHE: "_", SIGNATURE: "sig", @@ -48524,7 +62411,14 @@ var require_constants11 = __commonJS({ TIMEOUT: "timeout" } }; - exports2.HeaderConstants = { + var HTTPURLConnection = { + HTTP_ACCEPTED: 202, + HTTP_CONFLICT: 409, + HTTP_NOT_FOUND: 404, + HTTP_PRECON_FAILED: 412, + HTTP_RANGE_NOT_SATISFIABLE: 416 + }; + var HeaderConstants = { AUTHORIZATION: "Authorization", AUTHORIZATION_SCHEME: "Bearer", CONTENT_ENCODING: "Content-Encoding", @@ -48550,8 +62444,151 @@ var require_constants11 = __commonJS({ X_MS_VERSION: "x-ms-version", X_MS_CopySourceErrorCode: "x-ms-copy-source-error-code" }; - exports2.DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`; - exports2.PathStylePorts = [ + var ETagNone = ""; + var ETagAny = "*"; + var SIZE_1_MB = 1 * 1024 * 1024; + var BATCH_MAX_REQUEST = 256; + var BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB; + var HTTP_LINE_ENDING = "\r\n"; + var HTTP_VERSION_1_1 = "HTTP/1.1"; + var EncryptionAlgorithmAES25 = "AES256"; + var DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`; + var StorageBlobLoggingAllowedHeaderNames = [ + "Access-Control-Allow-Origin", + "Cache-Control", + "Content-Length", + "Content-Type", + "Date", + "Request-Id", + "traceparent", + "Transfer-Encoding", + "User-Agent", + "x-ms-client-request-id", + "x-ms-date", + "x-ms-error-code", + "x-ms-request-id", + "x-ms-return-client-request-id", + "x-ms-version", + "Accept-Ranges", + "Content-Disposition", + "Content-Encoding", + "Content-Language", + "Content-MD5", + "Content-Range", + "ETag", + "Last-Modified", + "Server", + "Vary", + "x-ms-content-crc64", + "x-ms-copy-action", + "x-ms-copy-completion-time", + "x-ms-copy-id", + "x-ms-copy-progress", + "x-ms-copy-status", + "x-ms-has-immutability-policy", + "x-ms-has-legal-hold", + "x-ms-lease-state", + "x-ms-lease-status", + "x-ms-range", + "x-ms-request-server-encrypted", + "x-ms-server-encrypted", + "x-ms-snapshot", + "x-ms-source-range", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "x-ms-access-tier", + "x-ms-access-tier-change-time", + "x-ms-access-tier-inferred", + "x-ms-account-kind", + "x-ms-archive-status", + "x-ms-blob-append-offset", + "x-ms-blob-cache-control", + "x-ms-blob-committed-block-count", + "x-ms-blob-condition-appendpos", + "x-ms-blob-condition-maxsize", + "x-ms-blob-content-disposition", + "x-ms-blob-content-encoding", + "x-ms-blob-content-language", + "x-ms-blob-content-length", + "x-ms-blob-content-md5", + "x-ms-blob-content-type", + "x-ms-blob-public-access", + "x-ms-blob-sequence-number", + "x-ms-blob-type", + "x-ms-copy-destination-snapshot", + "x-ms-creation-time", + "x-ms-default-encryption-scope", + "x-ms-delete-snapshots", + "x-ms-delete-type-permanent", + "x-ms-deny-encryption-scope-override", + "x-ms-encryption-algorithm", + "x-ms-if-sequence-number-eq", + "x-ms-if-sequence-number-le", + "x-ms-if-sequence-number-lt", + "x-ms-incremental-copy", + "x-ms-lease-action", + "x-ms-lease-break-period", + "x-ms-lease-duration", + "x-ms-lease-id", + "x-ms-lease-time", + "x-ms-page-write", + "x-ms-proposed-lease-id", + "x-ms-range-get-content-md5", + "x-ms-rehydrate-priority", + "x-ms-sequence-number-action", + "x-ms-sku-name", + "x-ms-source-content-md5", + "x-ms-source-if-match", + "x-ms-source-if-modified-since", + "x-ms-source-if-none-match", + "x-ms-source-if-unmodified-since", + "x-ms-tag-count", + "x-ms-encryption-key-sha256", + "x-ms-copy-source-error-code", + "x-ms-copy-source-status-code", + "x-ms-if-tags", + "x-ms-source-if-tags" + ]; + var StorageBlobLoggingAllowedQueryParameters = [ + "comp", + "maxresults", + "rscc", + "rscd", + "rsce", + "rscl", + "rsct", + "se", + "si", + "sip", + "sp", + "spr", + "sr", + "srt", + "ss", + "st", + "sv", + "include", + "marker", + "prefix", + "copyid", + "restype", + "blockid", + "blocklisttype", + "delimiter", + "prevsnapshot", + "ske", + "skoid", + "sks", + "skt", + "sktid", + "skv", + "snapshot" + ]; + var BlobUsesCustomerSpecifiedEncryptionMsg = "BlobUsesCustomerSpecifiedEncryption"; + var BlobDoesNotUseCustomerSpecifiedEncryption = "BlobDoesNotUseCustomerSpecifiedEncryption"; + var PathStylePorts = [ "10000", "10001", "10002", @@ -48576,2944 +62613,2102 @@ var require_constants11 = __commonJS({ } }); -// node_modules/@azure/storage-common/dist/commonjs/utils/utils.common.js -var require_utils_common2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/utils/utils.common.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.escapeURLPath = escapeURLPath; - exports2.getValueInConnString = getValueInConnString; - exports2.extractConnectionStringParts = extractConnectionStringParts; - exports2.appendToURLPath = appendToURLPath; - exports2.setURLParameter = setURLParameter; - exports2.getURLParameter = getURLParameter; - exports2.setURLHost = setURLHost; - exports2.getURLPath = getURLPath; - exports2.getURLScheme = getURLScheme; - exports2.getURLPathAndQuery = getURLPathAndQuery; - exports2.getURLQueries = getURLQueries; - exports2.appendToURLQuery = appendToURLQuery; - exports2.truncatedISO8061Date = truncatedISO8061Date; - exports2.base64encode = base64encode; - exports2.base64decode = base64decode; - exports2.generateBlockID = generateBlockID; - exports2.delay = delay2; - exports2.padStart = padStart2; - exports2.sanitizeURL = sanitizeURL; - exports2.sanitizeHeaders = sanitizeHeaders; - exports2.iEqual = iEqual; - exports2.getAccountNameFromUrl = getAccountNameFromUrl; - exports2.isIpEndpointStyle = isIpEndpointStyle; - exports2.attachCredential = attachCredential; - exports2.httpAuthorizationToString = httpAuthorizationToString; - exports2.EscapePath = EscapePath; - exports2.assertResponse = assertResponse; - var core_rest_pipeline_1 = require_commonjs6(); - var core_util_1 = require_commonjs4(); - var constants_js_1 = require_constants11(); - function escapeURLPath(url2) { - const urlParsed = new URL(url2); - let path30 = urlParsed.pathname; - path30 = path30 || "/"; - path30 = escape3(path30); - urlParsed.pathname = path30; - return urlParsed.toString(); - } - function getProxyUriFromDevConnString(connectionString) { - let proxyUri = ""; - if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { - const matchCredentials = connectionString.split(";"); - for (const element of matchCredentials) { - if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { - proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; - } - } +// node_modules/@azure/storage-blob/dist/commonjs/Pipeline.js +var require_Pipeline = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/Pipeline.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - return proxyUri; - } - function getValueInConnString(connectionString, argument) { - const elements = connectionString.split(";"); - for (const element of elements) { - if (element.trim().startsWith(argument)) { - return element.trim().match(argument + "=(.*)")[1]; - } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var Pipeline_exports = {}; + __export2(Pipeline_exports, { + Pipeline: () => Pipeline2, + StorageOAuthScopes: () => import_constants5.StorageOAuthScopes, + getCoreClientOptions: () => getCoreClientOptions, + getCredentialFromPipeline: () => getCredentialFromPipeline, + isPipelineLike: () => isPipelineLike2, + newPipeline: () => newPipeline2 + }); + module2.exports = __toCommonJS2(Pipeline_exports); + var import_core_http_compat = require_commonjs9(); + var import_core_rest_pipeline = require_commonjs6(); + var import_core_client = require_commonjs8(); + var import_core_xml = require_commonjs10(); + var import_core_auth = require_commonjs7(); + var import_log = require_log5(); + var import_storage_common = require_commonjs12(); + var import_constants5 = require_constants11(); + function isPipelineLike2(pipeline2) { + if (!pipeline2 || typeof pipeline2 !== "object") { + return false; } - return ""; + const castPipeline = pipeline2; + return Array.isArray(castPipeline.factories) && typeof castPipeline.options === "object" && typeof castPipeline.toServiceClientOptions === "function"; } - function extractConnectionStringParts(connectionString) { - let proxyUri = ""; - if (connectionString.startsWith("UseDevelopmentStorage=true")) { - proxyUri = getProxyUriFromDevConnString(connectionString); - connectionString = constants_js_1.DevelopmentConnectionString; + var Pipeline2 = class { + /** + * A list of chained request policy factories. + */ + factories; + /** + * Configures pipeline logger and HTTP client. + */ + options; + /** + * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface. + * + * @param factories - + * @param options - + */ + constructor(factories, options = {}) { + this.factories = factories; + this.options = options; } - let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); - blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; - if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && connectionString.search("AccountKey=") !== -1) { - let defaultEndpointsProtocol = ""; - let accountName = ""; - let accountKey = Buffer.from("accountKey", "base64"); - let endpointSuffix = ""; - accountName = getValueInConnString(connectionString, "AccountName"); - accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); - if (!blobEndpoint) { - defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); - const protocol = defaultEndpointsProtocol.toLowerCase(); - if (protocol !== "https" && protocol !== "http") { - throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'"); - } - endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix"); - if (!endpointSuffix) { - throw new Error("Invalid EndpointSuffix in the provided Connection String"); - } - blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; - } - if (!accountName) { - throw new Error("Invalid AccountName in the provided Connection String"); - } else if (accountKey.length === 0) { - throw new Error("Invalid AccountKey in the provided Connection String"); - } + /** + * Transfer Pipeline object to ServiceClientOptions object which is required by + * ServiceClient constructor. + * + * @returns The ServiceClientOptions object from this Pipeline. + */ + toServiceClientOptions() { return { - kind: "AccountConnString", - url: blobEndpoint, - accountName, - accountKey, - proxyUri + httpClient: this.options.httpClient, + requestPolicyFactories: this.factories }; - } else { - let accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); - let accountName = getValueInConnString(connectionString, "AccountName"); - if (!accountName) { - accountName = getAccountNameFromUrl(blobEndpoint); - } - if (!blobEndpoint) { - throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); - } else if (!accountSas) { - throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); - } - if (accountSas.startsWith("?")) { - accountSas = accountSas.substring(1); - } - return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas }; - } - } - function escape3(text) { - return encodeURIComponent(text).replace(/%2F/g, "/").replace(/'/g, "%27").replace(/\+/g, "%20").replace(/%25/g, "%"); - } - function appendToURLPath(url2, name) { - const urlParsed = new URL(url2); - let path30 = urlParsed.pathname; - path30 = path30 ? path30.endsWith("/") ? `${path30}${name}` : `${path30}/${name}` : name; - urlParsed.pathname = path30; - return urlParsed.toString(); - } - function setURLParameter(url2, name, value) { - const urlParsed = new URL(url2); - const encodedName = encodeURIComponent(name); - const encodedValue = value ? encodeURIComponent(value) : void 0; - const searchString = urlParsed.search === "" ? "?" : urlParsed.search; - const searchPieces = []; - for (const pair of searchString.slice(1).split("&")) { - if (pair) { - const [key] = pair.split("=", 2); - if (key !== encodedName) { - searchPieces.push(pair); - } - } - } - if (encodedValue) { - searchPieces.push(`${encodedName}=${encodedValue}`); - } - urlParsed.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; - return urlParsed.toString(); - } - function getURLParameter(url2, name) { - const urlParsed = new URL(url2); - return urlParsed.searchParams.get(name) ?? void 0; - } - function setURLHost(url2, host) { - const urlParsed = new URL(url2); - urlParsed.hostname = host; - return urlParsed.toString(); - } - function getURLPath(url2) { - try { - const urlParsed = new URL(url2); - return urlParsed.pathname; - } catch (e) { - return void 0; - } - } - function getURLScheme(url2) { - try { - const urlParsed = new URL(url2); - return urlParsed.protocol.endsWith(":") ? urlParsed.protocol.slice(0, -1) : urlParsed.protocol; - } catch (e) { - return void 0; - } - } - function getURLPathAndQuery(url2) { - const urlParsed = new URL(url2); - const pathString = urlParsed.pathname; - if (!pathString) { - throw new RangeError("Invalid url without valid path."); - } - let queryString = urlParsed.search || ""; - queryString = queryString.trim(); - if (queryString !== "") { - queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; } - return `${pathString}${queryString}`; - } - function getURLQueries(url2) { - let queryString = new URL(url2).search; - if (!queryString) { - return {}; - } - queryString = queryString.trim(); - queryString = queryString.startsWith("?") ? queryString.substring(1) : queryString; - let querySubStrings = queryString.split("&"); - querySubStrings = querySubStrings.filter((value) => { - const indexOfEqual = value.indexOf("="); - const lastIndexOfEqual = value.lastIndexOf("="); - return indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1; - }); - const queries = {}; - for (const querySubString of querySubStrings) { - const splitResults = querySubString.split("="); - const key = splitResults[0]; - const value = splitResults[1]; - queries[key] = value; + }; + function newPipeline2(credential, pipelineOptions = {}) { + if (!credential) { + credential = new import_storage_common.AnonymousCredential(); } - return queries; + const pipeline2 = new Pipeline2([], pipelineOptions); + pipeline2._credential = credential; + return pipeline2; } - function appendToURLQuery(url2, queryParts) { - const urlParsed = new URL(url2); - let query = urlParsed.search; - if (query) { - query += "&" + queryParts; - } else { - query = queryParts; + function processDownlevelPipeline(pipeline2) { + const knownFactoryFunctions = [ + isAnonymousCredential, + isStorageSharedKeyCredential, + isCoreHttpBearerTokenFactory, + isStorageBrowserPolicyFactory, + isStorageRetryPolicyFactory, + isStorageTelemetryPolicyFactory, + isCoreHttpPolicyFactory + ]; + if (pipeline2.factories.length) { + const novelFactories = pipeline2.factories.filter((factory) => { + return !knownFactoryFunctions.some((knownFactory) => knownFactory(factory)); + }); + if (novelFactories.length) { + const hasInjector = novelFactories.some((factory) => isInjectorPolicyFactory(factory)); + return { + wrappedPolicies: (0, import_core_http_compat.createRequestPolicyFactoryPolicy)(novelFactories), + afterRetry: hasInjector + }; + } } - urlParsed.search = query; - return urlParsed.toString(); - } - function truncatedISO8061Date(date, withMilliseconds = true) { - const dateString = date.toISOString(); - return withMilliseconds ? dateString.substring(0, dateString.length - 1) + "0000Z" : dateString.substring(0, dateString.length - 5) + "Z"; - } - function base64encode(content) { - return !core_util_1.isNodeLike ? btoa(content) : Buffer.from(content).toString("base64"); - } - function base64decode(encodedString) { - return !core_util_1.isNodeLike ? atob(encodedString) : Buffer.from(encodedString, "base64").toString(); + return void 0; } - function generateBlockID(blockIDPrefix, blockIndex) { - const maxSourceStringLength = 48; - const maxBlockIndexLength = 6; - const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; - if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { - blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); + function getCoreClientOptions(pipeline2) { + const { httpClient: v1Client, ...restOptions } = pipeline2.options; + let httpClient = pipeline2._coreHttpClient; + if (!httpClient) { + httpClient = v1Client ? (0, import_core_http_compat.convertHttpClient)(v1Client) : (0, import_storage_common.getCachedDefaultHttpClient)(); + pipeline2._coreHttpClient = httpClient; } - const res = blockIDPrefix + padStart2(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); - return base64encode(res); - } - async function delay2(timeInMs, aborter, abortError) { - return new Promise((resolve14, reject) => { - let timeout; - const abortHandler = () => { - if (timeout !== void 0) { - clearTimeout(timeout); - } - reject(abortError); - }; - const resolveHandler = () => { - if (aborter !== void 0) { - aborter.removeEventListener("abort", abortHandler); + let corePipeline = pipeline2._corePipeline; + if (!corePipeline) { + const packageDetails = `azsdk-js-azure-storage-blob/${import_constants5.SDK_VERSION}`; + const userAgentPrefix = restOptions.userAgentOptions && restOptions.userAgentOptions.userAgentPrefix ? `${restOptions.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`; + corePipeline = (0, import_core_client.createClientPipeline)({ + ...restOptions, + loggingOptions: { + additionalAllowedHeaderNames: import_constants5.StorageBlobLoggingAllowedHeaderNames, + additionalAllowedQueryParameters: import_constants5.StorageBlobLoggingAllowedQueryParameters, + logger: import_log.logger.info + }, + userAgentOptions: { + userAgentPrefix + }, + serializationOptions: { + stringifyXML: import_core_xml.stringifyXML, + serializerOptions: { + xml: { + // Use customized XML char key of "#" so we can deserialize metadata + // with "_" key + xmlCharKey: "#" + } + } + }, + deserializationOptions: { + parseXML: import_core_xml.parseXML, + serializerOptions: { + xml: { + // Use customized XML char key of "#" so we can deserialize metadata + // with "_" key + xmlCharKey: "#" + } + } } - resolve14(); - }; - timeout = setTimeout(resolveHandler, timeInMs); - if (aborter !== void 0) { - aborter.addEventListener("abort", abortHandler); + }); + corePipeline.removePolicy({ phase: "Retry" }); + corePipeline.removePolicy({ name: import_core_rest_pipeline.decompressResponsePolicyName }); + corePipeline.addPolicy((0, import_storage_common.storageCorrectContentLengthPolicy)()); + corePipeline.addPolicy((0, import_storage_common.storageRetryPolicy)(restOptions.retryOptions), { phase: "Retry" }); + corePipeline.addPolicy((0, import_storage_common.storageRequestFailureDetailsParserPolicy)()); + corePipeline.addPolicy((0, import_storage_common.storageBrowserPolicy)()); + const downlevelResults = processDownlevelPipeline(pipeline2); + if (downlevelResults) { + corePipeline.addPolicy( + downlevelResults.wrappedPolicies, + downlevelResults.afterRetry ? { afterPhase: "Retry" } : void 0 + ); } - }); + const credential = getCredentialFromPipeline(pipeline2); + if ((0, import_core_auth.isTokenCredential)(credential)) { + corePipeline.addPolicy( + (0, import_core_rest_pipeline.bearerTokenAuthenticationPolicy)({ + credential, + scopes: restOptions.audience ?? import_constants5.StorageOAuthScopes, + challengeCallbacks: { authorizeRequestOnChallenge: import_core_client.authorizeRequestOnTenantChallenge } + }), + { phase: "Sign" } + ); + } else if (credential instanceof import_storage_common.StorageSharedKeyCredential) { + corePipeline.addPolicy( + (0, import_storage_common.storageSharedKeyCredentialPolicy)({ + accountName: credential.accountName, + accountKey: credential.accountKey + }), + { phase: "Sign" } + ); + } + pipeline2._corePipeline = corePipeline; + } + return { + ...restOptions, + allowInsecureConnection: true, + httpClient, + pipeline: corePipeline + }; } - function padStart2(currentString, targetLength, padString = " ") { - if (String.prototype.padStart) { - return currentString.padStart(targetLength, padString); + function getCredentialFromPipeline(pipeline2) { + if (pipeline2._credential) { + return pipeline2._credential; } - padString = padString || " "; - if (currentString.length > targetLength) { - return currentString; - } else { - targetLength = targetLength - currentString.length; - if (targetLength > padString.length) { - padString += padString.repeat(targetLength / padString.length); + let credential = new import_storage_common.AnonymousCredential(); + for (const factory of pipeline2.factories) { + if ((0, import_core_auth.isTokenCredential)(factory.credential)) { + credential = factory.credential; + } else if (isStorageSharedKeyCredential(factory)) { + return factory; } - return padString.slice(0, targetLength) + currentString; } + return credential; } - function sanitizeURL(url2) { - let safeURL = url2; - if (getURLParameter(safeURL, constants_js_1.URLConstants.Parameters.SIGNATURE)) { - safeURL = setURLParameter(safeURL, constants_js_1.URLConstants.Parameters.SIGNATURE, "*****"); + function isStorageSharedKeyCredential(factory) { + if (factory instanceof import_storage_common.StorageSharedKeyCredential) { + return true; } - return safeURL; + return factory.constructor.name === "StorageSharedKeyCredential"; } - function sanitizeHeaders(originalHeader) { - const headers = (0, core_rest_pipeline_1.createHttpHeaders)(); - for (const [name, value] of originalHeader) { - if (name.toLowerCase() === constants_js_1.HeaderConstants.AUTHORIZATION.toLowerCase()) { - headers.set(name, "*****"); - } else if (name.toLowerCase() === constants_js_1.HeaderConstants.X_MS_COPY_SOURCE) { - headers.set(name, sanitizeURL(value)); - } else { - headers.set(name, value); - } + function isAnonymousCredential(factory) { + if (factory instanceof import_storage_common.AnonymousCredential) { + return true; } - return headers; + return factory.constructor.name === "AnonymousCredential"; } - function iEqual(str1, str2) { - return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); + function isCoreHttpBearerTokenFactory(factory) { + return (0, import_core_auth.isTokenCredential)(factory.credential); } - function getAccountNameFromUrl(url2) { - const parsedUrl = new URL(url2); - let accountName; - try { - if (parsedUrl.hostname.split(".")[1] === "blob") { - accountName = parsedUrl.hostname.split(".")[0]; - } else if (isIpEndpointStyle(parsedUrl)) { - accountName = parsedUrl.pathname.split("/")[1]; - } else { - accountName = ""; - } - return accountName; - } catch (error3) { - throw new Error("Unable to extract accountName with provided information."); + function isStorageBrowserPolicyFactory(factory) { + if (factory instanceof import_storage_common.StorageBrowserPolicyFactory) { + return true; } + return factory.constructor.name === "StorageBrowserPolicyFactory"; } - function isIpEndpointStyle(parsedUrl) { - const host = parsedUrl.host; - return /^.*:.*:.*$|^(localhost|host.docker.internal)(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host) || Boolean(parsedUrl.port) && constants_js_1.PathStylePorts.includes(parsedUrl.port); + function isStorageRetryPolicyFactory(factory) { + if (factory instanceof import_storage_common.StorageRetryPolicyFactory) { + return true; + } + return factory.constructor.name === "StorageRetryPolicyFactory"; } - function attachCredential(thing, credential) { - thing.credential = credential; - return thing; + function isStorageTelemetryPolicyFactory(factory) { + return factory.constructor.name === "TelemetryPolicyFactory"; } - function httpAuthorizationToString(httpAuthorization) { - return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : void 0; + function isInjectorPolicyFactory(factory) { + return factory.constructor.name === "InjectorPolicyFactory"; } - function EscapePath(blobName) { - const split = blobName.split("/"); - for (let i = 0; i < split.length; i++) { - split[i] = encodeURIComponent(split[i]); - } - return split.join("/"); + function isCoreHttpPolicyFactory(factory) { + const knownPolicies = [ + "GenerateClientRequestIdPolicy", + "TracingPolicy", + "LogPolicy", + "ProxyPolicy", + "DisableResponseDecompressionPolicy", + "KeepAlivePolicy", + "DeserializationPolicy" + ]; + const mockHttpClient = { + sendRequest: async (request3) => { + return { + request: request3, + headers: request3.headers.clone(), + status: 500 + }; + } + }; + const mockRequestPolicyOptions = { + log(_logLevel, _message) { + }, + shouldLog(_logLevel) { + return false; + } + }; + const policyInstance = factory.create(mockHttpClient, mockRequestPolicyOptions); + const policyName = policyInstance.constructor.name; + return knownPolicies.some((knownPolicyName) => { + return policyName.startsWith(knownPolicyName); + }); } - function assertResponse(response) { - if (`_response` in response) { - return response; + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/models/index.js +var require_models = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/models/index.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - throw new TypeError(`Unexpected response object ${response}`); - } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var models_exports = {}; + __export2(models_exports, { + KnownBlobExpiryOptions: () => KnownBlobExpiryOptions, + KnownEncryptionAlgorithmType: () => KnownEncryptionAlgorithmType, + KnownFileShareTokenIntent: () => KnownFileShareTokenIntent, + KnownStorageErrorCode: () => KnownStorageErrorCode + }); + module2.exports = __toCommonJS2(models_exports); + var KnownEncryptionAlgorithmType = /* @__PURE__ */ ((KnownEncryptionAlgorithmType2) => { + KnownEncryptionAlgorithmType2["AES256"] = "AES256"; + return KnownEncryptionAlgorithmType2; + })(KnownEncryptionAlgorithmType || {}); + var KnownFileShareTokenIntent = /* @__PURE__ */ ((KnownFileShareTokenIntent2) => { + KnownFileShareTokenIntent2["Backup"] = "backup"; + return KnownFileShareTokenIntent2; + })(KnownFileShareTokenIntent || {}); + var KnownBlobExpiryOptions = /* @__PURE__ */ ((KnownBlobExpiryOptions2) => { + KnownBlobExpiryOptions2["NeverExpire"] = "NeverExpire"; + KnownBlobExpiryOptions2["RelativeToCreation"] = "RelativeToCreation"; + KnownBlobExpiryOptions2["RelativeToNow"] = "RelativeToNow"; + KnownBlobExpiryOptions2["Absolute"] = "Absolute"; + return KnownBlobExpiryOptions2; + })(KnownBlobExpiryOptions || {}); + var KnownStorageErrorCode = /* @__PURE__ */ ((KnownStorageErrorCode2) => { + KnownStorageErrorCode2["AccountAlreadyExists"] = "AccountAlreadyExists"; + KnownStorageErrorCode2["AccountBeingCreated"] = "AccountBeingCreated"; + KnownStorageErrorCode2["AccountIsDisabled"] = "AccountIsDisabled"; + KnownStorageErrorCode2["AuthenticationFailed"] = "AuthenticationFailed"; + KnownStorageErrorCode2["AuthorizationFailure"] = "AuthorizationFailure"; + KnownStorageErrorCode2["ConditionHeadersNotSupported"] = "ConditionHeadersNotSupported"; + KnownStorageErrorCode2["ConditionNotMet"] = "ConditionNotMet"; + KnownStorageErrorCode2["EmptyMetadataKey"] = "EmptyMetadataKey"; + KnownStorageErrorCode2["InsufficientAccountPermissions"] = "InsufficientAccountPermissions"; + KnownStorageErrorCode2["InternalError"] = "InternalError"; + KnownStorageErrorCode2["InvalidAuthenticationInfo"] = "InvalidAuthenticationInfo"; + KnownStorageErrorCode2["InvalidHeaderValue"] = "InvalidHeaderValue"; + KnownStorageErrorCode2["InvalidHttpVerb"] = "InvalidHttpVerb"; + KnownStorageErrorCode2["InvalidInput"] = "InvalidInput"; + KnownStorageErrorCode2["InvalidMd5"] = "InvalidMd5"; + KnownStorageErrorCode2["InvalidMetadata"] = "InvalidMetadata"; + KnownStorageErrorCode2["InvalidQueryParameterValue"] = "InvalidQueryParameterValue"; + KnownStorageErrorCode2["InvalidRange"] = "InvalidRange"; + KnownStorageErrorCode2["InvalidResourceName"] = "InvalidResourceName"; + KnownStorageErrorCode2["InvalidUri"] = "InvalidUri"; + KnownStorageErrorCode2["InvalidXmlDocument"] = "InvalidXmlDocument"; + KnownStorageErrorCode2["InvalidXmlNodeValue"] = "InvalidXmlNodeValue"; + KnownStorageErrorCode2["Md5Mismatch"] = "Md5Mismatch"; + KnownStorageErrorCode2["MetadataTooLarge"] = "MetadataTooLarge"; + KnownStorageErrorCode2["MissingContentLengthHeader"] = "MissingContentLengthHeader"; + KnownStorageErrorCode2["MissingRequiredQueryParameter"] = "MissingRequiredQueryParameter"; + KnownStorageErrorCode2["MissingRequiredHeader"] = "MissingRequiredHeader"; + KnownStorageErrorCode2["MissingRequiredXmlNode"] = "MissingRequiredXmlNode"; + KnownStorageErrorCode2["MultipleConditionHeadersNotSupported"] = "MultipleConditionHeadersNotSupported"; + KnownStorageErrorCode2["OperationTimedOut"] = "OperationTimedOut"; + KnownStorageErrorCode2["OutOfRangeInput"] = "OutOfRangeInput"; + KnownStorageErrorCode2["OutOfRangeQueryParameterValue"] = "OutOfRangeQueryParameterValue"; + KnownStorageErrorCode2["RequestBodyTooLarge"] = "RequestBodyTooLarge"; + KnownStorageErrorCode2["ResourceTypeMismatch"] = "ResourceTypeMismatch"; + KnownStorageErrorCode2["RequestUrlFailedToParse"] = "RequestUrlFailedToParse"; + KnownStorageErrorCode2["ResourceAlreadyExists"] = "ResourceAlreadyExists"; + KnownStorageErrorCode2["ResourceNotFound"] = "ResourceNotFound"; + KnownStorageErrorCode2["ServerBusy"] = "ServerBusy"; + KnownStorageErrorCode2["UnsupportedHeader"] = "UnsupportedHeader"; + KnownStorageErrorCode2["UnsupportedXmlNode"] = "UnsupportedXmlNode"; + KnownStorageErrorCode2["UnsupportedQueryParameter"] = "UnsupportedQueryParameter"; + KnownStorageErrorCode2["UnsupportedHttpVerb"] = "UnsupportedHttpVerb"; + KnownStorageErrorCode2["AppendPositionConditionNotMet"] = "AppendPositionConditionNotMet"; + KnownStorageErrorCode2["BlobAlreadyExists"] = "BlobAlreadyExists"; + KnownStorageErrorCode2["BlobImmutableDueToPolicy"] = "BlobImmutableDueToPolicy"; + KnownStorageErrorCode2["BlobNotFound"] = "BlobNotFound"; + KnownStorageErrorCode2["BlobOverwritten"] = "BlobOverwritten"; + KnownStorageErrorCode2["BlobTierInadequateForContentLength"] = "BlobTierInadequateForContentLength"; + KnownStorageErrorCode2["BlobUsesCustomerSpecifiedEncryption"] = "BlobUsesCustomerSpecifiedEncryption"; + KnownStorageErrorCode2["BlockCountExceedsLimit"] = "BlockCountExceedsLimit"; + KnownStorageErrorCode2["BlockListTooLong"] = "BlockListTooLong"; + KnownStorageErrorCode2["CannotChangeToLowerTier"] = "CannotChangeToLowerTier"; + KnownStorageErrorCode2["CannotVerifyCopySource"] = "CannotVerifyCopySource"; + KnownStorageErrorCode2["ContainerAlreadyExists"] = "ContainerAlreadyExists"; + KnownStorageErrorCode2["ContainerBeingDeleted"] = "ContainerBeingDeleted"; + KnownStorageErrorCode2["ContainerDisabled"] = "ContainerDisabled"; + KnownStorageErrorCode2["ContainerNotFound"] = "ContainerNotFound"; + KnownStorageErrorCode2["ContentLengthLargerThanTierLimit"] = "ContentLengthLargerThanTierLimit"; + KnownStorageErrorCode2["CopyAcrossAccountsNotSupported"] = "CopyAcrossAccountsNotSupported"; + KnownStorageErrorCode2["CopyIdMismatch"] = "CopyIdMismatch"; + KnownStorageErrorCode2["FeatureVersionMismatch"] = "FeatureVersionMismatch"; + KnownStorageErrorCode2["IncrementalCopyBlobMismatch"] = "IncrementalCopyBlobMismatch"; + KnownStorageErrorCode2["IncrementalCopyOfEarlierSnapshotNotAllowed"] = "IncrementalCopyOfEarlierSnapshotNotAllowed"; + KnownStorageErrorCode2["IncrementalCopySourceMustBeSnapshot"] = "IncrementalCopySourceMustBeSnapshot"; + KnownStorageErrorCode2["InfiniteLeaseDurationRequired"] = "InfiniteLeaseDurationRequired"; + KnownStorageErrorCode2["InvalidBlobOrBlock"] = "InvalidBlobOrBlock"; + KnownStorageErrorCode2["InvalidBlobTier"] = "InvalidBlobTier"; + KnownStorageErrorCode2["InvalidBlobType"] = "InvalidBlobType"; + KnownStorageErrorCode2["InvalidBlockId"] = "InvalidBlockId"; + KnownStorageErrorCode2["InvalidBlockList"] = "InvalidBlockList"; + KnownStorageErrorCode2["InvalidOperation"] = "InvalidOperation"; + KnownStorageErrorCode2["InvalidPageRange"] = "InvalidPageRange"; + KnownStorageErrorCode2["InvalidSourceBlobType"] = "InvalidSourceBlobType"; + KnownStorageErrorCode2["InvalidSourceBlobUrl"] = "InvalidSourceBlobUrl"; + KnownStorageErrorCode2["InvalidVersionForPageBlobOperation"] = "InvalidVersionForPageBlobOperation"; + KnownStorageErrorCode2["LeaseAlreadyPresent"] = "LeaseAlreadyPresent"; + KnownStorageErrorCode2["LeaseAlreadyBroken"] = "LeaseAlreadyBroken"; + KnownStorageErrorCode2["LeaseIdMismatchWithBlobOperation"] = "LeaseIdMismatchWithBlobOperation"; + KnownStorageErrorCode2["LeaseIdMismatchWithContainerOperation"] = "LeaseIdMismatchWithContainerOperation"; + KnownStorageErrorCode2["LeaseIdMismatchWithLeaseOperation"] = "LeaseIdMismatchWithLeaseOperation"; + KnownStorageErrorCode2["LeaseIdMissing"] = "LeaseIdMissing"; + KnownStorageErrorCode2["LeaseIsBreakingAndCannotBeAcquired"] = "LeaseIsBreakingAndCannotBeAcquired"; + KnownStorageErrorCode2["LeaseIsBreakingAndCannotBeChanged"] = "LeaseIsBreakingAndCannotBeChanged"; + KnownStorageErrorCode2["LeaseIsBrokenAndCannotBeRenewed"] = "LeaseIsBrokenAndCannotBeRenewed"; + KnownStorageErrorCode2["LeaseLost"] = "LeaseLost"; + KnownStorageErrorCode2["LeaseNotPresentWithBlobOperation"] = "LeaseNotPresentWithBlobOperation"; + KnownStorageErrorCode2["LeaseNotPresentWithContainerOperation"] = "LeaseNotPresentWithContainerOperation"; + KnownStorageErrorCode2["LeaseNotPresentWithLeaseOperation"] = "LeaseNotPresentWithLeaseOperation"; + KnownStorageErrorCode2["MaxBlobSizeConditionNotMet"] = "MaxBlobSizeConditionNotMet"; + KnownStorageErrorCode2["NoAuthenticationInformation"] = "NoAuthenticationInformation"; + KnownStorageErrorCode2["NoPendingCopyOperation"] = "NoPendingCopyOperation"; + KnownStorageErrorCode2["OperationNotAllowedOnIncrementalCopyBlob"] = "OperationNotAllowedOnIncrementalCopyBlob"; + KnownStorageErrorCode2["PendingCopyOperation"] = "PendingCopyOperation"; + KnownStorageErrorCode2["PreviousSnapshotCannotBeNewer"] = "PreviousSnapshotCannotBeNewer"; + KnownStorageErrorCode2["PreviousSnapshotNotFound"] = "PreviousSnapshotNotFound"; + KnownStorageErrorCode2["PreviousSnapshotOperationNotSupported"] = "PreviousSnapshotOperationNotSupported"; + KnownStorageErrorCode2["SequenceNumberConditionNotMet"] = "SequenceNumberConditionNotMet"; + KnownStorageErrorCode2["SequenceNumberIncrementTooLarge"] = "SequenceNumberIncrementTooLarge"; + KnownStorageErrorCode2["SnapshotCountExceeded"] = "SnapshotCountExceeded"; + KnownStorageErrorCode2["SnapshotOperationRateExceeded"] = "SnapshotOperationRateExceeded"; + KnownStorageErrorCode2["SnapshotsPresent"] = "SnapshotsPresent"; + KnownStorageErrorCode2["SourceConditionNotMet"] = "SourceConditionNotMet"; + KnownStorageErrorCode2["SystemInUse"] = "SystemInUse"; + KnownStorageErrorCode2["TargetConditionNotMet"] = "TargetConditionNotMet"; + KnownStorageErrorCode2["UnauthorizedBlobOverwrite"] = "UnauthorizedBlobOverwrite"; + KnownStorageErrorCode2["BlobBeingRehydrated"] = "BlobBeingRehydrated"; + KnownStorageErrorCode2["BlobArchived"] = "BlobArchived"; + KnownStorageErrorCode2["BlobNotArchived"] = "BlobNotArchived"; + KnownStorageErrorCode2["AuthorizationSourceIPMismatch"] = "AuthorizationSourceIPMismatch"; + KnownStorageErrorCode2["AuthorizationProtocolMismatch"] = "AuthorizationProtocolMismatch"; + KnownStorageErrorCode2["AuthorizationPermissionMismatch"] = "AuthorizationPermissionMismatch"; + KnownStorageErrorCode2["AuthorizationServiceMismatch"] = "AuthorizationServiceMismatch"; + KnownStorageErrorCode2["AuthorizationResourceTypeMismatch"] = "AuthorizationResourceTypeMismatch"; + KnownStorageErrorCode2["BlobAccessTierNotSupportedForAccountType"] = "BlobAccessTierNotSupportedForAccountType"; + return KnownStorageErrorCode2; + })(KnownStorageErrorCode || {}); } }); -// node_modules/@azure/storage-common/dist/commonjs/policies/StorageBrowserPolicy.js -var require_StorageBrowserPolicy = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/policies/StorageBrowserPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageBrowserPolicy = void 0; - var RequestPolicy_js_1 = require_RequestPolicy2(); - var core_util_1 = require_commonjs4(); - var constants_js_1 = require_constants11(); - var utils_common_js_1 = require_utils_common2(); - var StorageBrowserPolicy = class extends RequestPolicy_js_1.BaseRequestPolicy { - /** - * Creates an instance of StorageBrowserPolicy. - * @param nextPolicy - - * @param options - - */ - // The base class has a protected constructor. Adding a public one to enable constructing of this class. - /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ - constructor(nextPolicy, options) { - super(nextPolicy, options); +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/models/mappers.js +var require_mappers = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/models/mappers.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } - /** - * Sends out request. - * - * @param request - - */ - async sendRequest(request3) { - if (core_util_1.isNodeLike) { - return this._nextPolicy.sendRequest(request3); + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var mappers_exports = {}; + __export2(mappers_exports, { + AccessPolicy: () => AccessPolicy, + AppendBlobAppendBlockExceptionHeaders: () => AppendBlobAppendBlockExceptionHeaders, + AppendBlobAppendBlockFromUrlExceptionHeaders: () => AppendBlobAppendBlockFromUrlExceptionHeaders, + AppendBlobAppendBlockFromUrlHeaders: () => AppendBlobAppendBlockFromUrlHeaders, + AppendBlobAppendBlockHeaders: () => AppendBlobAppendBlockHeaders, + AppendBlobCreateExceptionHeaders: () => AppendBlobCreateExceptionHeaders, + AppendBlobCreateHeaders: () => AppendBlobCreateHeaders, + AppendBlobSealExceptionHeaders: () => AppendBlobSealExceptionHeaders, + AppendBlobSealHeaders: () => AppendBlobSealHeaders, + ArrowConfiguration: () => ArrowConfiguration, + ArrowField: () => ArrowField, + BlobAbortCopyFromURLExceptionHeaders: () => BlobAbortCopyFromURLExceptionHeaders, + BlobAbortCopyFromURLHeaders: () => BlobAbortCopyFromURLHeaders, + BlobAcquireLeaseExceptionHeaders: () => BlobAcquireLeaseExceptionHeaders, + BlobAcquireLeaseHeaders: () => BlobAcquireLeaseHeaders, + BlobBreakLeaseExceptionHeaders: () => BlobBreakLeaseExceptionHeaders, + BlobBreakLeaseHeaders: () => BlobBreakLeaseHeaders, + BlobChangeLeaseExceptionHeaders: () => BlobChangeLeaseExceptionHeaders, + BlobChangeLeaseHeaders: () => BlobChangeLeaseHeaders, + BlobCopyFromURLExceptionHeaders: () => BlobCopyFromURLExceptionHeaders, + BlobCopyFromURLHeaders: () => BlobCopyFromURLHeaders, + BlobCreateSnapshotExceptionHeaders: () => BlobCreateSnapshotExceptionHeaders, + BlobCreateSnapshotHeaders: () => BlobCreateSnapshotHeaders, + BlobDeleteExceptionHeaders: () => BlobDeleteExceptionHeaders, + BlobDeleteHeaders: () => BlobDeleteHeaders, + BlobDeleteImmutabilityPolicyExceptionHeaders: () => BlobDeleteImmutabilityPolicyExceptionHeaders, + BlobDeleteImmutabilityPolicyHeaders: () => BlobDeleteImmutabilityPolicyHeaders, + BlobDownloadExceptionHeaders: () => BlobDownloadExceptionHeaders, + BlobDownloadHeaders: () => BlobDownloadHeaders, + BlobFlatListSegment: () => BlobFlatListSegment, + BlobGetAccountInfoExceptionHeaders: () => BlobGetAccountInfoExceptionHeaders, + BlobGetAccountInfoHeaders: () => BlobGetAccountInfoHeaders, + BlobGetPropertiesExceptionHeaders: () => BlobGetPropertiesExceptionHeaders, + BlobGetPropertiesHeaders: () => BlobGetPropertiesHeaders, + BlobGetTagsExceptionHeaders: () => BlobGetTagsExceptionHeaders, + BlobGetTagsHeaders: () => BlobGetTagsHeaders, + BlobHierarchyListSegment: () => BlobHierarchyListSegment, + BlobItemInternal: () => BlobItemInternal, + BlobName: () => BlobName, + BlobPrefix: () => BlobPrefix, + BlobPropertiesInternal: () => BlobPropertiesInternal, + BlobQueryExceptionHeaders: () => BlobQueryExceptionHeaders, + BlobQueryHeaders: () => BlobQueryHeaders, + BlobReleaseLeaseExceptionHeaders: () => BlobReleaseLeaseExceptionHeaders, + BlobReleaseLeaseHeaders: () => BlobReleaseLeaseHeaders, + BlobRenewLeaseExceptionHeaders: () => BlobRenewLeaseExceptionHeaders, + BlobRenewLeaseHeaders: () => BlobRenewLeaseHeaders, + BlobServiceProperties: () => BlobServiceProperties, + BlobServiceStatistics: () => BlobServiceStatistics, + BlobSetExpiryExceptionHeaders: () => BlobSetExpiryExceptionHeaders, + BlobSetExpiryHeaders: () => BlobSetExpiryHeaders, + BlobSetHttpHeadersExceptionHeaders: () => BlobSetHttpHeadersExceptionHeaders, + BlobSetHttpHeadersHeaders: () => BlobSetHttpHeadersHeaders, + BlobSetImmutabilityPolicyExceptionHeaders: () => BlobSetImmutabilityPolicyExceptionHeaders, + BlobSetImmutabilityPolicyHeaders: () => BlobSetImmutabilityPolicyHeaders, + BlobSetLegalHoldExceptionHeaders: () => BlobSetLegalHoldExceptionHeaders, + BlobSetLegalHoldHeaders: () => BlobSetLegalHoldHeaders, + BlobSetMetadataExceptionHeaders: () => BlobSetMetadataExceptionHeaders, + BlobSetMetadataHeaders: () => BlobSetMetadataHeaders, + BlobSetTagsExceptionHeaders: () => BlobSetTagsExceptionHeaders, + BlobSetTagsHeaders: () => BlobSetTagsHeaders, + BlobSetTierExceptionHeaders: () => BlobSetTierExceptionHeaders, + BlobSetTierHeaders: () => BlobSetTierHeaders, + BlobStartCopyFromURLExceptionHeaders: () => BlobStartCopyFromURLExceptionHeaders, + BlobStartCopyFromURLHeaders: () => BlobStartCopyFromURLHeaders, + BlobTag: () => BlobTag, + BlobTags: () => BlobTags, + BlobUndeleteExceptionHeaders: () => BlobUndeleteExceptionHeaders, + BlobUndeleteHeaders: () => BlobUndeleteHeaders, + Block: () => Block2, + BlockBlobCommitBlockListExceptionHeaders: () => BlockBlobCommitBlockListExceptionHeaders, + BlockBlobCommitBlockListHeaders: () => BlockBlobCommitBlockListHeaders, + BlockBlobGetBlockListExceptionHeaders: () => BlockBlobGetBlockListExceptionHeaders, + BlockBlobGetBlockListHeaders: () => BlockBlobGetBlockListHeaders, + BlockBlobPutBlobFromUrlExceptionHeaders: () => BlockBlobPutBlobFromUrlExceptionHeaders, + BlockBlobPutBlobFromUrlHeaders: () => BlockBlobPutBlobFromUrlHeaders, + BlockBlobStageBlockExceptionHeaders: () => BlockBlobStageBlockExceptionHeaders, + BlockBlobStageBlockFromURLExceptionHeaders: () => BlockBlobStageBlockFromURLExceptionHeaders, + BlockBlobStageBlockFromURLHeaders: () => BlockBlobStageBlockFromURLHeaders, + BlockBlobStageBlockHeaders: () => BlockBlobStageBlockHeaders, + BlockBlobUploadExceptionHeaders: () => BlockBlobUploadExceptionHeaders, + BlockBlobUploadHeaders: () => BlockBlobUploadHeaders, + BlockList: () => BlockList, + BlockLookupList: () => BlockLookupList, + ClearRange: () => ClearRange, + ContainerAcquireLeaseExceptionHeaders: () => ContainerAcquireLeaseExceptionHeaders, + ContainerAcquireLeaseHeaders: () => ContainerAcquireLeaseHeaders, + ContainerBreakLeaseExceptionHeaders: () => ContainerBreakLeaseExceptionHeaders, + ContainerBreakLeaseHeaders: () => ContainerBreakLeaseHeaders, + ContainerChangeLeaseExceptionHeaders: () => ContainerChangeLeaseExceptionHeaders, + ContainerChangeLeaseHeaders: () => ContainerChangeLeaseHeaders, + ContainerCreateExceptionHeaders: () => ContainerCreateExceptionHeaders, + ContainerCreateHeaders: () => ContainerCreateHeaders, + ContainerDeleteExceptionHeaders: () => ContainerDeleteExceptionHeaders, + ContainerDeleteHeaders: () => ContainerDeleteHeaders, + ContainerFilterBlobsExceptionHeaders: () => ContainerFilterBlobsExceptionHeaders, + ContainerFilterBlobsHeaders: () => ContainerFilterBlobsHeaders, + ContainerGetAccessPolicyExceptionHeaders: () => ContainerGetAccessPolicyExceptionHeaders, + ContainerGetAccessPolicyHeaders: () => ContainerGetAccessPolicyHeaders, + ContainerGetAccountInfoExceptionHeaders: () => ContainerGetAccountInfoExceptionHeaders, + ContainerGetAccountInfoHeaders: () => ContainerGetAccountInfoHeaders, + ContainerGetPropertiesExceptionHeaders: () => ContainerGetPropertiesExceptionHeaders, + ContainerGetPropertiesHeaders: () => ContainerGetPropertiesHeaders, + ContainerItem: () => ContainerItem, + ContainerListBlobFlatSegmentApacheArrowExceptionHeaders: () => ContainerListBlobFlatSegmentApacheArrowExceptionHeaders, + ContainerListBlobFlatSegmentApacheArrowHeaders: () => ContainerListBlobFlatSegmentApacheArrowHeaders, + ContainerListBlobFlatSegmentExceptionHeaders: () => ContainerListBlobFlatSegmentExceptionHeaders, + ContainerListBlobFlatSegmentHeaders: () => ContainerListBlobFlatSegmentHeaders, + ContainerListBlobHierarchySegmentApacheArrowExceptionHeaders: () => ContainerListBlobHierarchySegmentApacheArrowExceptionHeaders, + ContainerListBlobHierarchySegmentApacheArrowHeaders: () => ContainerListBlobHierarchySegmentApacheArrowHeaders, + ContainerListBlobHierarchySegmentExceptionHeaders: () => ContainerListBlobHierarchySegmentExceptionHeaders, + ContainerListBlobHierarchySegmentHeaders: () => ContainerListBlobHierarchySegmentHeaders, + ContainerProperties: () => ContainerProperties, + ContainerReleaseLeaseExceptionHeaders: () => ContainerReleaseLeaseExceptionHeaders, + ContainerReleaseLeaseHeaders: () => ContainerReleaseLeaseHeaders, + ContainerRenameExceptionHeaders: () => ContainerRenameExceptionHeaders, + ContainerRenameHeaders: () => ContainerRenameHeaders, + ContainerRenewLeaseExceptionHeaders: () => ContainerRenewLeaseExceptionHeaders, + ContainerRenewLeaseHeaders: () => ContainerRenewLeaseHeaders, + ContainerRestoreExceptionHeaders: () => ContainerRestoreExceptionHeaders, + ContainerRestoreHeaders: () => ContainerRestoreHeaders, + ContainerSetAccessPolicyExceptionHeaders: () => ContainerSetAccessPolicyExceptionHeaders, + ContainerSetAccessPolicyHeaders: () => ContainerSetAccessPolicyHeaders, + ContainerSetMetadataExceptionHeaders: () => ContainerSetMetadataExceptionHeaders, + ContainerSetMetadataHeaders: () => ContainerSetMetadataHeaders, + ContainerSubmitBatchExceptionHeaders: () => ContainerSubmitBatchExceptionHeaders, + ContainerSubmitBatchHeaders: () => ContainerSubmitBatchHeaders, + CorsRule: () => CorsRule, + DelimitedTextConfiguration: () => DelimitedTextConfiguration, + FilterBlobItem: () => FilterBlobItem, + FilterBlobSegment: () => FilterBlobSegment, + GeoReplication: () => GeoReplication, + JsonTextConfiguration: () => JsonTextConfiguration, + KeyInfo: () => KeyInfo, + ListBlobsFlatSegmentResponse: () => ListBlobsFlatSegmentResponse, + ListBlobsHierarchySegmentResponse: () => ListBlobsHierarchySegmentResponse, + ListContainersSegmentResponse: () => ListContainersSegmentResponse, + Logging: () => Logging, + Metrics: () => Metrics, + PageBlobClearPagesExceptionHeaders: () => PageBlobClearPagesExceptionHeaders, + PageBlobClearPagesHeaders: () => PageBlobClearPagesHeaders, + PageBlobCopyIncrementalExceptionHeaders: () => PageBlobCopyIncrementalExceptionHeaders, + PageBlobCopyIncrementalHeaders: () => PageBlobCopyIncrementalHeaders, + PageBlobCreateExceptionHeaders: () => PageBlobCreateExceptionHeaders, + PageBlobCreateHeaders: () => PageBlobCreateHeaders, + PageBlobGetPageRangesDiffExceptionHeaders: () => PageBlobGetPageRangesDiffExceptionHeaders, + PageBlobGetPageRangesDiffHeaders: () => PageBlobGetPageRangesDiffHeaders, + PageBlobGetPageRangesExceptionHeaders: () => PageBlobGetPageRangesExceptionHeaders, + PageBlobGetPageRangesHeaders: () => PageBlobGetPageRangesHeaders, + PageBlobResizeExceptionHeaders: () => PageBlobResizeExceptionHeaders, + PageBlobResizeHeaders: () => PageBlobResizeHeaders, + PageBlobUpdateSequenceNumberExceptionHeaders: () => PageBlobUpdateSequenceNumberExceptionHeaders, + PageBlobUpdateSequenceNumberHeaders: () => PageBlobUpdateSequenceNumberHeaders, + PageBlobUploadPagesExceptionHeaders: () => PageBlobUploadPagesExceptionHeaders, + PageBlobUploadPagesFromURLExceptionHeaders: () => PageBlobUploadPagesFromURLExceptionHeaders, + PageBlobUploadPagesFromURLHeaders: () => PageBlobUploadPagesFromURLHeaders, + PageBlobUploadPagesHeaders: () => PageBlobUploadPagesHeaders, + PageList: () => PageList, + PageRange: () => PageRange, + QueryFormat: () => QueryFormat, + QueryRequest: () => QueryRequest, + QuerySerialization: () => QuerySerialization, + RetentionPolicy: () => RetentionPolicy, + ServiceFilterBlobsExceptionHeaders: () => ServiceFilterBlobsExceptionHeaders, + ServiceFilterBlobsHeaders: () => ServiceFilterBlobsHeaders, + ServiceGetAccountInfoExceptionHeaders: () => ServiceGetAccountInfoExceptionHeaders, + ServiceGetAccountInfoHeaders: () => ServiceGetAccountInfoHeaders, + ServiceGetPropertiesExceptionHeaders: () => ServiceGetPropertiesExceptionHeaders, + ServiceGetPropertiesHeaders: () => ServiceGetPropertiesHeaders, + ServiceGetStatisticsExceptionHeaders: () => ServiceGetStatisticsExceptionHeaders, + ServiceGetStatisticsHeaders: () => ServiceGetStatisticsHeaders, + ServiceGetUserDelegationKeyExceptionHeaders: () => ServiceGetUserDelegationKeyExceptionHeaders, + ServiceGetUserDelegationKeyHeaders: () => ServiceGetUserDelegationKeyHeaders, + ServiceListContainersSegmentExceptionHeaders: () => ServiceListContainersSegmentExceptionHeaders, + ServiceListContainersSegmentHeaders: () => ServiceListContainersSegmentHeaders, + ServiceSetPropertiesExceptionHeaders: () => ServiceSetPropertiesExceptionHeaders, + ServiceSetPropertiesHeaders: () => ServiceSetPropertiesHeaders, + ServiceSubmitBatchExceptionHeaders: () => ServiceSubmitBatchExceptionHeaders, + ServiceSubmitBatchHeaders: () => ServiceSubmitBatchHeaders, + SignedIdentifier: () => SignedIdentifier, + StaticWebsite: () => StaticWebsite, + StorageError: () => StorageError, + UserDelegationKey: () => UserDelegationKey + }); + module2.exports = __toCommonJS2(mappers_exports); + var BlobServiceProperties = { + serializedName: "BlobServiceProperties", + xmlName: "StorageServiceProperties", + type: { + name: "Composite", + className: "BlobServiceProperties", + modelProperties: { + blobAnalyticsLogging: { + serializedName: "Logging", + xmlName: "Logging", + type: { + name: "Composite", + className: "Logging" + } + }, + hourMetrics: { + serializedName: "HourMetrics", + xmlName: "HourMetrics", + type: { + name: "Composite", + className: "Metrics" + } + }, + minuteMetrics: { + serializedName: "MinuteMetrics", + xmlName: "MinuteMetrics", + type: { + name: "Composite", + className: "Metrics" + } + }, + cors: { + serializedName: "Cors", + xmlName: "Cors", + xmlIsWrapped: true, + xmlElementName: "CorsRule", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "CorsRule" + } + } + } + }, + defaultServiceVersion: { + serializedName: "DefaultServiceVersion", + xmlName: "DefaultServiceVersion", + type: { + name: "String" + } + }, + deleteRetentionPolicy: { + serializedName: "DeleteRetentionPolicy", + xmlName: "DeleteRetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + }, + staticWebsite: { + serializedName: "StaticWebsite", + xmlName: "StaticWebsite", + type: { + name: "Composite", + className: "StaticWebsite" + } + } } - if (request3.method.toUpperCase() === "GET" || request3.method.toUpperCase() === "HEAD") { - request3.url = (0, utils_common_js_1.setURLParameter)(request3.url, constants_js_1.URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, (/* @__PURE__ */ new Date()).getTime().toString()); + } + }; + var Logging = { + serializedName: "Logging", + type: { + name: "Composite", + className: "Logging", + modelProperties: { + version: { + serializedName: "Version", + required: true, + xmlName: "Version", + type: { + name: "String" + } + }, + deleteProperty: { + serializedName: "Delete", + required: true, + xmlName: "Delete", + type: { + name: "Boolean" + } + }, + read: { + serializedName: "Read", + required: true, + xmlName: "Read", + type: { + name: "Boolean" + } + }, + write: { + serializedName: "Write", + required: true, + xmlName: "Write", + type: { + name: "Boolean" + } + }, + retentionPolicy: { + serializedName: "RetentionPolicy", + xmlName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + } } - request3.headers.remove(constants_js_1.HeaderConstants.COOKIE); - request3.headers.remove(constants_js_1.HeaderConstants.CONTENT_LENGTH); - return this._nextPolicy.sendRequest(request3); } }; - exports2.StorageBrowserPolicy = StorageBrowserPolicy; - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/StorageBrowserPolicyFactory.js -var require_StorageBrowserPolicyFactory = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/StorageBrowserPolicyFactory.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageBrowserPolicyFactory = exports2.StorageBrowserPolicy = void 0; - var StorageBrowserPolicy_js_1 = require_StorageBrowserPolicy(); - Object.defineProperty(exports2, "StorageBrowserPolicy", { enumerable: true, get: function() { - return StorageBrowserPolicy_js_1.StorageBrowserPolicy; - } }); - var StorageBrowserPolicyFactory = class { - /** - * Creates a StorageBrowserPolicyFactory object. - * - * @param nextPolicy - - * @param options - - */ - create(nextPolicy, options) { - return new StorageBrowserPolicy_js_1.StorageBrowserPolicy(nextPolicy, options); + var RetentionPolicy = { + serializedName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy", + modelProperties: { + enabled: { + serializedName: "Enabled", + required: true, + xmlName: "Enabled", + type: { + name: "Boolean" + } + }, + days: { + constraints: { + InclusiveMinimum: 1 + }, + serializedName: "Days", + xmlName: "Days", + type: { + name: "Number" + } + } + } } }; - exports2.StorageBrowserPolicyFactory = StorageBrowserPolicyFactory; - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/policies/CredentialPolicy.js -var require_CredentialPolicy2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/policies/CredentialPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CredentialPolicy = void 0; - var RequestPolicy_js_1 = require_RequestPolicy2(); - var CredentialPolicy = class extends RequestPolicy_js_1.BaseRequestPolicy { - /** - * Sends out request. - * - * @param request - - */ - sendRequest(request3) { - return this._nextPolicy.sendRequest(this.signRequest(request3)); + var Metrics = { + serializedName: "Metrics", + type: { + name: "Composite", + className: "Metrics", + modelProperties: { + version: { + serializedName: "Version", + xmlName: "Version", + type: { + name: "String" + } + }, + enabled: { + serializedName: "Enabled", + required: true, + xmlName: "Enabled", + type: { + name: "Boolean" + } + }, + includeAPIs: { + serializedName: "IncludeAPIs", + xmlName: "IncludeAPIs", + type: { + name: "Boolean" + } + }, + retentionPolicy: { + serializedName: "RetentionPolicy", + xmlName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + } + } } - /** - * Child classes must implement this method with request signing. This method - * will be executed in {@link sendRequest}. - * - * @param request - - */ - signRequest(request3) { - return request3; + }; + var CorsRule = { + serializedName: "CorsRule", + type: { + name: "Composite", + className: "CorsRule", + modelProperties: { + allowedOrigins: { + serializedName: "AllowedOrigins", + required: true, + xmlName: "AllowedOrigins", + type: { + name: "String" + } + }, + allowedMethods: { + serializedName: "AllowedMethods", + required: true, + xmlName: "AllowedMethods", + type: { + name: "String" + } + }, + allowedHeaders: { + serializedName: "AllowedHeaders", + required: true, + xmlName: "AllowedHeaders", + type: { + name: "String" + } + }, + exposedHeaders: { + serializedName: "ExposedHeaders", + required: true, + xmlName: "ExposedHeaders", + type: { + name: "String" + } + }, + maxAgeInSeconds: { + constraints: { + InclusiveMinimum: 0 + }, + serializedName: "MaxAgeInSeconds", + required: true, + xmlName: "MaxAgeInSeconds", + type: { + name: "Number" + } + } + } } }; - exports2.CredentialPolicy = CredentialPolicy; - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/policies/AnonymousCredentialPolicy.js -var require_AnonymousCredentialPolicy2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/policies/AnonymousCredentialPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AnonymousCredentialPolicy = void 0; - var CredentialPolicy_js_1 = require_CredentialPolicy2(); - var AnonymousCredentialPolicy = class extends CredentialPolicy_js_1.CredentialPolicy { - /** - * Creates an instance of AnonymousCredentialPolicy. - * @param nextPolicy - - * @param options - - */ - // The base class has a protected constructor. Adding a public one to enable constructing of this class. - /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ - constructor(nextPolicy, options) { - super(nextPolicy, options); + var StaticWebsite = { + serializedName: "StaticWebsite", + type: { + name: "Composite", + className: "StaticWebsite", + modelProperties: { + enabled: { + serializedName: "Enabled", + required: true, + xmlName: "Enabled", + type: { + name: "Boolean" + } + }, + indexDocument: { + serializedName: "IndexDocument", + xmlName: "IndexDocument", + type: { + name: "String" + } + }, + errorDocument404Path: { + serializedName: "ErrorDocument404Path", + xmlName: "ErrorDocument404Path", + type: { + name: "String" + } + }, + defaultIndexDocumentPath: { + serializedName: "DefaultIndexDocumentPath", + xmlName: "DefaultIndexDocumentPath", + type: { + name: "String" + } + } + } } }; - exports2.AnonymousCredentialPolicy = AnonymousCredentialPolicy; - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/credentials/Credential.js -var require_Credential2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/credentials/Credential.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Credential = void 0; - var Credential2 = class { - /** - * Creates a RequestPolicy object. - * - * @param _nextPolicy - - * @param _options - - */ - create(_nextPolicy, _options) { - throw new Error("Method should be implemented in children classes."); + var StorageError = { + serializedName: "StorageError", + type: { + name: "Composite", + className: "StorageError", + modelProperties: { + message: { + serializedName: "Message", + xmlName: "Message", + type: { + name: "String" + } + }, + copySourceStatusCode: { + serializedName: "CopySourceStatusCode", + xmlName: "CopySourceStatusCode", + type: { + name: "Number" + } + }, + copySourceErrorCode: { + serializedName: "CopySourceErrorCode", + xmlName: "CopySourceErrorCode", + type: { + name: "String" + } + }, + copySourceErrorMessage: { + serializedName: "CopySourceErrorMessage", + xmlName: "CopySourceErrorMessage", + type: { + name: "String" + } + }, + code: { + serializedName: "Code", + xmlName: "Code", + type: { + name: "String" + } + }, + authenticationErrorDetail: { + serializedName: "AuthenticationErrorDetail", + xmlName: "AuthenticationErrorDetail", + type: { + name: "String" + } + } + } } }; - exports2.Credential = Credential2; - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/credentials/AnonymousCredential.js -var require_AnonymousCredential2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/credentials/AnonymousCredential.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AnonymousCredential = void 0; - var AnonymousCredentialPolicy_js_1 = require_AnonymousCredentialPolicy2(); - var Credential_js_1 = require_Credential2(); - var AnonymousCredential = class extends Credential_js_1.Credential { - /** - * Creates an {@link AnonymousCredentialPolicy} object. - * - * @param nextPolicy - - * @param options - - */ - create(nextPolicy, options) { - return new AnonymousCredentialPolicy_js_1.AnonymousCredentialPolicy(nextPolicy, options); + var BlobServiceStatistics = { + serializedName: "BlobServiceStatistics", + xmlName: "StorageServiceStats", + type: { + name: "Composite", + className: "BlobServiceStatistics", + modelProperties: { + geoReplication: { + serializedName: "GeoReplication", + xmlName: "GeoReplication", + type: { + name: "Composite", + className: "GeoReplication" + } + } + } } }; - exports2.AnonymousCredential = AnonymousCredential; - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/utils/SharedKeyComparator.js -var require_SharedKeyComparator2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/utils/SharedKeyComparator.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.compareHeader = compareHeader; - var table_lv0 = new Uint32Array([ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1820, - 0, - 1823, - 1825, - 1827, - 1829, - 0, - 0, - 0, - 1837, - 2051, - 0, - 0, - 1843, - 0, - 3331, - 3354, - 3356, - 3358, - 3360, - 3362, - 3364, - 3366, - 3368, - 3370, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 3586, - 3593, - 3594, - 3610, - 3617, - 3619, - 3621, - 3628, - 3634, - 3637, - 3638, - 3656, - 3665, - 3696, - 3708, - 3710, - 3721, - 3722, - 3729, - 3737, - 3743, - 3746, - 3748, - 3750, - 3751, - 3753, - 0, - 0, - 0, - 1859, - 1860, - 1864, - 3586, - 3593, - 3594, - 3610, - 3617, - 3619, - 3621, - 3628, - 3634, - 3637, - 3638, - 3656, - 3665, - 3696, - 3708, - 3710, - 3721, - 3722, - 3729, - 3737, - 3743, - 3746, - 3748, - 3750, - 3751, - 3753, - 0, - 1868, - 0, - 1872, - 0 - ]); - var table_lv2 = new Uint32Array([ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]); - var table_lv4 = new Uint32Array([ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 32786, - 0, - 0, - 0, - 0, - 0, - 33298, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]); - function compareHeader(lhs, rhs) { - if (isLessThan(lhs, rhs)) - return -1; - return 1; - } - function isLessThan(lhs, rhs) { - const tables = [table_lv0, table_lv2, table_lv4]; - let curr_level = 0; - let i = 0; - let j = 0; - while (curr_level < tables.length) { - if (curr_level === tables.length - 1 && i !== j) { - return i > j; - } - const weight1 = i < lhs.length ? tables[curr_level][lhs[i].charCodeAt(0)] : 1; - const weight2 = j < rhs.length ? tables[curr_level][rhs[j].charCodeAt(0)] : 1; - if (weight1 === 1 && weight2 === 1) { - i = 0; - j = 0; - ++curr_level; - } else if (weight1 === weight2) { - ++i; - ++j; - } else if (weight1 === 0) { - ++i; - } else if (weight2 === 0) { - ++j; - } else { - return weight1 < weight2; + var GeoReplication = { + serializedName: "GeoReplication", + type: { + name: "Composite", + className: "GeoReplication", + modelProperties: { + status: { + serializedName: "Status", + required: true, + xmlName: "Status", + type: { + name: "Enum", + allowedValues: ["live", "bootstrap", "unavailable"] + } + }, + lastSyncOn: { + serializedName: "LastSyncTime", + required: true, + xmlName: "LastSyncTime", + type: { + name: "DateTimeRfc1123" + } + } } } - return false; - } - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/policies/StorageSharedKeyCredentialPolicy.js -var require_StorageSharedKeyCredentialPolicy2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/policies/StorageSharedKeyCredentialPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageSharedKeyCredentialPolicy = void 0; - var constants_js_1 = require_constants11(); - var utils_common_js_1 = require_utils_common2(); - var CredentialPolicy_js_1 = require_CredentialPolicy2(); - var SharedKeyComparator_js_1 = require_SharedKeyComparator2(); - var StorageSharedKeyCredentialPolicy = class extends CredentialPolicy_js_1.CredentialPolicy { - /** - * Reference to StorageSharedKeyCredential which generates StorageSharedKeyCredentialPolicy - */ - factory; - /** - * Creates an instance of StorageSharedKeyCredentialPolicy. - * @param nextPolicy - - * @param options - - * @param factory - - */ - constructor(nextPolicy, options, factory) { - super(nextPolicy, options); - this.factory = factory; - } - /** - * Signs request. - * - * @param request - - */ - signRequest(request3) { - request3.headers.set(constants_js_1.HeaderConstants.X_MS_DATE, (/* @__PURE__ */ new Date()).toUTCString()); - if (request3.body && (typeof request3.body === "string" || request3.body !== void 0) && request3.body.length > 0) { - request3.headers.set(constants_js_1.HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request3.body)); + }; + var ListContainersSegmentResponse = { + serializedName: "ListContainersSegmentResponse", + xmlName: "EnumerationResults", + type: { + name: "Composite", + className: "ListContainersSegmentResponse", + modelProperties: { + serviceEndpoint: { + serializedName: "ServiceEndpoint", + required: true, + xmlName: "ServiceEndpoint", + xmlIsAttribute: true, + type: { + name: "String" + } + }, + prefix: { + serializedName: "Prefix", + xmlName: "Prefix", + type: { + name: "String" + } + }, + marker: { + serializedName: "Marker", + xmlName: "Marker", + type: { + name: "String" + } + }, + maxPageSize: { + serializedName: "MaxResults", + xmlName: "MaxResults", + type: { + name: "Number" + } + }, + containerItems: { + serializedName: "ContainerItems", + required: true, + xmlName: "Containers", + xmlIsWrapped: true, + xmlElementName: "Container", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "ContainerItem" + } + } + } + }, + continuationToken: { + serializedName: "NextMarker", + xmlName: "NextMarker", + type: { + name: "String" + } + } } - const stringToSign = [ - request3.method.toUpperCase(), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_LANGUAGE), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_ENCODING), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_LENGTH), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_MD5), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_TYPE), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.DATE), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_MODIFIED_SINCE), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_MATCH), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_NONE_MATCH), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_UNMODIFIED_SINCE), - this.getHeaderValueToSign(request3, constants_js_1.HeaderConstants.RANGE) - ].join("\n") + "\n" + this.getCanonicalizedHeadersString(request3) + this.getCanonicalizedResourceString(request3); - const signature = this.factory.computeHMACSHA256(stringToSign); - request3.headers.set(constants_js_1.HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`); - return request3; } - /** - * Retrieve header value according to shared key sign rules. - * @see https://learn.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key - * - * @param request - - * @param headerName - - */ - getHeaderValueToSign(request3, headerName) { - const value = request3.headers.get(headerName); - if (!value) { - return ""; - } - if (headerName === constants_js_1.HeaderConstants.CONTENT_LENGTH && value === "0") { - return ""; + }; + var ContainerItem = { + serializedName: "ContainerItem", + xmlName: "Container", + type: { + name: "Composite", + className: "ContainerItem", + modelProperties: { + name: { + serializedName: "Name", + required: true, + xmlName: "Name", + type: { + name: "String" + } + }, + deleted: { + serializedName: "Deleted", + xmlName: "Deleted", + type: { + name: "Boolean" + } + }, + version: { + serializedName: "Version", + xmlName: "Version", + type: { + name: "String" + } + }, + properties: { + serializedName: "Properties", + xmlName: "Properties", + type: { + name: "Composite", + className: "ContainerProperties" + } + }, + metadata: { + serializedName: "Metadata", + xmlName: "Metadata", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + } } - return value; } - /** - * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: - * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. - * 2. Convert each HTTP header name to lowercase. - * 3. Sort the headers lexicographically by header name, in ascending order. - * Each header may appear only once in the string. - * 4. Replace any linear whitespace in the header value with a single space. - * 5. Trim any whitespace around the colon in the header. - * 6. Finally, append a new-line character to each canonicalized header in the resulting list. - * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. - * - * @param request - - */ - getCanonicalizedHeadersString(request3) { - let headersArray = request3.headers.headersArray().filter((value) => { - return value.name.toLowerCase().startsWith(constants_js_1.HeaderConstants.PREFIX_FOR_STORAGE); - }); - headersArray.sort((a, b) => { - return (0, SharedKeyComparator_js_1.compareHeader)(a.name.toLowerCase(), b.name.toLowerCase()); - }); - headersArray = headersArray.filter((value, index2, array2) => { - if (index2 > 0 && value.name.toLowerCase() === array2[index2 - 1].name.toLowerCase()) { - return false; + }; + var ContainerProperties = { + serializedName: "ContainerProperties", + type: { + name: "Composite", + className: "ContainerProperties", + modelProperties: { + lastModified: { + serializedName: "Last-Modified", + required: true, + xmlName: "Last-Modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "Etag", + required: true, + xmlName: "Etag", + type: { + name: "String" + } + }, + leaseStatus: { + serializedName: "LeaseStatus", + xmlName: "LeaseStatus", + type: { + name: "Enum", + allowedValues: ["locked", "unlocked"] + } + }, + leaseState: { + serializedName: "LeaseState", + xmlName: "LeaseState", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseDuration: { + serializedName: "LeaseDuration", + xmlName: "LeaseDuration", + type: { + name: "Enum", + allowedValues: ["infinite", "fixed"] + } + }, + publicAccess: { + serializedName: "PublicAccess", + xmlName: "PublicAccess", + type: { + name: "Enum", + allowedValues: ["container", "blob"] + } + }, + hasImmutabilityPolicy: { + serializedName: "HasImmutabilityPolicy", + xmlName: "HasImmutabilityPolicy", + type: { + name: "Boolean" + } + }, + hasLegalHold: { + serializedName: "HasLegalHold", + xmlName: "HasLegalHold", + type: { + name: "Boolean" + } + }, + defaultEncryptionScope: { + serializedName: "DefaultEncryptionScope", + xmlName: "DefaultEncryptionScope", + type: { + name: "String" + } + }, + preventEncryptionScopeOverride: { + serializedName: "DenyEncryptionScopeOverride", + xmlName: "DenyEncryptionScopeOverride", + type: { + name: "Boolean" + } + }, + deletedOn: { + serializedName: "DeletedTime", + xmlName: "DeletedTime", + type: { + name: "DateTimeRfc1123" + } + }, + remainingRetentionDays: { + serializedName: "RemainingRetentionDays", + xmlName: "RemainingRetentionDays", + type: { + name: "Number" + } + }, + isImmutableStorageWithVersioningEnabled: { + serializedName: "ImmutableStorageWithVersioningEnabled", + xmlName: "ImmutableStorageWithVersioningEnabled", + type: { + name: "Boolean" + } } - return true; - }); - let canonicalizedHeadersStringToSign = ""; - headersArray.forEach((header) => { - canonicalizedHeadersStringToSign += `${header.name.toLowerCase().trimRight()}:${header.value.trimLeft()} -`; - }); - return canonicalizedHeadersStringToSign; + } } - /** - * Retrieves the webResource canonicalized resource string. - * - * @param request - - */ - getCanonicalizedResourceString(request3) { - const path30 = (0, utils_common_js_1.getURLPath)(request3.url) || "/"; - let canonicalizedResourceString = ""; - canonicalizedResourceString += `/${this.factory.accountName}${path30}`; - const queries = (0, utils_common_js_1.getURLQueries)(request3.url); - const lowercaseQueries = {}; - if (queries) { - const queryKeys = []; - for (const key in queries) { - if (Object.prototype.hasOwnProperty.call(queries, key)) { - const lowercaseKey = key.toLowerCase(); - lowercaseQueries[lowercaseKey] = queries[key]; - queryKeys.push(lowercaseKey); + }; + var KeyInfo = { + serializedName: "KeyInfo", + type: { + name: "Composite", + className: "KeyInfo", + modelProperties: { + startsOn: { + serializedName: "Start", + required: true, + xmlName: "Start", + type: { + name: "String" + } + }, + expiresOn: { + serializedName: "Expiry", + required: true, + xmlName: "Expiry", + type: { + name: "String" + } + }, + delegatedUserTid: { + serializedName: "DelegatedUserTid", + xmlName: "DelegatedUserTid", + type: { + name: "String" } } - queryKeys.sort(); - for (const key of queryKeys) { - canonicalizedResourceString += ` -${key}:${decodeURIComponent(lowercaseQueries[key])}`; + } + } + }; + var UserDelegationKey = { + serializedName: "UserDelegationKey", + type: { + name: "Composite", + className: "UserDelegationKey", + modelProperties: { + signedObjectId: { + serializedName: "SignedOid", + required: true, + xmlName: "SignedOid", + type: { + name: "String" + } + }, + signedTenantId: { + serializedName: "SignedTid", + required: true, + xmlName: "SignedTid", + type: { + name: "String" + } + }, + signedStartsOn: { + serializedName: "SignedStart", + required: true, + xmlName: "SignedStart", + type: { + name: "String" + } + }, + signedExpiresOn: { + serializedName: "SignedExpiry", + required: true, + xmlName: "SignedExpiry", + type: { + name: "String" + } + }, + signedService: { + serializedName: "SignedService", + required: true, + xmlName: "SignedService", + type: { + name: "String" + } + }, + signedVersion: { + serializedName: "SignedVersion", + required: true, + xmlName: "SignedVersion", + type: { + name: "String" + } + }, + signedDelegatedUserTenantId: { + serializedName: "SignedDelegatedUserTid", + xmlName: "SignedDelegatedUserTid", + type: { + name: "String" + } + }, + value: { + serializedName: "Value", + required: true, + xmlName: "Value", + type: { + name: "String" + } } } - return canonicalizedResourceString; } }; - exports2.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/credentials/StorageSharedKeyCredential.js -var require_StorageSharedKeyCredential2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/credentials/StorageSharedKeyCredential.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageSharedKeyCredential = void 0; - var node_crypto_1 = require("node:crypto"); - var StorageSharedKeyCredentialPolicy_js_1 = require_StorageSharedKeyCredentialPolicy2(); - var Credential_js_1 = require_Credential2(); - var StorageSharedKeyCredential = class extends Credential_js_1.Credential { - /** - * Azure Storage account name; readonly. - */ - accountName; - /** - * Azure Storage account key; readonly. - */ - accountKey; - /** - * Creates an instance of StorageSharedKeyCredential. - * @param accountName - - * @param accountKey - - */ - constructor(accountName, accountKey) { - super(); - this.accountName = accountName; - this.accountKey = Buffer.from(accountKey, "base64"); + var FilterBlobSegment = { + serializedName: "FilterBlobSegment", + xmlName: "EnumerationResults", + type: { + name: "Composite", + className: "FilterBlobSegment", + modelProperties: { + serviceEndpoint: { + serializedName: "ServiceEndpoint", + required: true, + xmlName: "ServiceEndpoint", + xmlIsAttribute: true, + type: { + name: "String" + } + }, + where: { + serializedName: "Where", + required: true, + xmlName: "Where", + type: { + name: "String" + } + }, + blobs: { + serializedName: "Blobs", + required: true, + xmlName: "Blobs", + xmlIsWrapped: true, + xmlElementName: "Blob", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "FilterBlobItem" + } + } + } + }, + continuationToken: { + serializedName: "NextMarker", + xmlName: "NextMarker", + type: { + name: "String" + } + } + } } - /** - * Creates a StorageSharedKeyCredentialPolicy object. - * - * @param nextPolicy - - * @param options - - */ - create(nextPolicy, options) { - return new StorageSharedKeyCredentialPolicy_js_1.StorageSharedKeyCredentialPolicy(nextPolicy, options, this); + }; + var FilterBlobItem = { + serializedName: "FilterBlobItem", + xmlName: "Blob", + type: { + name: "Composite", + className: "FilterBlobItem", + modelProperties: { + name: { + serializedName: "Name", + required: true, + xmlName: "Name", + type: { + name: "String" + } + }, + containerName: { + serializedName: "ContainerName", + required: true, + xmlName: "ContainerName", + type: { + name: "String" + } + }, + tags: { + serializedName: "Tags", + xmlName: "Tags", + type: { + name: "Composite", + className: "BlobTags" + } + } + } } - /** - * Generates a hash signature for an HTTP request or for a SAS. - * - * @param stringToSign - - */ - computeHMACSHA256(stringToSign) { - return (0, node_crypto_1.createHmac)("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64"); + }; + var BlobTags = { + serializedName: "BlobTags", + xmlName: "Tags", + type: { + name: "Composite", + className: "BlobTags", + modelProperties: { + blobTagSet: { + serializedName: "BlobTagSet", + required: true, + xmlName: "TagSet", + xmlIsWrapped: true, + xmlElementName: "Tag", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobTag" + } + } + } + } + } } }; - exports2.StorageSharedKeyCredential = StorageSharedKeyCredential; - } -}); - -// node_modules/@azure/storage-common/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError4 = __commonJS({ - "node_modules/@azure/storage-common/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + var BlobTag = { + serializedName: "BlobTag", + xmlName: "Tag", + type: { + name: "Composite", + className: "BlobTag", + modelProperties: { + key: { + serializedName: "Key", + required: true, + xmlName: "Key", + type: { + name: "String" + } + }, + value: { + serializedName: "Value", + required: true, + xmlName: "Value", + type: { + name: "String" + } + } + } } }; - exports2.AbortError = AbortError; - } -}); - -// node_modules/@azure/storage-common/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs12 = __commonJS({ - "node_modules/@azure/storage-common/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError4(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/log.js -var require_log6 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/log.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = void 0; - var logger_1 = require_commonjs2(); - exports2.logger = (0, logger_1.createClientLogger)("storage-common"); - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/policies/StorageRetryPolicyType.js -var require_StorageRetryPolicyType2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/policies/StorageRetryPolicyType.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageRetryPolicyType = void 0; - var StorageRetryPolicyType; - (function(StorageRetryPolicyType2) { - StorageRetryPolicyType2[StorageRetryPolicyType2["EXPONENTIAL"] = 0] = "EXPONENTIAL"; - StorageRetryPolicyType2[StorageRetryPolicyType2["FIXED"] = 1] = "FIXED"; - })(StorageRetryPolicyType || (exports2.StorageRetryPolicyType = StorageRetryPolicyType = {})); - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/policies/StorageRetryPolicy.js -var require_StorageRetryPolicy2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/policies/StorageRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageRetryPolicy = void 0; - exports2.NewRetryPolicyFactory = NewRetryPolicyFactory; - var abort_controller_1 = require_commonjs12(); - var RequestPolicy_js_1 = require_RequestPolicy2(); - var constants_js_1 = require_constants11(); - var utils_common_js_1 = require_utils_common2(); - var log_js_1 = require_log6(); - var StorageRetryPolicyType_js_1 = require_StorageRetryPolicyType2(); - function NewRetryPolicyFactory(retryOptions) { - return { - create: (nextPolicy, options) => { - return new StorageRetryPolicy(nextPolicy, options, retryOptions); - } - }; - } - var DEFAULT_RETRY_OPTIONS = { - maxRetryDelayInMs: 120 * 1e3, - maxTries: 4, - retryDelayInMs: 4 * 1e3, - retryPolicyType: StorageRetryPolicyType_js_1.StorageRetryPolicyType.EXPONENTIAL, - secondaryHost: "", - tryTimeoutInMs: void 0 - // Use server side default timeout strategy - }; - var RETRY_ABORT_ERROR = new abort_controller_1.AbortError("The operation was aborted."); - var StorageRetryPolicy = class extends RequestPolicy_js_1.BaseRequestPolicy { - /** - * RetryOptions. - */ - retryOptions; - /** - * Creates an instance of RetryPolicy. - * - * @param nextPolicy - - * @param options - - * @param retryOptions - - */ - constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS) { - super(nextPolicy, options); - this.retryOptions = { - retryPolicyType: retryOptions.retryPolicyType ? retryOptions.retryPolicyType : DEFAULT_RETRY_OPTIONS.retryPolicyType, - maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1 ? Math.floor(retryOptions.maxTries) : DEFAULT_RETRY_OPTIONS.maxTries, - tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0 ? retryOptions.tryTimeoutInMs : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs, - retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0 ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs) : DEFAULT_RETRY_OPTIONS.retryDelayInMs, - maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0 ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs, - secondaryHost: retryOptions.secondaryHost ? retryOptions.secondaryHost : DEFAULT_RETRY_OPTIONS.secondaryHost - }; - } - /** - * Sends request. - * - * @param request - - */ - async sendRequest(request3) { - return this.attemptSendRequest(request3, false, 1); - } - /** - * Decide and perform next retry. Won't mutate request parameter. - * - * @param request - - * @param secondaryHas404 - If attempt was against the secondary & it returned a StatusNotFound (404), then - * the resource was not found. This may be due to replication delay. So, in this - * case, we'll never try the secondary again for this operation. - * @param attempt - How many retries has been attempted to performed, starting from 1, which includes - * the attempt will be performed by this method call. - */ - async attemptSendRequest(request3, secondaryHas404, attempt) { - const newRequest = request3.clone(); - const isPrimaryRetry = secondaryHas404 || !this.retryOptions.secondaryHost || !(request3.method === "GET" || request3.method === "HEAD" || request3.method === "OPTIONS") || attempt % 2 === 1; - if (!isPrimaryRetry) { - newRequest.url = (0, utils_common_js_1.setURLHost)(newRequest.url, this.retryOptions.secondaryHost); - } - if (this.retryOptions.tryTimeoutInMs) { - newRequest.url = (0, utils_common_js_1.setURLParameter)(newRequest.url, constants_js_1.URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1e3).toString()); - } - let response; - try { - log_js_1.logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); - response = await this._nextPolicy.sendRequest(newRequest); - if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { - return response; - } - secondaryHas404 = secondaryHas404 || !isPrimaryRetry && response.status === 404; - } catch (err) { - log_js_1.logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`); - if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) { - throw err; - } - } - await this.delay(isPrimaryRetry, attempt, request3.abortSignal); - return this.attemptSendRequest(request3, secondaryHas404, ++attempt); - } - /** - * Decide whether to retry according to last HTTP response and retry counters. - * - * @param isPrimaryRetry - - * @param attempt - - * @param response - - * @param err - - */ - shouldRetry(isPrimaryRetry, attempt, response, err) { - if (attempt >= this.retryOptions.maxTries) { - log_js_1.logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions.maxTries}, no further try.`); - return false; - } - const retriableErrors = [ - "ETIMEDOUT", - "ESOCKETTIMEDOUT", - "ECONNREFUSED", - "ECONNRESET", - "ENOENT", - "ENOTFOUND", - "TIMEOUT", - "EPIPE", - "REQUEST_SEND_ERROR" - // For default xhr based http client provided in ms-rest-js - ]; - if (err) { - for (const retriableError of retriableErrors) { - if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || err.code && err.code.toString().toUpperCase() === retriableError) { - log_js_1.logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); - return true; + var SignedIdentifier = { + serializedName: "SignedIdentifier", + xmlName: "SignedIdentifier", + type: { + name: "Composite", + className: "SignedIdentifier", + modelProperties: { + id: { + serializedName: "Id", + required: true, + xmlName: "Id", + type: { + name: "String" } - } - } - if (response || err) { - const statusCode = response ? response.status : err ? err.statusCode : 0; - if (!isPrimaryRetry && statusCode === 404) { - log_js_1.logger.info(`RetryPolicy: Secondary access with 404, will retry.`); - return true; - } - if (statusCode === 503 || statusCode === 500) { - log_js_1.logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); - return true; - } - } - if (response) { - if (response?.status >= 400) { - const copySourceError = response.headers.get(constants_js_1.HeaderConstants.X_MS_CopySourceErrorCode); - if (copySourceError !== void 0) { - switch (copySourceError) { - case "InternalError": - case "OperationTimedOut": - case "ServerBusy": - return true; - } + }, + accessPolicy: { + serializedName: "AccessPolicy", + xmlName: "AccessPolicy", + type: { + name: "Composite", + className: "AccessPolicy" } } } - if (err?.code === "PARSE_ERROR" && err?.message.startsWith(`Error "Error: Unclosed root tag`)) { - log_js_1.logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); - return true; - } - return false; - } - /** - * Delay a calculated time between retries. - * - * @param isPrimaryRetry - - * @param attempt - - * @param abortSignal - - */ - async delay(isPrimaryRetry, attempt, abortSignal) { - let delayTimeInMs = 0; - if (isPrimaryRetry) { - switch (this.retryOptions.retryPolicyType) { - case StorageRetryPolicyType_js_1.StorageRetryPolicyType.EXPONENTIAL: - delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); - break; - case StorageRetryPolicyType_js_1.StorageRetryPolicyType.FIXED: - delayTimeInMs = this.retryOptions.retryDelayInMs; - break; - } - } else { - delayTimeInMs = Math.random() * 1e3; - } - log_js_1.logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); - return (0, utils_common_js_1.delay)(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR); - } - }; - exports2.StorageRetryPolicy = StorageRetryPolicy; - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/StorageRetryPolicyFactory.js -var require_StorageRetryPolicyFactory2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/StorageRetryPolicyFactory.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageRetryPolicyFactory = exports2.StorageRetryPolicy = exports2.StorageRetryPolicyType = void 0; - var StorageRetryPolicy_js_1 = require_StorageRetryPolicy2(); - Object.defineProperty(exports2, "StorageRetryPolicy", { enumerable: true, get: function() { - return StorageRetryPolicy_js_1.StorageRetryPolicy; - } }); - var StorageRetryPolicyType_js_1 = require_StorageRetryPolicyType2(); - Object.defineProperty(exports2, "StorageRetryPolicyType", { enumerable: true, get: function() { - return StorageRetryPolicyType_js_1.StorageRetryPolicyType; - } }); - var StorageRetryPolicyFactory = class { - retryOptions; - /** - * Creates an instance of StorageRetryPolicyFactory. - * @param retryOptions - - */ - constructor(retryOptions) { - this.retryOptions = retryOptions; - } - /** - * Creates a StorageRetryPolicy object. - * - * @param nextPolicy - - * @param options - - */ - create(nextPolicy, options) { - return new StorageRetryPolicy_js_1.StorageRetryPolicy(nextPolicy, options, this.retryOptions); } }; - exports2.StorageRetryPolicyFactory = StorageRetryPolicyFactory; - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/policies/StorageBrowserPolicyV2.js -var require_StorageBrowserPolicyV2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/policies/StorageBrowserPolicyV2.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.storageBrowserPolicyName = void 0; - exports2.storageBrowserPolicy = storageBrowserPolicy; - var core_util_1 = require_commonjs4(); - var constants_js_1 = require_constants11(); - var utils_common_js_1 = require_utils_common2(); - exports2.storageBrowserPolicyName = "storageBrowserPolicy"; - function storageBrowserPolicy() { - return { - name: exports2.storageBrowserPolicyName, - async sendRequest(request3, next) { - if (core_util_1.isNodeLike) { - return next(request3); - } - if (request3.method === "GET" || request3.method === "HEAD") { - request3.url = (0, utils_common_js_1.setURLParameter)(request3.url, constants_js_1.URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, (/* @__PURE__ */ new Date()).getTime().toString()); + var AccessPolicy = { + serializedName: "AccessPolicy", + type: { + name: "Composite", + className: "AccessPolicy", + modelProperties: { + startsOn: { + serializedName: "Start", + xmlName: "Start", + type: { + name: "String" + } + }, + expiresOn: { + serializedName: "Expiry", + xmlName: "Expiry", + type: { + name: "String" + } + }, + permissions: { + serializedName: "Permission", + xmlName: "Permission", + type: { + name: "String" + } } - request3.headers.delete(constants_js_1.HeaderConstants.COOKIE); - request3.headers.delete(constants_js_1.HeaderConstants.CONTENT_LENGTH); - return next(request3); - } - }; - } - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/policies/StorageCorrectContentLengthPolicy.js -var require_StorageCorrectContentLengthPolicy = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/policies/StorageCorrectContentLengthPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.storageCorrectContentLengthPolicyName = void 0; - exports2.storageCorrectContentLengthPolicy = storageCorrectContentLengthPolicy; - var constants_js_1 = require_constants11(); - exports2.storageCorrectContentLengthPolicyName = "StorageCorrectContentLengthPolicy"; - function storageCorrectContentLengthPolicy() { - function correctContentLength(request3) { - if (request3.body && (typeof request3.body === "string" || Buffer.isBuffer(request3.body)) && request3.body.length > 0) { - request3.headers.set(constants_js_1.HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request3.body)); } } - return { - name: exports2.storageCorrectContentLengthPolicyName, - async sendRequest(request3, next) { - correctContentLength(request3); - return next(request3); - } - }; - } - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/policies/StorageRetryPolicyV2.js -var require_StorageRetryPolicyV2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/policies/StorageRetryPolicyV2.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.storageRetryPolicyName = void 0; - exports2.storageRetryPolicy = storageRetryPolicy; - var abort_controller_1 = require_commonjs12(); - var core_rest_pipeline_1 = require_commonjs6(); - var core_util_1 = require_commonjs4(); - var StorageRetryPolicyFactory_js_1 = require_StorageRetryPolicyFactory2(); - var constants_js_1 = require_constants11(); - var utils_common_js_1 = require_utils_common2(); - var log_js_1 = require_log6(); - exports2.storageRetryPolicyName = "storageRetryPolicy"; - var DEFAULT_RETRY_OPTIONS = { - maxRetryDelayInMs: 120 * 1e3, - maxTries: 4, - retryDelayInMs: 4 * 1e3, - retryPolicyType: StorageRetryPolicyFactory_js_1.StorageRetryPolicyType.EXPONENTIAL, - secondaryHost: "", - tryTimeoutInMs: void 0 - // Use server side default timeout strategy }; - var retriableErrors = [ - "ETIMEDOUT", - "ESOCKETTIMEDOUT", - "ECONNREFUSED", - "ECONNRESET", - "ENOENT", - "ENOTFOUND", - "TIMEOUT", - "EPIPE", - "REQUEST_SEND_ERROR" - ]; - var RETRY_ABORT_ERROR = new abort_controller_1.AbortError("The operation was aborted."); - function storageRetryPolicy(options = {}) { - const retryPolicyType = options.retryPolicyType ?? DEFAULT_RETRY_OPTIONS.retryPolicyType; - const maxTries = options.maxTries ?? DEFAULT_RETRY_OPTIONS.maxTries; - const retryDelayInMs = options.retryDelayInMs ?? DEFAULT_RETRY_OPTIONS.retryDelayInMs; - const maxRetryDelayInMs = options.maxRetryDelayInMs ?? DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs; - const secondaryHost = options.secondaryHost ?? DEFAULT_RETRY_OPTIONS.secondaryHost; - const tryTimeoutInMs = options.tryTimeoutInMs ?? DEFAULT_RETRY_OPTIONS.tryTimeoutInMs; - function shouldRetry({ isPrimaryRetry, attempt, response, error: error3 }) { - if (attempt >= maxTries) { - log_js_1.logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${maxTries}, no further try.`); - return false; - } - if (error3) { - for (const retriableError of retriableErrors) { - if (error3.name.toUpperCase().includes(retriableError) || error3.message.toUpperCase().includes(retriableError) || error3.code && error3.code.toString().toUpperCase() === retriableError) { - log_js_1.logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); - return true; + var ListBlobsFlatSegmentResponse = { + serializedName: "ListBlobsFlatSegmentResponse", + xmlName: "EnumerationResults", + type: { + name: "Composite", + className: "ListBlobsFlatSegmentResponse", + modelProperties: { + serviceEndpoint: { + serializedName: "ServiceEndpoint", + required: true, + xmlName: "ServiceEndpoint", + xmlIsAttribute: true, + type: { + name: "String" } - } - if (error3?.code === "PARSE_ERROR" && error3?.message.startsWith(`Error "Error: Unclosed root tag`)) { - log_js_1.logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); - return true; - } - } - if (response || error3) { - const statusCode = response?.status ?? error3?.statusCode ?? 0; - if (!isPrimaryRetry && statusCode === 404) { - log_js_1.logger.info(`RetryPolicy: Secondary access with 404, will retry.`); - return true; - } - if (statusCode === 503 || statusCode === 500) { - log_js_1.logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); - return true; - } - } - if (response) { - if (response?.status >= 400) { - const copySourceError = response.headers.get(constants_js_1.HeaderConstants.X_MS_CopySourceErrorCode); - if (copySourceError !== void 0) { - switch (copySourceError) { - case "InternalError": - case "OperationTimedOut": - case "ServerBusy": - return true; - } + }, + containerName: { + serializedName: "ContainerName", + required: true, + xmlName: "ContainerName", + xmlIsAttribute: true, + type: { + name: "String" } - } - } - return false; - } - function calculateDelay(isPrimaryRetry, attempt) { - let delayTimeInMs = 0; - if (isPrimaryRetry) { - switch (retryPolicyType) { - case StorageRetryPolicyFactory_js_1.StorageRetryPolicyType.EXPONENTIAL: - delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * retryDelayInMs, maxRetryDelayInMs); - break; - case StorageRetryPolicyFactory_js_1.StorageRetryPolicyType.FIXED: - delayTimeInMs = retryDelayInMs; - break; - } - } else { - delayTimeInMs = Math.random() * 1e3; - } - log_js_1.logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); - return delayTimeInMs; - } - return { - name: exports2.storageRetryPolicyName, - async sendRequest(request3, next) { - if (tryTimeoutInMs) { - request3.url = (0, utils_common_js_1.setURLParameter)(request3.url, constants_js_1.URLConstants.Parameters.TIMEOUT, String(Math.floor(tryTimeoutInMs / 1e3))); - } - const primaryUrl = request3.url; - const secondaryUrl = secondaryHost ? (0, utils_common_js_1.setURLHost)(request3.url, secondaryHost) : void 0; - let secondaryHas404 = false; - let attempt = 1; - let retryAgain = true; - let response; - let error3; - while (retryAgain) { - const isPrimaryRetry = secondaryHas404 || !secondaryUrl || !["GET", "HEAD", "OPTIONS"].includes(request3.method) || attempt % 2 === 1; - request3.url = isPrimaryRetry ? primaryUrl : secondaryUrl; - response = void 0; - error3 = void 0; - try { - log_js_1.logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); - response = await next(request3); - secondaryHas404 = secondaryHas404 || !isPrimaryRetry && response.status === 404; - } catch (e) { - if ((0, core_rest_pipeline_1.isRestError)(e)) { - log_js_1.logger.error(`RetryPolicy: Caught error, message: ${e.message}, code: ${e.code}`); - error3 = e; - } else { - log_js_1.logger.error(`RetryPolicy: Caught error, message: ${(0, core_util_1.getErrorMessage)(e)}`); - throw e; - } + }, + prefix: { + serializedName: "Prefix", + xmlName: "Prefix", + type: { + name: "String" } - retryAgain = shouldRetry({ isPrimaryRetry, attempt, response, error: error3 }); - if (retryAgain) { - await (0, utils_common_js_1.delay)(calculateDelay(isPrimaryRetry, attempt), request3.abortSignal, RETRY_ABORT_ERROR); + }, + marker: { + serializedName: "Marker", + xmlName: "Marker", + type: { + name: "String" } - attempt++; - } - if (response) { - return response; - } - throw error3 ?? new core_rest_pipeline_1.RestError("RetryPolicy failed without known error."); - } - }; - } - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/policies/StorageSharedKeyCredentialPolicyV2.js -var require_StorageSharedKeyCredentialPolicyV2 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/policies/StorageSharedKeyCredentialPolicyV2.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.storageSharedKeyCredentialPolicyName = void 0; - exports2.storageSharedKeyCredentialPolicy = storageSharedKeyCredentialPolicy; - var node_crypto_1 = require("node:crypto"); - var constants_js_1 = require_constants11(); - var utils_common_js_1 = require_utils_common2(); - var SharedKeyComparator_js_1 = require_SharedKeyComparator2(); - exports2.storageSharedKeyCredentialPolicyName = "storageSharedKeyCredentialPolicy"; - function storageSharedKeyCredentialPolicy(options) { - function signRequest(request3) { - request3.headers.set(constants_js_1.HeaderConstants.X_MS_DATE, (/* @__PURE__ */ new Date()).toUTCString()); - if (request3.body && (typeof request3.body === "string" || Buffer.isBuffer(request3.body)) && request3.body.length > 0) { - request3.headers.set(constants_js_1.HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request3.body)); - } - const stringToSign = [ - request3.method.toUpperCase(), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_LANGUAGE), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_ENCODING), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_LENGTH), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_MD5), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_TYPE), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.DATE), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_MODIFIED_SINCE), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_MATCH), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_NONE_MATCH), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_UNMODIFIED_SINCE), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.RANGE) - ].join("\n") + "\n" + getCanonicalizedHeadersString(request3) + getCanonicalizedResourceString(request3); - const signature = (0, node_crypto_1.createHmac)("sha256", options.accountKey).update(stringToSign, "utf8").digest("base64"); - request3.headers.set(constants_js_1.HeaderConstants.AUTHORIZATION, `SharedKey ${options.accountName}:${signature}`); - } - function getHeaderValueToSign(request3, headerName) { - const value = request3.headers.get(headerName); - if (!value) { - return ""; - } - if (headerName === constants_js_1.HeaderConstants.CONTENT_LENGTH && value === "0") { - return ""; - } - return value; - } - function getCanonicalizedHeadersString(request3) { - let headersArray = []; - for (const [name, value] of request3.headers) { - if (name.toLowerCase().startsWith(constants_js_1.HeaderConstants.PREFIX_FOR_STORAGE)) { - headersArray.push({ name, value }); - } - } - headersArray.sort((a, b) => { - return (0, SharedKeyComparator_js_1.compareHeader)(a.name.toLowerCase(), b.name.toLowerCase()); - }); - headersArray = headersArray.filter((value, index2, array2) => { - if (index2 > 0 && value.name.toLowerCase() === array2[index2 - 1].name.toLowerCase()) { - return false; - } - return true; - }); - let canonicalizedHeadersStringToSign = ""; - headersArray.forEach((header) => { - canonicalizedHeadersStringToSign += `${header.name.toLowerCase().trimRight()}:${header.value.trimLeft()} -`; - }); - return canonicalizedHeadersStringToSign; - } - function getCanonicalizedResourceString(request3) { - const path30 = (0, utils_common_js_1.getURLPath)(request3.url) || "/"; - let canonicalizedResourceString = ""; - canonicalizedResourceString += `/${options.accountName}${path30}`; - const queries = (0, utils_common_js_1.getURLQueries)(request3.url); - const lowercaseQueries = {}; - if (queries) { - const queryKeys = []; - for (const key in queries) { - if (Object.prototype.hasOwnProperty.call(queries, key)) { - const lowercaseKey = key.toLowerCase(); - lowercaseQueries[lowercaseKey] = queries[key]; - queryKeys.push(lowercaseKey); + }, + maxPageSize: { + serializedName: "MaxResults", + xmlName: "MaxResults", + type: { + name: "Number" + } + }, + segment: { + serializedName: "Segment", + xmlName: "Blobs", + type: { + name: "Composite", + className: "BlobFlatListSegment" + } + }, + continuationToken: { + serializedName: "NextMarker", + xmlName: "NextMarker", + type: { + name: "String" } - } - queryKeys.sort(); - for (const key of queryKeys) { - canonicalizedResourceString += ` -${key}:${decodeURIComponent(lowercaseQueries[key])}`; } } - return canonicalizedResourceString; } - return { - name: exports2.storageSharedKeyCredentialPolicyName, - async sendRequest(request3, next) { - signRequest(request3); - return next(request3); - } - }; - } - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/policies/StorageRequestFailureDetailsParserPolicy.js -var require_StorageRequestFailureDetailsParserPolicy = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/policies/StorageRequestFailureDetailsParserPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.storageRequestFailureDetailsParserPolicyName = void 0; - exports2.storageRequestFailureDetailsParserPolicy = storageRequestFailureDetailsParserPolicy; - exports2.storageRequestFailureDetailsParserPolicyName = "storageRequestFailureDetailsParserPolicy"; - function storageRequestFailureDetailsParserPolicy() { - return { - name: exports2.storageRequestFailureDetailsParserPolicyName, - async sendRequest(request3, next) { - try { - const response = await next(request3); - return response; - } catch (err) { - if (typeof err === "object" && err !== null && err.response && err.response.parsedBody) { - if (err.response.parsedBody.code === "InvalidHeaderValue" && err.response.parsedBody.HeaderName === "x-ms-version") { - err.message = "The provided service version is not enabled on this storage account. Please see https://learn.microsoft.com/rest/api/storageservices/versioning-for-the-azure-storage-services for additional information.\n"; + }; + var BlobFlatListSegment = { + serializedName: "BlobFlatListSegment", + xmlName: "Blobs", + type: { + name: "Composite", + className: "BlobFlatListSegment", + modelProperties: { + blobItems: { + serializedName: "BlobItems", + required: true, + xmlName: "BlobItems", + xmlElementName: "Blob", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobItemInternal" + } } } - throw err; - } - } - }; - } - } -}); - -// node_modules/@azure/storage-common/dist/commonjs/index.js -var require_commonjs13 = __commonJS({ - "node_modules/@azure/storage-common/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BaseRequestPolicy = exports2.getCachedDefaultHttpClient = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_BufferScheduler(), exports2); - var cache_js_1 = require_cache2(); - Object.defineProperty(exports2, "getCachedDefaultHttpClient", { enumerable: true, get: function() { - return cache_js_1.getCachedDefaultHttpClient; - } }); - tslib_1.__exportStar(require_StorageBrowserPolicyFactory(), exports2); - tslib_1.__exportStar(require_AnonymousCredential2(), exports2); - tslib_1.__exportStar(require_Credential2(), exports2); - tslib_1.__exportStar(require_StorageSharedKeyCredential2(), exports2); - tslib_1.__exportStar(require_StorageRetryPolicyFactory2(), exports2); - var RequestPolicy_js_1 = require_RequestPolicy2(); - Object.defineProperty(exports2, "BaseRequestPolicy", { enumerable: true, get: function() { - return RequestPolicy_js_1.BaseRequestPolicy; - } }); - tslib_1.__exportStar(require_AnonymousCredentialPolicy2(), exports2); - tslib_1.__exportStar(require_CredentialPolicy2(), exports2); - tslib_1.__exportStar(require_StorageBrowserPolicy(), exports2); - tslib_1.__exportStar(require_StorageBrowserPolicyV2(), exports2); - tslib_1.__exportStar(require_StorageCorrectContentLengthPolicy(), exports2); - tslib_1.__exportStar(require_StorageRetryPolicyType2(), exports2); - tslib_1.__exportStar(require_StorageRetryPolicy2(), exports2); - tslib_1.__exportStar(require_StorageRetryPolicyV2(), exports2); - tslib_1.__exportStar(require_StorageSharedKeyCredentialPolicy2(), exports2); - tslib_1.__exportStar(require_StorageSharedKeyCredentialPolicyV2(), exports2); - tslib_1.__exportStar(require_StorageRetryPolicyFactory2(), exports2); - tslib_1.__exportStar(require_StorageRequestFailureDetailsParserPolicy(), exports2); - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/policies/StorageBrowserPolicyV2.js -var require_StorageBrowserPolicyV22 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/policies/StorageBrowserPolicyV2.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.storageBrowserPolicyName = void 0; - exports2.storageBrowserPolicy = storageBrowserPolicy; - var core_util_1 = require_commonjs4(); - var constants_js_1 = require_constants10(); - var utils_common_js_1 = require_utils_common(); - exports2.storageBrowserPolicyName = "storageBrowserPolicy"; - function storageBrowserPolicy() { - return { - name: exports2.storageBrowserPolicyName, - async sendRequest(request3, next) { - if (core_util_1.isNodeLike) { - return next(request3); - } - if (request3.method === "GET" || request3.method === "HEAD") { - request3.url = (0, utils_common_js_1.setURLParameter)(request3.url, constants_js_1.URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, (/* @__PURE__ */ new Date()).getTime().toString()); } - request3.headers.delete(constants_js_1.HeaderConstants.COOKIE); - request3.headers.delete(constants_js_1.HeaderConstants.CONTENT_LENGTH); - return next(request3); } - }; - } - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/policies/StorageRetryPolicyV2.js -var require_StorageRetryPolicyV22 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/policies/StorageRetryPolicyV2.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.storageRetryPolicyName = void 0; - exports2.storageRetryPolicy = storageRetryPolicy; - var abort_controller_1 = require_commonjs11(); - var core_rest_pipeline_1 = require_commonjs6(); - var core_util_1 = require_commonjs4(); - var StorageRetryPolicyFactory_js_1 = require_StorageRetryPolicyFactory(); - var constants_js_1 = require_constants10(); - var utils_common_js_1 = require_utils_common(); - var log_js_1 = require_log5(); - exports2.storageRetryPolicyName = "storageRetryPolicy"; - var DEFAULT_RETRY_OPTIONS = { - maxRetryDelayInMs: 120 * 1e3, - maxTries: 4, - retryDelayInMs: 4 * 1e3, - retryPolicyType: StorageRetryPolicyFactory_js_1.StorageRetryPolicyType.EXPONENTIAL, - secondaryHost: "", - tryTimeoutInMs: void 0 - // Use server side default timeout strategy + } }; - var retriableErrors = [ - "ETIMEDOUT", - "ESOCKETTIMEDOUT", - "ECONNREFUSED", - "ECONNRESET", - "ENOENT", - "ENOTFOUND", - "TIMEOUT", - "EPIPE", - "REQUEST_SEND_ERROR" - ]; - var RETRY_ABORT_ERROR = new abort_controller_1.AbortError("The operation was aborted."); - function storageRetryPolicy(options = {}) { - const retryPolicyType = options.retryPolicyType ?? DEFAULT_RETRY_OPTIONS.retryPolicyType; - const maxTries = options.maxTries ?? DEFAULT_RETRY_OPTIONS.maxTries; - const retryDelayInMs = options.retryDelayInMs ?? DEFAULT_RETRY_OPTIONS.retryDelayInMs; - const maxRetryDelayInMs = options.maxRetryDelayInMs ?? DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs; - const secondaryHost = options.secondaryHost ?? DEFAULT_RETRY_OPTIONS.secondaryHost; - const tryTimeoutInMs = options.tryTimeoutInMs ?? DEFAULT_RETRY_OPTIONS.tryTimeoutInMs; - function shouldRetry({ isPrimaryRetry, attempt, response, error: error3 }) { - if (attempt >= maxTries) { - log_js_1.logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${maxTries}, no further try.`); - return false; - } - if (error3) { - for (const retriableError of retriableErrors) { - if (error3.name.toUpperCase().includes(retriableError) || error3.message.toUpperCase().includes(retriableError) || error3.code && error3.code.toString().toUpperCase() === retriableError) { - log_js_1.logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); - return true; + var BlobItemInternal = { + serializedName: "BlobItemInternal", + xmlName: "Blob", + type: { + name: "Composite", + className: "BlobItemInternal", + modelProperties: { + name: { + serializedName: "Name", + xmlName: "Name", + type: { + name: "Composite", + className: "BlobName" } - } - if (error3?.code === "PARSE_ERROR" && error3?.message.startsWith(`Error "Error: Unclosed root tag`)) { - log_js_1.logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); - return true; - } - } - if (response || error3) { - const statusCode = response?.status ?? error3?.statusCode ?? 0; - if (!isPrimaryRetry && statusCode === 404) { - log_js_1.logger.info(`RetryPolicy: Secondary access with 404, will retry.`); - return true; - } - if (statusCode === 503 || statusCode === 500) { - log_js_1.logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); - return true; - } - } - if (response) { - if (response?.status >= 400) { - const copySourceError = response.headers.get(constants_js_1.HeaderConstants.X_MS_CopySourceErrorCode); - if (copySourceError !== void 0) { - switch (copySourceError) { - case "InternalError": - case "OperationTimedOut": - case "ServerBusy": - return true; - } + }, + deleted: { + serializedName: "Deleted", + required: true, + xmlName: "Deleted", + type: { + name: "Boolean" } - } - } - return false; - } - function calculateDelay(isPrimaryRetry, attempt) { - let delayTimeInMs = 0; - if (isPrimaryRetry) { - switch (retryPolicyType) { - case StorageRetryPolicyFactory_js_1.StorageRetryPolicyType.EXPONENTIAL: - delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * retryDelayInMs, maxRetryDelayInMs); - break; - case StorageRetryPolicyFactory_js_1.StorageRetryPolicyType.FIXED: - delayTimeInMs = retryDelayInMs; - break; - } - } else { - delayTimeInMs = Math.random() * 1e3; - } - log_js_1.logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); - return delayTimeInMs; - } - return { - name: exports2.storageRetryPolicyName, - async sendRequest(request3, next) { - if (tryTimeoutInMs) { - request3.url = (0, utils_common_js_1.setURLParameter)(request3.url, constants_js_1.URLConstants.Parameters.TIMEOUT, String(Math.floor(tryTimeoutInMs / 1e3))); - } - const primaryUrl = request3.url; - const secondaryUrl = secondaryHost ? (0, utils_common_js_1.setURLHost)(request3.url, secondaryHost) : void 0; - let secondaryHas404 = false; - let attempt = 1; - let retryAgain = true; - let response; - let error3; - while (retryAgain) { - const isPrimaryRetry = secondaryHas404 || !secondaryUrl || !["GET", "HEAD", "OPTIONS"].includes(request3.method) || attempt % 2 === 1; - request3.url = isPrimaryRetry ? primaryUrl : secondaryUrl; - response = void 0; - error3 = void 0; - try { - log_js_1.logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); - response = await next(request3); - secondaryHas404 = secondaryHas404 || !isPrimaryRetry && response.status === 404; - } catch (e) { - if ((0, core_rest_pipeline_1.isRestError)(e)) { - log_js_1.logger.error(`RetryPolicy: Caught error, message: ${e.message}, code: ${e.code}`); - error3 = e; - } else { - log_js_1.logger.error(`RetryPolicy: Caught error, message: ${(0, core_util_1.getErrorMessage)(e)}`); - throw e; - } + }, + snapshot: { + serializedName: "Snapshot", + required: true, + xmlName: "Snapshot", + type: { + name: "String" } - retryAgain = shouldRetry({ isPrimaryRetry, attempt, response, error: error3 }); - if (retryAgain) { - await (0, utils_common_js_1.delay)(calculateDelay(isPrimaryRetry, attempt), request3.abortSignal, RETRY_ABORT_ERROR); + }, + versionId: { + serializedName: "VersionId", + xmlName: "VersionId", + type: { + name: "String" } - attempt++; - } - if (response) { - return response; - } - throw error3 ?? new core_rest_pipeline_1.RestError("RetryPolicy failed without known error."); - } - }; - } - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/policies/StorageSharedKeyCredentialPolicyV2.js -var require_StorageSharedKeyCredentialPolicyV22 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/policies/StorageSharedKeyCredentialPolicyV2.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.storageSharedKeyCredentialPolicyName = void 0; - exports2.storageSharedKeyCredentialPolicy = storageSharedKeyCredentialPolicy; - var node_crypto_1 = require("node:crypto"); - var constants_js_1 = require_constants10(); - var utils_common_js_1 = require_utils_common(); - var SharedKeyComparator_js_1 = require_SharedKeyComparator(); - exports2.storageSharedKeyCredentialPolicyName = "storageSharedKeyCredentialPolicy"; - function storageSharedKeyCredentialPolicy(options) { - function signRequest(request3) { - request3.headers.set(constants_js_1.HeaderConstants.X_MS_DATE, (/* @__PURE__ */ new Date()).toUTCString()); - if (request3.body && (typeof request3.body === "string" || Buffer.isBuffer(request3.body)) && request3.body.length > 0) { - request3.headers.set(constants_js_1.HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request3.body)); - } - const stringToSign = [ - request3.method.toUpperCase(), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_LANGUAGE), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_ENCODING), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_LENGTH), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_MD5), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.CONTENT_TYPE), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.DATE), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_MODIFIED_SINCE), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_MATCH), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_NONE_MATCH), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.IF_UNMODIFIED_SINCE), - getHeaderValueToSign(request3, constants_js_1.HeaderConstants.RANGE) - ].join("\n") + "\n" + getCanonicalizedHeadersString(request3) + getCanonicalizedResourceString(request3); - const signature = (0, node_crypto_1.createHmac)("sha256", options.accountKey).update(stringToSign, "utf8").digest("base64"); - request3.headers.set(constants_js_1.HeaderConstants.AUTHORIZATION, `SharedKey ${options.accountName}:${signature}`); - } - function getHeaderValueToSign(request3, headerName) { - const value = request3.headers.get(headerName); - if (!value) { - return ""; - } - if (headerName === constants_js_1.HeaderConstants.CONTENT_LENGTH && value === "0") { - return ""; - } - return value; - } - function getCanonicalizedHeadersString(request3) { - let headersArray = []; - for (const [name, value] of request3.headers) { - if (name.toLowerCase().startsWith(constants_js_1.HeaderConstants.PREFIX_FOR_STORAGE)) { - headersArray.push({ name, value }); - } - } - headersArray.sort((a, b) => { - return (0, SharedKeyComparator_js_1.compareHeader)(a.name.toLowerCase(), b.name.toLowerCase()); - }); - headersArray = headersArray.filter((value, index2, array2) => { - if (index2 > 0 && value.name.toLowerCase() === array2[index2 - 1].name.toLowerCase()) { - return false; - } - return true; - }); - let canonicalizedHeadersStringToSign = ""; - headersArray.forEach((header) => { - canonicalizedHeadersStringToSign += `${header.name.toLowerCase().trimRight()}:${header.value.trimLeft()} -`; - }); - return canonicalizedHeadersStringToSign; - } - function getCanonicalizedResourceString(request3) { - const path30 = (0, utils_common_js_1.getURLPath)(request3.url) || "/"; - let canonicalizedResourceString = ""; - canonicalizedResourceString += `/${options.accountName}${path30}`; - const queries = (0, utils_common_js_1.getURLQueries)(request3.url); - const lowercaseQueries = {}; - if (queries) { - const queryKeys = []; - for (const key in queries) { - if (Object.prototype.hasOwnProperty.call(queries, key)) { - const lowercaseKey = key.toLowerCase(); - lowercaseQueries[lowercaseKey] = queries[key]; - queryKeys.push(lowercaseKey); + }, + isCurrentVersion: { + serializedName: "IsCurrentVersion", + xmlName: "IsCurrentVersion", + type: { + name: "Boolean" + } + }, + properties: { + serializedName: "Properties", + xmlName: "Properties", + type: { + name: "Composite", + className: "BlobPropertiesInternal" + } + }, + metadata: { + serializedName: "Metadata", + xmlName: "Metadata", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + }, + blobTags: { + serializedName: "BlobTags", + xmlName: "Tags", + type: { + name: "Composite", + className: "BlobTags" + } + }, + objectReplicationMetadata: { + serializedName: "ObjectReplicationMetadata", + xmlName: "OrMetadata", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + }, + hasVersionsOnly: { + serializedName: "HasVersionsOnly", + xmlName: "HasVersionsOnly", + type: { + name: "Boolean" } } - queryKeys.sort(); - for (const key of queryKeys) { - canonicalizedResourceString += ` -${key}:${decodeURIComponent(lowercaseQueries[key])}`; - } - } - return canonicalizedResourceString; - } - return { - name: exports2.storageSharedKeyCredentialPolicyName, - async sendRequest(request3, next) { - signRequest(request3); - return next(request3); - } - }; - } - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/policies/StorageBrowserPolicy.js -var require_StorageBrowserPolicy2 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/policies/StorageBrowserPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageBrowserPolicy = void 0; - var RequestPolicy_js_1 = require_RequestPolicy(); - var core_util_1 = require_commonjs4(); - var constants_js_1 = require_constants10(); - var utils_common_js_1 = require_utils_common(); - var StorageBrowserPolicy = class extends RequestPolicy_js_1.BaseRequestPolicy { - /** - * Creates an instance of StorageBrowserPolicy. - * @param nextPolicy - - * @param options - - */ - // The base class has a protected constructor. Adding a public one to enable constructing of this class. - /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ - constructor(nextPolicy, options) { - super(nextPolicy, options); - } - /** - * Sends out request. - * - * @param request - - */ - async sendRequest(request3) { - if (core_util_1.isNodeLike) { - return this._nextPolicy.sendRequest(request3); } - if (request3.method.toUpperCase() === "GET" || request3.method.toUpperCase() === "HEAD") { - request3.url = (0, utils_common_js_1.setURLParameter)(request3.url, constants_js_1.URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, (/* @__PURE__ */ new Date()).getTime().toString()); - } - request3.headers.remove(constants_js_1.HeaderConstants.COOKIE); - request3.headers.remove(constants_js_1.HeaderConstants.CONTENT_LENGTH); - return this._nextPolicy.sendRequest(request3); - } - }; - exports2.StorageBrowserPolicy = StorageBrowserPolicy; - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/StorageBrowserPolicyFactory.js -var require_StorageBrowserPolicyFactory2 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/StorageBrowserPolicyFactory.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageBrowserPolicyFactory = exports2.StorageBrowserPolicy = void 0; - var StorageBrowserPolicy_js_1 = require_StorageBrowserPolicy2(); - Object.defineProperty(exports2, "StorageBrowserPolicy", { enumerable: true, get: function() { - return StorageBrowserPolicy_js_1.StorageBrowserPolicy; - } }); - var StorageBrowserPolicyFactory = class { - /** - * Creates a StorageBrowserPolicyFactory object. - * - * @param nextPolicy - - * @param options - - */ - create(nextPolicy, options) { - return new StorageBrowserPolicy_js_1.StorageBrowserPolicy(nextPolicy, options); } }; - exports2.StorageBrowserPolicyFactory = StorageBrowserPolicyFactory; - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/policies/StorageCorrectContentLengthPolicy.js -var require_StorageCorrectContentLengthPolicy2 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/policies/StorageCorrectContentLengthPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.storageCorrectContentLengthPolicyName = void 0; - exports2.storageCorrectContentLengthPolicy = storageCorrectContentLengthPolicy; - var constants_js_1 = require_constants10(); - exports2.storageCorrectContentLengthPolicyName = "StorageCorrectContentLengthPolicy"; - function storageCorrectContentLengthPolicy() { - function correctContentLength(request3) { - if (request3.body && (typeof request3.body === "string" || Buffer.isBuffer(request3.body)) && request3.body.length > 0) { - request3.headers.set(constants_js_1.HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request3.body)); - } - } - return { - name: exports2.storageCorrectContentLengthPolicyName, - async sendRequest(request3, next) { - correctContentLength(request3); - return next(request3); + var BlobName = { + serializedName: "BlobName", + type: { + name: "Composite", + className: "BlobName", + modelProperties: { + encoded: { + serializedName: "Encoded", + xmlName: "Encoded", + xmlIsAttribute: true, + type: { + name: "Boolean" + } + }, + content: { + serializedName: "content", + xmlName: "content", + xmlIsMsText: true, + type: { + name: "String" + } + } } - }; - } - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/Pipeline.js -var require_Pipeline = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/Pipeline.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Pipeline = exports2.StorageOAuthScopes = void 0; - exports2.isPipelineLike = isPipelineLike; - exports2.newPipeline = newPipeline; - exports2.getCoreClientOptions = getCoreClientOptions; - exports2.getCredentialFromPipeline = getCredentialFromPipeline; - var core_http_compat_1 = require_commonjs9(); - var core_rest_pipeline_1 = require_commonjs6(); - var core_client_1 = require_commonjs8(); - var core_xml_1 = require_commonjs10(); - var core_auth_1 = require_commonjs7(); - var log_js_1 = require_log5(); - var StorageRetryPolicyFactory_js_1 = require_StorageRetryPolicyFactory(); - var StorageSharedKeyCredential_js_1 = require_StorageSharedKeyCredential(); - var AnonymousCredential_js_1 = require_AnonymousCredential(); - var constants_js_1 = require_constants10(); - Object.defineProperty(exports2, "StorageOAuthScopes", { enumerable: true, get: function() { - return constants_js_1.StorageOAuthScopes; - } }); - var storage_common_1 = require_commonjs13(); - var StorageBrowserPolicyV2_js_1 = require_StorageBrowserPolicyV22(); - var StorageRetryPolicyV2_js_1 = require_StorageRetryPolicyV22(); - var StorageSharedKeyCredentialPolicyV2_js_1 = require_StorageSharedKeyCredentialPolicyV22(); - var StorageBrowserPolicyFactory_js_1 = require_StorageBrowserPolicyFactory2(); - var StorageCorrectContentLengthPolicy_js_1 = require_StorageCorrectContentLengthPolicy2(); - function isPipelineLike(pipeline2) { - if (!pipeline2 || typeof pipeline2 !== "object") { - return false; - } - const castPipeline = pipeline2; - return Array.isArray(castPipeline.factories) && typeof castPipeline.options === "object" && typeof castPipeline.toServiceClientOptions === "function"; - } - var Pipeline = class { - /** - * A list of chained request policy factories. - */ - factories; - /** - * Configures pipeline logger and HTTP client. - */ - options; - /** - * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface. - * - * @param factories - - * @param options - - */ - constructor(factories, options = {}) { - this.factories = factories; - this.options = options; - } - /** - * Transfer Pipeline object to ServiceClientOptions object which is required by - * ServiceClient constructor. - * - * @returns The ServiceClientOptions object from this Pipeline. - */ - toServiceClientOptions() { - return { - httpClient: this.options.httpClient, - requestPolicyFactories: this.factories - }; } }; - exports2.Pipeline = Pipeline; - function newPipeline(credential, pipelineOptions = {}) { - if (!credential) { - credential = new AnonymousCredential_js_1.AnonymousCredential(); - } - const pipeline2 = new Pipeline([], pipelineOptions); - pipeline2._credential = credential; - return pipeline2; - } - function processDownlevelPipeline(pipeline2) { - const knownFactoryFunctions = [ - isAnonymousCredential, - isStorageSharedKeyCredential, - isCoreHttpBearerTokenFactory, - isStorageBrowserPolicyFactory, - isStorageRetryPolicyFactory, - isStorageTelemetryPolicyFactory, - isCoreHttpPolicyFactory - ]; - if (pipeline2.factories.length) { - const novelFactories = pipeline2.factories.filter((factory) => { - return !knownFactoryFunctions.some((knownFactory) => knownFactory(factory)); - }); - if (novelFactories.length) { - const hasInjector = novelFactories.some((factory) => isInjectorPolicyFactory(factory)); - return { - wrappedPolicies: (0, core_http_compat_1.createRequestPolicyFactoryPolicy)(novelFactories), - afterRetry: hasInjector - }; - } - } - return void 0; - } - function getCoreClientOptions(pipeline2) { - const { httpClient: v1Client, ...restOptions } = pipeline2.options; - let httpClient = pipeline2._coreHttpClient; - if (!httpClient) { - httpClient = v1Client ? (0, core_http_compat_1.convertHttpClient)(v1Client) : (0, storage_common_1.getCachedDefaultHttpClient)(); - pipeline2._coreHttpClient = httpClient; - } - let corePipeline = pipeline2._corePipeline; - if (!corePipeline) { - const packageDetails = `azsdk-js-azure-storage-blob/${constants_js_1.SDK_VERSION}`; - const userAgentPrefix = restOptions.userAgentOptions && restOptions.userAgentOptions.userAgentPrefix ? `${restOptions.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`; - corePipeline = (0, core_client_1.createClientPipeline)({ - ...restOptions, - loggingOptions: { - additionalAllowedHeaderNames: constants_js_1.StorageBlobLoggingAllowedHeaderNames, - additionalAllowedQueryParameters: constants_js_1.StorageBlobLoggingAllowedQueryParameters, - logger: log_js_1.logger.info + var BlobPropertiesInternal = { + serializedName: "BlobPropertiesInternal", + xmlName: "Properties", + type: { + name: "Composite", + className: "BlobPropertiesInternal", + modelProperties: { + createdOn: { + serializedName: "Creation-Time", + xmlName: "Creation-Time", + type: { + name: "DateTimeRfc1123" + } }, - userAgentOptions: { - userAgentPrefix + lastModified: { + serializedName: "Last-Modified", + required: true, + xmlName: "Last-Modified", + type: { + name: "DateTimeRfc1123" + } }, - serializationOptions: { - stringifyXML: core_xml_1.stringifyXML, - serializerOptions: { - xml: { - // Use customized XML char key of "#" so we can deserialize metadata - // with "_" key - xmlCharKey: "#" - } + etag: { + serializedName: "Etag", + required: true, + xmlName: "Etag", + type: { + name: "String" } }, - deserializationOptions: { - parseXML: core_xml_1.parseXML, - serializerOptions: { - xml: { - // Use customized XML char key of "#" so we can deserialize metadata - // with "_" key - xmlCharKey: "#" - } + contentLength: { + serializedName: "Content-Length", + xmlName: "Content-Length", + type: { + name: "Number" } - } - }); - corePipeline.removePolicy({ phase: "Retry" }); - corePipeline.removePolicy({ name: core_rest_pipeline_1.decompressResponsePolicyName }); - corePipeline.addPolicy((0, StorageCorrectContentLengthPolicy_js_1.storageCorrectContentLengthPolicy)()); - corePipeline.addPolicy((0, StorageRetryPolicyV2_js_1.storageRetryPolicy)(restOptions.retryOptions), { phase: "Retry" }); - corePipeline.addPolicy((0, storage_common_1.storageRequestFailureDetailsParserPolicy)()); - corePipeline.addPolicy((0, StorageBrowserPolicyV2_js_1.storageBrowserPolicy)()); - const downlevelResults = processDownlevelPipeline(pipeline2); - if (downlevelResults) { - corePipeline.addPolicy(downlevelResults.wrappedPolicies, downlevelResults.afterRetry ? { afterPhase: "Retry" } : void 0); - } - const credential = getCredentialFromPipeline(pipeline2); - if ((0, core_auth_1.isTokenCredential)(credential)) { - corePipeline.addPolicy((0, core_rest_pipeline_1.bearerTokenAuthenticationPolicy)({ - credential, - scopes: restOptions.audience ?? constants_js_1.StorageOAuthScopes, - challengeCallbacks: { authorizeRequestOnChallenge: core_client_1.authorizeRequestOnTenantChallenge } - }), { phase: "Sign" }); - } else if (credential instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential) { - corePipeline.addPolicy((0, StorageSharedKeyCredentialPolicyV2_js_1.storageSharedKeyCredentialPolicy)({ - accountName: credential.accountName, - accountKey: credential.accountKey - }), { phase: "Sign" }); - } - pipeline2._corePipeline = corePipeline; - } - return { - ...restOptions, - allowInsecureConnection: true, - httpClient, - pipeline: corePipeline - }; - } - function getCredentialFromPipeline(pipeline2) { - if (pipeline2._credential) { - return pipeline2._credential; - } - let credential = new AnonymousCredential_js_1.AnonymousCredential(); - for (const factory of pipeline2.factories) { - if ((0, core_auth_1.isTokenCredential)(factory.credential)) { - credential = factory.credential; - } else if (isStorageSharedKeyCredential(factory)) { - return factory; - } - } - return credential; - } - function isStorageSharedKeyCredential(factory) { - if (factory instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential) { - return true; - } - return factory.constructor.name === "StorageSharedKeyCredential"; - } - function isAnonymousCredential(factory) { - if (factory instanceof AnonymousCredential_js_1.AnonymousCredential) { - return true; - } - return factory.constructor.name === "AnonymousCredential"; - } - function isCoreHttpBearerTokenFactory(factory) { - return (0, core_auth_1.isTokenCredential)(factory.credential); - } - function isStorageBrowserPolicyFactory(factory) { - if (factory instanceof StorageBrowserPolicyFactory_js_1.StorageBrowserPolicyFactory) { - return true; - } - return factory.constructor.name === "StorageBrowserPolicyFactory"; - } - function isStorageRetryPolicyFactory(factory) { - if (factory instanceof StorageRetryPolicyFactory_js_1.StorageRetryPolicyFactory) { - return true; - } - return factory.constructor.name === "StorageRetryPolicyFactory"; - } - function isStorageTelemetryPolicyFactory(factory) { - return factory.constructor.name === "TelemetryPolicyFactory"; - } - function isInjectorPolicyFactory(factory) { - return factory.constructor.name === "InjectorPolicyFactory"; - } - function isCoreHttpPolicyFactory(factory) { - const knownPolicies = [ - "GenerateClientRequestIdPolicy", - "TracingPolicy", - "LogPolicy", - "ProxyPolicy", - "DisableResponseDecompressionPolicy", - "KeepAlivePolicy", - "DeserializationPolicy" - ]; - const mockHttpClient = { - sendRequest: async (request3) => { - return { - request: request3, - headers: request3.headers.clone(), - status: 500 - }; - } - }; - const mockRequestPolicyOptions = { - log(_logLevel, _message) { - }, - shouldLog(_logLevel) { - return false; - } - }; - const policyInstance = factory.create(mockHttpClient, mockRequestPolicyOptions); - const policyName = policyInstance.constructor.name; - return knownPolicies.some((knownPolicyName) => { - return policyName.startsWith(knownPolicyName); - }); - } - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/models/index.js -var require_models = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/models/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.KnownStorageErrorCode = exports2.KnownBlobExpiryOptions = exports2.KnownFileShareTokenIntent = exports2.KnownEncryptionAlgorithmType = void 0; - var KnownEncryptionAlgorithmType; - (function(KnownEncryptionAlgorithmType2) { - KnownEncryptionAlgorithmType2["AES256"] = "AES256"; - })(KnownEncryptionAlgorithmType || (exports2.KnownEncryptionAlgorithmType = KnownEncryptionAlgorithmType = {})); - var KnownFileShareTokenIntent; - (function(KnownFileShareTokenIntent2) { - KnownFileShareTokenIntent2["Backup"] = "backup"; - })(KnownFileShareTokenIntent || (exports2.KnownFileShareTokenIntent = KnownFileShareTokenIntent = {})); - var KnownBlobExpiryOptions; - (function(KnownBlobExpiryOptions2) { - KnownBlobExpiryOptions2["NeverExpire"] = "NeverExpire"; - KnownBlobExpiryOptions2["RelativeToCreation"] = "RelativeToCreation"; - KnownBlobExpiryOptions2["RelativeToNow"] = "RelativeToNow"; - KnownBlobExpiryOptions2["Absolute"] = "Absolute"; - })(KnownBlobExpiryOptions || (exports2.KnownBlobExpiryOptions = KnownBlobExpiryOptions = {})); - var KnownStorageErrorCode; - (function(KnownStorageErrorCode2) { - KnownStorageErrorCode2["AccountAlreadyExists"] = "AccountAlreadyExists"; - KnownStorageErrorCode2["AccountBeingCreated"] = "AccountBeingCreated"; - KnownStorageErrorCode2["AccountIsDisabled"] = "AccountIsDisabled"; - KnownStorageErrorCode2["AuthenticationFailed"] = "AuthenticationFailed"; - KnownStorageErrorCode2["AuthorizationFailure"] = "AuthorizationFailure"; - KnownStorageErrorCode2["ConditionHeadersNotSupported"] = "ConditionHeadersNotSupported"; - KnownStorageErrorCode2["ConditionNotMet"] = "ConditionNotMet"; - KnownStorageErrorCode2["EmptyMetadataKey"] = "EmptyMetadataKey"; - KnownStorageErrorCode2["InsufficientAccountPermissions"] = "InsufficientAccountPermissions"; - KnownStorageErrorCode2["InternalError"] = "InternalError"; - KnownStorageErrorCode2["InvalidAuthenticationInfo"] = "InvalidAuthenticationInfo"; - KnownStorageErrorCode2["InvalidHeaderValue"] = "InvalidHeaderValue"; - KnownStorageErrorCode2["InvalidHttpVerb"] = "InvalidHttpVerb"; - KnownStorageErrorCode2["InvalidInput"] = "InvalidInput"; - KnownStorageErrorCode2["InvalidMd5"] = "InvalidMd5"; - KnownStorageErrorCode2["InvalidMetadata"] = "InvalidMetadata"; - KnownStorageErrorCode2["InvalidQueryParameterValue"] = "InvalidQueryParameterValue"; - KnownStorageErrorCode2["InvalidRange"] = "InvalidRange"; - KnownStorageErrorCode2["InvalidResourceName"] = "InvalidResourceName"; - KnownStorageErrorCode2["InvalidUri"] = "InvalidUri"; - KnownStorageErrorCode2["InvalidXmlDocument"] = "InvalidXmlDocument"; - KnownStorageErrorCode2["InvalidXmlNodeValue"] = "InvalidXmlNodeValue"; - KnownStorageErrorCode2["Md5Mismatch"] = "Md5Mismatch"; - KnownStorageErrorCode2["MetadataTooLarge"] = "MetadataTooLarge"; - KnownStorageErrorCode2["MissingContentLengthHeader"] = "MissingContentLengthHeader"; - KnownStorageErrorCode2["MissingRequiredQueryParameter"] = "MissingRequiredQueryParameter"; - KnownStorageErrorCode2["MissingRequiredHeader"] = "MissingRequiredHeader"; - KnownStorageErrorCode2["MissingRequiredXmlNode"] = "MissingRequiredXmlNode"; - KnownStorageErrorCode2["MultipleConditionHeadersNotSupported"] = "MultipleConditionHeadersNotSupported"; - KnownStorageErrorCode2["OperationTimedOut"] = "OperationTimedOut"; - KnownStorageErrorCode2["OutOfRangeInput"] = "OutOfRangeInput"; - KnownStorageErrorCode2["OutOfRangeQueryParameterValue"] = "OutOfRangeQueryParameterValue"; - KnownStorageErrorCode2["RequestBodyTooLarge"] = "RequestBodyTooLarge"; - KnownStorageErrorCode2["ResourceTypeMismatch"] = "ResourceTypeMismatch"; - KnownStorageErrorCode2["RequestUrlFailedToParse"] = "RequestUrlFailedToParse"; - KnownStorageErrorCode2["ResourceAlreadyExists"] = "ResourceAlreadyExists"; - KnownStorageErrorCode2["ResourceNotFound"] = "ResourceNotFound"; - KnownStorageErrorCode2["ServerBusy"] = "ServerBusy"; - KnownStorageErrorCode2["UnsupportedHeader"] = "UnsupportedHeader"; - KnownStorageErrorCode2["UnsupportedXmlNode"] = "UnsupportedXmlNode"; - KnownStorageErrorCode2["UnsupportedQueryParameter"] = "UnsupportedQueryParameter"; - KnownStorageErrorCode2["UnsupportedHttpVerb"] = "UnsupportedHttpVerb"; - KnownStorageErrorCode2["AppendPositionConditionNotMet"] = "AppendPositionConditionNotMet"; - KnownStorageErrorCode2["BlobAlreadyExists"] = "BlobAlreadyExists"; - KnownStorageErrorCode2["BlobImmutableDueToPolicy"] = "BlobImmutableDueToPolicy"; - KnownStorageErrorCode2["BlobNotFound"] = "BlobNotFound"; - KnownStorageErrorCode2["BlobOverwritten"] = "BlobOverwritten"; - KnownStorageErrorCode2["BlobTierInadequateForContentLength"] = "BlobTierInadequateForContentLength"; - KnownStorageErrorCode2["BlobUsesCustomerSpecifiedEncryption"] = "BlobUsesCustomerSpecifiedEncryption"; - KnownStorageErrorCode2["BlockCountExceedsLimit"] = "BlockCountExceedsLimit"; - KnownStorageErrorCode2["BlockListTooLong"] = "BlockListTooLong"; - KnownStorageErrorCode2["CannotChangeToLowerTier"] = "CannotChangeToLowerTier"; - KnownStorageErrorCode2["CannotVerifyCopySource"] = "CannotVerifyCopySource"; - KnownStorageErrorCode2["ContainerAlreadyExists"] = "ContainerAlreadyExists"; - KnownStorageErrorCode2["ContainerBeingDeleted"] = "ContainerBeingDeleted"; - KnownStorageErrorCode2["ContainerDisabled"] = "ContainerDisabled"; - KnownStorageErrorCode2["ContainerNotFound"] = "ContainerNotFound"; - KnownStorageErrorCode2["ContentLengthLargerThanTierLimit"] = "ContentLengthLargerThanTierLimit"; - KnownStorageErrorCode2["CopyAcrossAccountsNotSupported"] = "CopyAcrossAccountsNotSupported"; - KnownStorageErrorCode2["CopyIdMismatch"] = "CopyIdMismatch"; - KnownStorageErrorCode2["FeatureVersionMismatch"] = "FeatureVersionMismatch"; - KnownStorageErrorCode2["IncrementalCopyBlobMismatch"] = "IncrementalCopyBlobMismatch"; - KnownStorageErrorCode2["IncrementalCopyOfEarlierVersionSnapshotNotAllowed"] = "IncrementalCopyOfEarlierVersionSnapshotNotAllowed"; - KnownStorageErrorCode2["IncrementalCopySourceMustBeSnapshot"] = "IncrementalCopySourceMustBeSnapshot"; - KnownStorageErrorCode2["InfiniteLeaseDurationRequired"] = "InfiniteLeaseDurationRequired"; - KnownStorageErrorCode2["InvalidBlobOrBlock"] = "InvalidBlobOrBlock"; - KnownStorageErrorCode2["InvalidBlobTier"] = "InvalidBlobTier"; - KnownStorageErrorCode2["InvalidBlobType"] = "InvalidBlobType"; - KnownStorageErrorCode2["InvalidBlockId"] = "InvalidBlockId"; - KnownStorageErrorCode2["InvalidBlockList"] = "InvalidBlockList"; - KnownStorageErrorCode2["InvalidOperation"] = "InvalidOperation"; - KnownStorageErrorCode2["InvalidPageRange"] = "InvalidPageRange"; - KnownStorageErrorCode2["InvalidSourceBlobType"] = "InvalidSourceBlobType"; - KnownStorageErrorCode2["InvalidSourceBlobUrl"] = "InvalidSourceBlobUrl"; - KnownStorageErrorCode2["InvalidVersionForPageBlobOperation"] = "InvalidVersionForPageBlobOperation"; - KnownStorageErrorCode2["LeaseAlreadyPresent"] = "LeaseAlreadyPresent"; - KnownStorageErrorCode2["LeaseAlreadyBroken"] = "LeaseAlreadyBroken"; - KnownStorageErrorCode2["LeaseIdMismatchWithBlobOperation"] = "LeaseIdMismatchWithBlobOperation"; - KnownStorageErrorCode2["LeaseIdMismatchWithContainerOperation"] = "LeaseIdMismatchWithContainerOperation"; - KnownStorageErrorCode2["LeaseIdMismatchWithLeaseOperation"] = "LeaseIdMismatchWithLeaseOperation"; - KnownStorageErrorCode2["LeaseIdMissing"] = "LeaseIdMissing"; - KnownStorageErrorCode2["LeaseIsBreakingAndCannotBeAcquired"] = "LeaseIsBreakingAndCannotBeAcquired"; - KnownStorageErrorCode2["LeaseIsBreakingAndCannotBeChanged"] = "LeaseIsBreakingAndCannotBeChanged"; - KnownStorageErrorCode2["LeaseIsBrokenAndCannotBeRenewed"] = "LeaseIsBrokenAndCannotBeRenewed"; - KnownStorageErrorCode2["LeaseLost"] = "LeaseLost"; - KnownStorageErrorCode2["LeaseNotPresentWithBlobOperation"] = "LeaseNotPresentWithBlobOperation"; - KnownStorageErrorCode2["LeaseNotPresentWithContainerOperation"] = "LeaseNotPresentWithContainerOperation"; - KnownStorageErrorCode2["LeaseNotPresentWithLeaseOperation"] = "LeaseNotPresentWithLeaseOperation"; - KnownStorageErrorCode2["MaxBlobSizeConditionNotMet"] = "MaxBlobSizeConditionNotMet"; - KnownStorageErrorCode2["NoAuthenticationInformation"] = "NoAuthenticationInformation"; - KnownStorageErrorCode2["NoPendingCopyOperation"] = "NoPendingCopyOperation"; - KnownStorageErrorCode2["OperationNotAllowedOnIncrementalCopyBlob"] = "OperationNotAllowedOnIncrementalCopyBlob"; - KnownStorageErrorCode2["PendingCopyOperation"] = "PendingCopyOperation"; - KnownStorageErrorCode2["PreviousSnapshotCannotBeNewer"] = "PreviousSnapshotCannotBeNewer"; - KnownStorageErrorCode2["PreviousSnapshotNotFound"] = "PreviousSnapshotNotFound"; - KnownStorageErrorCode2["PreviousSnapshotOperationNotSupported"] = "PreviousSnapshotOperationNotSupported"; - KnownStorageErrorCode2["SequenceNumberConditionNotMet"] = "SequenceNumberConditionNotMet"; - KnownStorageErrorCode2["SequenceNumberIncrementTooLarge"] = "SequenceNumberIncrementTooLarge"; - KnownStorageErrorCode2["SnapshotCountExceeded"] = "SnapshotCountExceeded"; - KnownStorageErrorCode2["SnapshotOperationRateExceeded"] = "SnapshotOperationRateExceeded"; - KnownStorageErrorCode2["SnapshotsPresent"] = "SnapshotsPresent"; - KnownStorageErrorCode2["SourceConditionNotMet"] = "SourceConditionNotMet"; - KnownStorageErrorCode2["SystemInUse"] = "SystemInUse"; - KnownStorageErrorCode2["TargetConditionNotMet"] = "TargetConditionNotMet"; - KnownStorageErrorCode2["UnauthorizedBlobOverwrite"] = "UnauthorizedBlobOverwrite"; - KnownStorageErrorCode2["BlobBeingRehydrated"] = "BlobBeingRehydrated"; - KnownStorageErrorCode2["BlobArchived"] = "BlobArchived"; - KnownStorageErrorCode2["BlobNotArchived"] = "BlobNotArchived"; - KnownStorageErrorCode2["AuthorizationSourceIPMismatch"] = "AuthorizationSourceIPMismatch"; - KnownStorageErrorCode2["AuthorizationProtocolMismatch"] = "AuthorizationProtocolMismatch"; - KnownStorageErrorCode2["AuthorizationPermissionMismatch"] = "AuthorizationPermissionMismatch"; - KnownStorageErrorCode2["AuthorizationServiceMismatch"] = "AuthorizationServiceMismatch"; - KnownStorageErrorCode2["AuthorizationResourceTypeMismatch"] = "AuthorizationResourceTypeMismatch"; - KnownStorageErrorCode2["BlobAccessTierNotSupportedForAccountType"] = "BlobAccessTierNotSupportedForAccountType"; - })(KnownStorageErrorCode || (exports2.KnownStorageErrorCode = KnownStorageErrorCode = {})); - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/models/mappers.js -var require_mappers = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/models/mappers.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServiceGetUserDelegationKeyHeaders = exports2.ServiceListContainersSegmentExceptionHeaders = exports2.ServiceListContainersSegmentHeaders = exports2.ServiceGetStatisticsExceptionHeaders = exports2.ServiceGetStatisticsHeaders = exports2.ServiceGetPropertiesExceptionHeaders = exports2.ServiceGetPropertiesHeaders = exports2.ServiceSetPropertiesExceptionHeaders = exports2.ServiceSetPropertiesHeaders = exports2.ArrowField = exports2.ArrowConfiguration = exports2.JsonTextConfiguration = exports2.DelimitedTextConfiguration = exports2.QueryFormat = exports2.QuerySerialization = exports2.QueryRequest = exports2.ClearRange = exports2.PageRange = exports2.PageList = exports2.Block = exports2.BlockList = exports2.BlockLookupList = exports2.BlobPrefix = exports2.BlobHierarchyListSegment = exports2.ListBlobsHierarchySegmentResponse = exports2.BlobPropertiesInternal = exports2.BlobName = exports2.BlobItemInternal = exports2.BlobFlatListSegment = exports2.ListBlobsFlatSegmentResponse = exports2.AccessPolicy = exports2.SignedIdentifier = exports2.BlobTag = exports2.BlobTags = exports2.FilterBlobItem = exports2.FilterBlobSegment = exports2.UserDelegationKey = exports2.KeyInfo = exports2.ContainerProperties = exports2.ContainerItem = exports2.ListContainersSegmentResponse = exports2.GeoReplication = exports2.BlobServiceStatistics = exports2.StorageError = exports2.StaticWebsite = exports2.CorsRule = exports2.Metrics = exports2.RetentionPolicy = exports2.Logging = exports2.BlobServiceProperties = void 0; - exports2.BlobUndeleteHeaders = exports2.BlobDeleteExceptionHeaders = exports2.BlobDeleteHeaders = exports2.BlobGetPropertiesExceptionHeaders = exports2.BlobGetPropertiesHeaders = exports2.BlobDownloadExceptionHeaders = exports2.BlobDownloadHeaders = exports2.ContainerGetAccountInfoExceptionHeaders = exports2.ContainerGetAccountInfoHeaders = exports2.ContainerListBlobHierarchySegmentExceptionHeaders = exports2.ContainerListBlobHierarchySegmentHeaders = exports2.ContainerListBlobFlatSegmentExceptionHeaders = exports2.ContainerListBlobFlatSegmentHeaders = exports2.ContainerChangeLeaseExceptionHeaders = exports2.ContainerChangeLeaseHeaders = exports2.ContainerBreakLeaseExceptionHeaders = exports2.ContainerBreakLeaseHeaders = exports2.ContainerRenewLeaseExceptionHeaders = exports2.ContainerRenewLeaseHeaders = exports2.ContainerReleaseLeaseExceptionHeaders = exports2.ContainerReleaseLeaseHeaders = exports2.ContainerAcquireLeaseExceptionHeaders = exports2.ContainerAcquireLeaseHeaders = exports2.ContainerFilterBlobsExceptionHeaders = exports2.ContainerFilterBlobsHeaders = exports2.ContainerSubmitBatchExceptionHeaders = exports2.ContainerSubmitBatchHeaders = exports2.ContainerRenameExceptionHeaders = exports2.ContainerRenameHeaders = exports2.ContainerRestoreExceptionHeaders = exports2.ContainerRestoreHeaders = exports2.ContainerSetAccessPolicyExceptionHeaders = exports2.ContainerSetAccessPolicyHeaders = exports2.ContainerGetAccessPolicyExceptionHeaders = exports2.ContainerGetAccessPolicyHeaders = exports2.ContainerSetMetadataExceptionHeaders = exports2.ContainerSetMetadataHeaders = exports2.ContainerDeleteExceptionHeaders = exports2.ContainerDeleteHeaders = exports2.ContainerGetPropertiesExceptionHeaders = exports2.ContainerGetPropertiesHeaders = exports2.ContainerCreateExceptionHeaders = exports2.ContainerCreateHeaders = exports2.ServiceFilterBlobsExceptionHeaders = exports2.ServiceFilterBlobsHeaders = exports2.ServiceSubmitBatchExceptionHeaders = exports2.ServiceSubmitBatchHeaders = exports2.ServiceGetAccountInfoExceptionHeaders = exports2.ServiceGetAccountInfoHeaders = exports2.ServiceGetUserDelegationKeyExceptionHeaders = void 0; - exports2.PageBlobGetPageRangesHeaders = exports2.PageBlobUploadPagesFromURLExceptionHeaders = exports2.PageBlobUploadPagesFromURLHeaders = exports2.PageBlobClearPagesExceptionHeaders = exports2.PageBlobClearPagesHeaders = exports2.PageBlobUploadPagesExceptionHeaders = exports2.PageBlobUploadPagesHeaders = exports2.PageBlobCreateExceptionHeaders = exports2.PageBlobCreateHeaders = exports2.BlobSetTagsExceptionHeaders = exports2.BlobSetTagsHeaders = exports2.BlobGetTagsExceptionHeaders = exports2.BlobGetTagsHeaders = exports2.BlobQueryExceptionHeaders = exports2.BlobQueryHeaders = exports2.BlobGetAccountInfoExceptionHeaders = exports2.BlobGetAccountInfoHeaders = exports2.BlobSetTierExceptionHeaders = exports2.BlobSetTierHeaders = exports2.BlobAbortCopyFromURLExceptionHeaders = exports2.BlobAbortCopyFromURLHeaders = exports2.BlobCopyFromURLExceptionHeaders = exports2.BlobCopyFromURLHeaders = exports2.BlobStartCopyFromURLExceptionHeaders = exports2.BlobStartCopyFromURLHeaders = exports2.BlobCreateSnapshotExceptionHeaders = exports2.BlobCreateSnapshotHeaders = exports2.BlobBreakLeaseExceptionHeaders = exports2.BlobBreakLeaseHeaders = exports2.BlobChangeLeaseExceptionHeaders = exports2.BlobChangeLeaseHeaders = exports2.BlobRenewLeaseExceptionHeaders = exports2.BlobRenewLeaseHeaders = exports2.BlobReleaseLeaseExceptionHeaders = exports2.BlobReleaseLeaseHeaders = exports2.BlobAcquireLeaseExceptionHeaders = exports2.BlobAcquireLeaseHeaders = exports2.BlobSetMetadataExceptionHeaders = exports2.BlobSetMetadataHeaders = exports2.BlobSetLegalHoldExceptionHeaders = exports2.BlobSetLegalHoldHeaders = exports2.BlobDeleteImmutabilityPolicyExceptionHeaders = exports2.BlobDeleteImmutabilityPolicyHeaders = exports2.BlobSetImmutabilityPolicyExceptionHeaders = exports2.BlobSetImmutabilityPolicyHeaders = exports2.BlobSetHttpHeadersExceptionHeaders = exports2.BlobSetHttpHeadersHeaders = exports2.BlobSetExpiryExceptionHeaders = exports2.BlobSetExpiryHeaders = exports2.BlobUndeleteExceptionHeaders = void 0; - exports2.BlockBlobGetBlockListExceptionHeaders = exports2.BlockBlobGetBlockListHeaders = exports2.BlockBlobCommitBlockListExceptionHeaders = exports2.BlockBlobCommitBlockListHeaders = exports2.BlockBlobStageBlockFromURLExceptionHeaders = exports2.BlockBlobStageBlockFromURLHeaders = exports2.BlockBlobStageBlockExceptionHeaders = exports2.BlockBlobStageBlockHeaders = exports2.BlockBlobPutBlobFromUrlExceptionHeaders = exports2.BlockBlobPutBlobFromUrlHeaders = exports2.BlockBlobUploadExceptionHeaders = exports2.BlockBlobUploadHeaders = exports2.AppendBlobSealExceptionHeaders = exports2.AppendBlobSealHeaders = exports2.AppendBlobAppendBlockFromUrlExceptionHeaders = exports2.AppendBlobAppendBlockFromUrlHeaders = exports2.AppendBlobAppendBlockExceptionHeaders = exports2.AppendBlobAppendBlockHeaders = exports2.AppendBlobCreateExceptionHeaders = exports2.AppendBlobCreateHeaders = exports2.PageBlobCopyIncrementalExceptionHeaders = exports2.PageBlobCopyIncrementalHeaders = exports2.PageBlobUpdateSequenceNumberExceptionHeaders = exports2.PageBlobUpdateSequenceNumberHeaders = exports2.PageBlobResizeExceptionHeaders = exports2.PageBlobResizeHeaders = exports2.PageBlobGetPageRangesDiffExceptionHeaders = exports2.PageBlobGetPageRangesDiffHeaders = exports2.PageBlobGetPageRangesExceptionHeaders = void 0; - exports2.BlobServiceProperties = { - serializedName: "BlobServiceProperties", - xmlName: "StorageServiceProperties", - type: { - name: "Composite", - className: "BlobServiceProperties", - modelProperties: { - blobAnalyticsLogging: { - serializedName: "Logging", - xmlName: "Logging", + }, + contentType: { + serializedName: "Content-Type", + xmlName: "Content-Type", type: { - name: "Composite", - className: "Logging" + name: "String" } }, - hourMetrics: { - serializedName: "HourMetrics", - xmlName: "HourMetrics", + contentEncoding: { + serializedName: "Content-Encoding", + xmlName: "Content-Encoding", type: { - name: "Composite", - className: "Metrics" + name: "String" } }, - minuteMetrics: { - serializedName: "MinuteMetrics", - xmlName: "MinuteMetrics", + contentLanguage: { + serializedName: "Content-Language", + xmlName: "Content-Language", type: { - name: "Composite", - className: "Metrics" + name: "String" } }, - cors: { - serializedName: "Cors", - xmlName: "Cors", - xmlIsWrapped: true, - xmlElementName: "CorsRule", + contentMD5: { + serializedName: "Content-MD5", + xmlName: "Content-MD5", type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "CorsRule" - } - } + name: "ByteArray" } }, - defaultServiceVersion: { - serializedName: "DefaultServiceVersion", - xmlName: "DefaultServiceVersion", + contentDisposition: { + serializedName: "Content-Disposition", + xmlName: "Content-Disposition", type: { name: "String" } }, - deleteRetentionPolicy: { - serializedName: "DeleteRetentionPolicy", - xmlName: "DeleteRetentionPolicy", + cacheControl: { + serializedName: "Cache-Control", + xmlName: "Cache-Control", type: { - name: "Composite", - className: "RetentionPolicy" + name: "String" } }, - staticWebsite: { - serializedName: "StaticWebsite", - xmlName: "StaticWebsite", + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", type: { - name: "Composite", - className: "StaticWebsite" + name: "Number" } - } - } - } - }; - exports2.Logging = { - serializedName: "Logging", - type: { - name: "Composite", - className: "Logging", - modelProperties: { - version: { - serializedName: "Version", - required: true, - xmlName: "Version", + }, + blobType: { + serializedName: "BlobType", + xmlName: "BlobType", type: { - name: "String" + name: "Enum", + allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"] } }, - deleteProperty: { - serializedName: "Delete", - required: true, - xmlName: "Delete", + leaseStatus: { + serializedName: "LeaseStatus", + xmlName: "LeaseStatus", type: { - name: "Boolean" + name: "Enum", + allowedValues: ["locked", "unlocked"] } }, - read: { - serializedName: "Read", - required: true, - xmlName: "Read", + leaseState: { + serializedName: "LeaseState", + xmlName: "LeaseState", type: { - name: "Boolean" + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] } }, - write: { - serializedName: "Write", - required: true, - xmlName: "Write", + leaseDuration: { + serializedName: "LeaseDuration", + xmlName: "LeaseDuration", type: { - name: "Boolean" + name: "Enum", + allowedValues: ["infinite", "fixed"] } }, - retentionPolicy: { - serializedName: "RetentionPolicy", - xmlName: "RetentionPolicy", + copyId: { + serializedName: "CopyId", + xmlName: "CopyId", type: { - name: "Composite", - className: "RetentionPolicy" + name: "String" } - } - } - } - }; - exports2.RetentionPolicy = { - serializedName: "RetentionPolicy", - type: { - name: "Composite", - className: "RetentionPolicy", - modelProperties: { - enabled: { - serializedName: "Enabled", - required: true, - xmlName: "Enabled", + }, + copyStatus: { + serializedName: "CopyStatus", + xmlName: "CopyStatus", type: { - name: "Boolean" + name: "Enum", + allowedValues: ["pending", "success", "aborted", "failed"] } }, - days: { - constraints: { - InclusiveMinimum: 1 - }, - serializedName: "Days", - xmlName: "Days", + copySource: { + serializedName: "CopySource", + xmlName: "CopySource", type: { - name: "Number" + name: "String" } - } - } - } - }; - exports2.Metrics = { - serializedName: "Metrics", - type: { - name: "Composite", - className: "Metrics", - modelProperties: { - version: { - serializedName: "Version", - xmlName: "Version", + }, + copyProgress: { + serializedName: "CopyProgress", + xmlName: "CopyProgress", type: { name: "String" } }, - enabled: { - serializedName: "Enabled", - required: true, - xmlName: "Enabled", + copyCompletedOn: { + serializedName: "CopyCompletionTime", + xmlName: "CopyCompletionTime", type: { - name: "Boolean" + name: "DateTimeRfc1123" } }, - includeAPIs: { - serializedName: "IncludeAPIs", - xmlName: "IncludeAPIs", + copyStatusDescription: { + serializedName: "CopyStatusDescription", + xmlName: "CopyStatusDescription", type: { - name: "Boolean" + name: "String" } }, - retentionPolicy: { - serializedName: "RetentionPolicy", - xmlName: "RetentionPolicy", + serverEncrypted: { + serializedName: "ServerEncrypted", + xmlName: "ServerEncrypted", type: { - name: "Composite", - className: "RetentionPolicy" + name: "Boolean" } - } - } - } - }; - exports2.CorsRule = { - serializedName: "CorsRule", - type: { - name: "Composite", - className: "CorsRule", - modelProperties: { - allowedOrigins: { - serializedName: "AllowedOrigins", - required: true, - xmlName: "AllowedOrigins", + }, + incrementalCopy: { + serializedName: "IncrementalCopy", + xmlName: "IncrementalCopy", type: { - name: "String" + name: "Boolean" } }, - allowedMethods: { - serializedName: "AllowedMethods", - required: true, - xmlName: "AllowedMethods", + destinationSnapshot: { + serializedName: "DestinationSnapshot", + xmlName: "DestinationSnapshot", type: { name: "String" } }, - allowedHeaders: { - serializedName: "AllowedHeaders", - required: true, - xmlName: "AllowedHeaders", + deletedOn: { + serializedName: "DeletedTime", + xmlName: "DeletedTime", type: { - name: "String" + name: "DateTimeRfc1123" } }, - exposedHeaders: { - serializedName: "ExposedHeaders", - required: true, - xmlName: "ExposedHeaders", + remainingRetentionDays: { + serializedName: "RemainingRetentionDays", + xmlName: "RemainingRetentionDays", type: { - name: "String" + name: "Number" } }, - maxAgeInSeconds: { - constraints: { - InclusiveMinimum: 0 - }, - serializedName: "MaxAgeInSeconds", - required: true, - xmlName: "MaxAgeInSeconds", + accessTier: { + serializedName: "AccessTier", + xmlName: "AccessTier", type: { - name: "Number" + name: "Enum", + allowedValues: [ + "P4", + "P6", + "P10", + "P15", + "P20", + "P30", + "P40", + "P50", + "P60", + "P70", + "P80", + "Hot", + "Cool", + "Archive", + "Cold", + "Smart" + ] } - } - } - } - }; - exports2.StaticWebsite = { - serializedName: "StaticWebsite", - type: { - name: "Composite", - className: "StaticWebsite", - modelProperties: { - enabled: { - serializedName: "Enabled", - required: true, - xmlName: "Enabled", + }, + accessTierInferred: { + serializedName: "AccessTierInferred", + xmlName: "AccessTierInferred", type: { name: "Boolean" } }, - indexDocument: { - serializedName: "IndexDocument", - xmlName: "IndexDocument", + archiveStatus: { + serializedName: "ArchiveStatus", + xmlName: "ArchiveStatus", type: { - name: "String" + name: "Enum", + allowedValues: [ + "rehydrate-pending-to-hot", + "rehydrate-pending-to-cool", + "rehydrate-pending-to-cold", + "rehydrate-pending-to-smart" + ] } }, - errorDocument404Path: { - serializedName: "ErrorDocument404Path", - xmlName: "ErrorDocument404Path", + smartAccessTier: { + serializedName: "SmartAccessTier", + xmlName: "SmartAccessTier", type: { - name: "String" + name: "Enum", + allowedValues: [ + "P4", + "P6", + "P10", + "P15", + "P20", + "P30", + "P40", + "P50", + "P60", + "P70", + "P80", + "Hot", + "Cool", + "Archive", + "Cold", + "Smart" + ] } }, - defaultIndexDocumentPath: { - serializedName: "DefaultIndexDocumentPath", - xmlName: "DefaultIndexDocumentPath", + customerProvidedKeySha256: { + serializedName: "CustomerProvidedKeySha256", + xmlName: "CustomerProvidedKeySha256", type: { name: "String" } - } - } - } - }; - exports2.StorageError = { - serializedName: "StorageError", - type: { - name: "Composite", - className: "StorageError", - modelProperties: { - message: { - serializedName: "Message", - xmlName: "Message", + }, + encryptionScope: { + serializedName: "EncryptionScope", + xmlName: "EncryptionScope", type: { name: "String" } }, - copySourceStatusCode: { - serializedName: "CopySourceStatusCode", - xmlName: "CopySourceStatusCode", + accessTierChangedOn: { + serializedName: "AccessTierChangeTime", + xmlName: "AccessTierChangeTime", + type: { + name: "DateTimeRfc1123" + } + }, + tagCount: { + serializedName: "TagCount", + xmlName: "TagCount", type: { name: "Number" } }, - copySourceErrorCode: { - serializedName: "CopySourceErrorCode", - xmlName: "CopySourceErrorCode", + expiresOn: { + serializedName: "Expiry-Time", + xmlName: "Expiry-Time", type: { - name: "String" + name: "DateTimeRfc1123" } }, - copySourceErrorMessage: { - serializedName: "CopySourceErrorMessage", - xmlName: "CopySourceErrorMessage", + isSealed: { + serializedName: "Sealed", + xmlName: "Sealed", type: { - name: "String" + name: "Boolean" } }, - code: { - serializedName: "Code", - xmlName: "Code", + rehydratePriority: { + serializedName: "RehydratePriority", + xmlName: "RehydratePriority", type: { - name: "String" + name: "Enum", + allowedValues: ["High", "Standard"] } }, - authenticationErrorDetail: { - serializedName: "AuthenticationErrorDetail", - xmlName: "AuthenticationErrorDetail", + lastAccessedOn: { + serializedName: "LastAccessTime", + xmlName: "LastAccessTime", type: { - name: "String" + name: "DateTimeRfc1123" } - } - } - } - }; - exports2.BlobServiceStatistics = { - serializedName: "BlobServiceStatistics", - xmlName: "StorageServiceStats", - type: { - name: "Composite", - className: "BlobServiceStatistics", - modelProperties: { - geoReplication: { - serializedName: "GeoReplication", - xmlName: "GeoReplication", + }, + immutabilityPolicyExpiresOn: { + serializedName: "ImmutabilityPolicyUntilDate", + xmlName: "ImmutabilityPolicyUntilDate", type: { - name: "Composite", - className: "GeoReplication" + name: "DateTimeRfc1123" } - } - } - } - }; - exports2.GeoReplication = { - serializedName: "GeoReplication", - type: { - name: "Composite", - className: "GeoReplication", - modelProperties: { - status: { - serializedName: "Status", - required: true, - xmlName: "Status", + }, + immutabilityPolicyMode: { + serializedName: "ImmutabilityPolicyMode", + xmlName: "ImmutabilityPolicyMode", type: { name: "Enum", - allowedValues: ["live", "bootstrap", "unavailable"] + allowedValues: ["Mutable", "Unlocked", "Locked"] } }, - lastSyncOn: { - serializedName: "LastSyncTime", - required: true, - xmlName: "LastSyncTime", + legalHold: { + serializedName: "LegalHold", + xmlName: "LegalHold", type: { - name: "DateTimeRfc1123" + name: "Boolean" } } } } }; - exports2.ListContainersSegmentResponse = { - serializedName: "ListContainersSegmentResponse", + var ListBlobsHierarchySegmentResponse = { + serializedName: "ListBlobsHierarchySegmentResponse", xmlName: "EnumerationResults", type: { name: "Composite", - className: "ListContainersSegmentResponse", + className: "ListBlobsHierarchySegmentResponse", modelProperties: { serviceEndpoint: { serializedName: "ServiceEndpoint", @@ -51524,6 +64719,15 @@ var require_mappers = __commonJS({ name: "String" } }, + containerName: { + serializedName: "ContainerName", + required: true, + xmlName: "ContainerName", + xmlIsAttribute: true, + type: { + name: "String" + } + }, prefix: { serializedName: "Prefix", xmlName: "Prefix", @@ -51545,20 +64749,19 @@ var require_mappers = __commonJS({ name: "Number" } }, - containerItems: { - serializedName: "ContainerItems", - required: true, - xmlName: "Containers", - xmlIsWrapped: true, - xmlElementName: "Container", + delimiter: { + serializedName: "Delimiter", + xmlName: "Delimiter", type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "ContainerItem" - } - } + name: "String" + } + }, + segment: { + serializedName: "Segment", + xmlName: "Blobs", + type: { + name: "Composite", + className: "BlobHierarchyListSegment" } }, continuationToken: { @@ -51571,359 +64774,461 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerItem = { - serializedName: "ContainerItem", - xmlName: "Container", + var BlobHierarchyListSegment = { + serializedName: "BlobHierarchyListSegment", + xmlName: "Blobs", type: { name: "Composite", - className: "ContainerItem", + className: "BlobHierarchyListSegment", modelProperties: { - name: { - serializedName: "Name", - required: true, - xmlName: "Name", - type: { - name: "String" - } - }, - deleted: { - serializedName: "Deleted", - xmlName: "Deleted", + blobPrefixes: { + serializedName: "BlobPrefixes", + xmlName: "BlobPrefixes", + xmlElementName: "BlobPrefix", type: { - name: "Boolean" + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobPrefix" + } + } } }, - version: { - serializedName: "Version", - xmlName: "Version", + blobItems: { + serializedName: "BlobItems", + required: true, + xmlName: "BlobItems", + xmlElementName: "Blob", type: { - name: "String" + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobItemInternal" + } + } } - }, - properties: { - serializedName: "Properties", - xmlName: "Properties", + } + } + } + }; + var BlobPrefix = { + serializedName: "BlobPrefix", + type: { + name: "Composite", + className: "BlobPrefix", + modelProperties: { + name: { + serializedName: "Name", + xmlName: "Name", type: { name: "Composite", - className: "ContainerProperties" - } - }, - metadata: { - serializedName: "Metadata", - xmlName: "Metadata", - type: { - name: "Dictionary", - value: { type: { name: "String" } } + className: "BlobName" } } } } }; - exports2.ContainerProperties = { - serializedName: "ContainerProperties", + var BlockLookupList = { + serializedName: "BlockLookupList", + xmlName: "BlockList", type: { name: "Composite", - className: "ContainerProperties", + className: "BlockLookupList", modelProperties: { - lastModified: { - serializedName: "Last-Modified", - required: true, - xmlName: "Last-Modified", - type: { - name: "DateTimeRfc1123" - } - }, - etag: { - serializedName: "Etag", - required: true, - xmlName: "Etag", - type: { - name: "String" - } - }, - leaseStatus: { - serializedName: "LeaseStatus", - xmlName: "LeaseStatus", - type: { - name: "Enum", - allowedValues: ["locked", "unlocked"] - } - }, - leaseState: { - serializedName: "LeaseState", - xmlName: "LeaseState", + committed: { + serializedName: "Committed", + xmlName: "Committed", + xmlElementName: "Committed", type: { - name: "Enum", - allowedValues: [ - "available", - "leased", - "expired", - "breaking", - "broken" - ] + name: "Sequence", + element: { + type: { + name: "String" + } + } } }, - leaseDuration: { - serializedName: "LeaseDuration", - xmlName: "LeaseDuration", + uncommitted: { + serializedName: "Uncommitted", + xmlName: "Uncommitted", + xmlElementName: "Uncommitted", type: { - name: "Enum", - allowedValues: ["infinite", "fixed"] + name: "Sequence", + element: { + type: { + name: "String" + } + } } }, - publicAccess: { - serializedName: "PublicAccess", - xmlName: "PublicAccess", + latest: { + serializedName: "Latest", + xmlName: "Latest", + xmlElementName: "Latest", type: { - name: "Enum", - allowedValues: ["container", "blob"] + name: "Sequence", + element: { + type: { + name: "String" + } + } } - }, - hasImmutabilityPolicy: { - serializedName: "HasImmutabilityPolicy", - xmlName: "HasImmutabilityPolicy", + } + } + } + }; + var BlockList = { + serializedName: "BlockList", + type: { + name: "Composite", + className: "BlockList", + modelProperties: { + committedBlocks: { + serializedName: "CommittedBlocks", + xmlName: "CommittedBlocks", + xmlIsWrapped: true, + xmlElementName: "Block", type: { - name: "Boolean" + name: "Sequence", + element: { + type: { + name: "Composite", + className: "Block" + } + } } }, - hasLegalHold: { - serializedName: "HasLegalHold", - xmlName: "HasLegalHold", + uncommittedBlocks: { + serializedName: "UncommittedBlocks", + xmlName: "UncommittedBlocks", + xmlIsWrapped: true, + xmlElementName: "Block", type: { - name: "Boolean" + name: "Sequence", + element: { + type: { + name: "Composite", + className: "Block" + } + } } - }, - defaultEncryptionScope: { - serializedName: "DefaultEncryptionScope", - xmlName: "DefaultEncryptionScope", + } + } + } + }; + var Block2 = { + serializedName: "Block", + type: { + name: "Composite", + className: "Block", + modelProperties: { + name: { + serializedName: "Name", + required: true, + xmlName: "Name", type: { name: "String" } }, - preventEncryptionScopeOverride: { - serializedName: "DenyEncryptionScopeOverride", - xmlName: "DenyEncryptionScopeOverride", + size: { + serializedName: "Size", + required: true, + xmlName: "Size", type: { - name: "Boolean" + name: "Number" } - }, - deletedOn: { - serializedName: "DeletedTime", - xmlName: "DeletedTime", + } + } + } + }; + var PageList = { + serializedName: "PageList", + type: { + name: "Composite", + className: "PageList", + modelProperties: { + pageRange: { + serializedName: "PageRange", + xmlName: "PageRange", + xmlElementName: "PageRange", type: { - name: "DateTimeRfc1123" + name: "Sequence", + element: { + type: { + name: "Composite", + className: "PageRange" + } + } } }, - remainingRetentionDays: { - serializedName: "RemainingRetentionDays", - xmlName: "RemainingRetentionDays", + clearRange: { + serializedName: "ClearRange", + xmlName: "ClearRange", + xmlElementName: "ClearRange", type: { - name: "Number" + name: "Sequence", + element: { + type: { + name: "Composite", + className: "ClearRange" + } + } } }, - isImmutableStorageWithVersioningEnabled: { - serializedName: "ImmutableStorageWithVersioningEnabled", - xmlName: "ImmutableStorageWithVersioningEnabled", + continuationToken: { + serializedName: "NextMarker", + xmlName: "NextMarker", type: { - name: "Boolean" + name: "String" } } } } }; - exports2.KeyInfo = { - serializedName: "KeyInfo", + var PageRange = { + serializedName: "PageRange", + xmlName: "PageRange", type: { name: "Composite", - className: "KeyInfo", + className: "PageRange", modelProperties: { - startsOn: { + start: { serializedName: "Start", required: true, xmlName: "Start", type: { - name: "String" + name: "Number" } }, - expiresOn: { - serializedName: "Expiry", + end: { + serializedName: "End", required: true, - xmlName: "Expiry", + xmlName: "End", type: { - name: "String" + name: "Number" } } } } }; - exports2.UserDelegationKey = { - serializedName: "UserDelegationKey", + var ClearRange = { + serializedName: "ClearRange", + xmlName: "ClearRange", type: { name: "Composite", - className: "UserDelegationKey", + className: "ClearRange", modelProperties: { - signedObjectId: { - serializedName: "SignedOid", + start: { + serializedName: "Start", required: true, - xmlName: "SignedOid", + xmlName: "Start", type: { - name: "String" + name: "Number" } }, - signedTenantId: { - serializedName: "SignedTid", + end: { + serializedName: "End", required: true, - xmlName: "SignedTid", + xmlName: "End", type: { - name: "String" + name: "Number" } - }, - signedStartsOn: { - serializedName: "SignedStart", + } + } + } + }; + var QueryRequest = { + serializedName: "QueryRequest", + xmlName: "QueryRequest", + type: { + name: "Composite", + className: "QueryRequest", + modelProperties: { + queryType: { + serializedName: "QueryType", required: true, - xmlName: "SignedStart", + xmlName: "QueryType", type: { name: "String" } }, - signedExpiresOn: { - serializedName: "SignedExpiry", + expression: { + serializedName: "Expression", required: true, - xmlName: "SignedExpiry", + xmlName: "Expression", type: { name: "String" } }, - signedService: { - serializedName: "SignedService", - required: true, - xmlName: "SignedService", + inputSerialization: { + serializedName: "InputSerialization", + xmlName: "InputSerialization", type: { - name: "String" + name: "Composite", + className: "QuerySerialization" } }, - signedVersion: { - serializedName: "SignedVersion", - required: true, - xmlName: "SignedVersion", + outputSerialization: { + serializedName: "OutputSerialization", + xmlName: "OutputSerialization", type: { - name: "String" + name: "Composite", + className: "QuerySerialization" } - }, - value: { - serializedName: "Value", - required: true, - xmlName: "Value", + } + } + } + }; + var QuerySerialization = { + serializedName: "QuerySerialization", + type: { + name: "Composite", + className: "QuerySerialization", + modelProperties: { + format: { + serializedName: "Format", + xmlName: "Format", type: { - name: "String" + name: "Composite", + className: "QueryFormat" } } } } }; - exports2.FilterBlobSegment = { - serializedName: "FilterBlobSegment", - xmlName: "EnumerationResults", + var QueryFormat = { + serializedName: "QueryFormat", type: { name: "Composite", - className: "FilterBlobSegment", + className: "QueryFormat", modelProperties: { - serviceEndpoint: { - serializedName: "ServiceEndpoint", + type: { + serializedName: "Type", required: true, - xmlName: "ServiceEndpoint", - xmlIsAttribute: true, + xmlName: "Type", type: { - name: "String" + name: "Enum", + allowedValues: ["delimited", "json", "arrow", "parquet"] } }, - where: { - serializedName: "Where", - required: true, - xmlName: "Where", + delimitedTextConfiguration: { + serializedName: "DelimitedTextConfiguration", + xmlName: "DelimitedTextConfiguration", type: { - name: "String" + name: "Composite", + className: "DelimitedTextConfiguration" } }, - blobs: { - serializedName: "Blobs", - required: true, - xmlName: "Blobs", - xmlIsWrapped: true, - xmlElementName: "Blob", + jsonTextConfiguration: { + serializedName: "JsonTextConfiguration", + xmlName: "JsonTextConfiguration", type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "FilterBlobItem" - } - } + name: "Composite", + className: "JsonTextConfiguration" } }, - continuationToken: { - serializedName: "NextMarker", - xmlName: "NextMarker", + arrowConfiguration: { + serializedName: "ArrowConfiguration", + xmlName: "ArrowConfiguration", type: { - name: "String" + name: "Composite", + className: "ArrowConfiguration" + } + }, + parquetTextConfiguration: { + serializedName: "ParquetTextConfiguration", + xmlName: "ParquetTextConfiguration", + type: { + name: "Dictionary", + value: { type: { name: "any" } } } } } } }; - exports2.FilterBlobItem = { - serializedName: "FilterBlobItem", - xmlName: "Blob", + var DelimitedTextConfiguration = { + serializedName: "DelimitedTextConfiguration", + xmlName: "DelimitedTextConfiguration", type: { name: "Composite", - className: "FilterBlobItem", + className: "DelimitedTextConfiguration", modelProperties: { - name: { - serializedName: "Name", - required: true, - xmlName: "Name", + columnSeparator: { + serializedName: "ColumnSeparator", + xmlName: "ColumnSeparator", type: { name: "String" } }, - containerName: { - serializedName: "ContainerName", - required: true, - xmlName: "ContainerName", + fieldQuote: { + serializedName: "FieldQuote", + xmlName: "FieldQuote", type: { name: "String" } }, - tags: { - serializedName: "Tags", - xmlName: "Tags", + recordSeparator: { + serializedName: "RecordSeparator", + xmlName: "RecordSeparator", type: { - name: "Composite", - className: "BlobTags" + name: "String" + } + }, + escapeChar: { + serializedName: "EscapeChar", + xmlName: "EscapeChar", + type: { + name: "String" + } + }, + headersPresent: { + serializedName: "HeadersPresent", + xmlName: "HasHeaders", + type: { + name: "Boolean" } } } } }; - exports2.BlobTags = { - serializedName: "BlobTags", - xmlName: "Tags", + var JsonTextConfiguration = { + serializedName: "JsonTextConfiguration", + xmlName: "JsonTextConfiguration", type: { name: "Composite", - className: "BlobTags", + className: "JsonTextConfiguration", modelProperties: { - blobTagSet: { - serializedName: "BlobTagSet", + recordSeparator: { + serializedName: "RecordSeparator", + xmlName: "RecordSeparator", + type: { + name: "String" + } + } + } + } + }; + var ArrowConfiguration = { + serializedName: "ArrowConfiguration", + xmlName: "ArrowConfiguration", + type: { + name: "Composite", + className: "ArrowConfiguration", + modelProperties: { + schema: { + serializedName: "Schema", required: true, - xmlName: "TagSet", + xmlName: "Schema", xmlIsWrapped: true, - xmlElementName: "Tag", + xmlElementName: "Field", type: { name: "Sequence", element: { type: { name: "Composite", - className: "BlobTag" + className: "ArrowField" } } } @@ -51931,81 +65236,128 @@ var require_mappers = __commonJS({ } } }; - exports2.BlobTag = { - serializedName: "BlobTag", - xmlName: "Tag", + var ArrowField = { + serializedName: "ArrowField", + xmlName: "Field", type: { name: "Composite", - className: "BlobTag", + className: "ArrowField", modelProperties: { - key: { - serializedName: "Key", + type: { + serializedName: "Type", required: true, - xmlName: "Key", + xmlName: "Type", type: { name: "String" } }, - value: { - serializedName: "Value", - required: true, - xmlName: "Value", + name: { + serializedName: "Name", + xmlName: "Name", type: { name: "String" } + }, + precision: { + serializedName: "Precision", + xmlName: "Precision", + type: { + name: "Number" + } + }, + scale: { + serializedName: "Scale", + xmlName: "Scale", + type: { + name: "Number" + } } } } }; - exports2.SignedIdentifier = { - serializedName: "SignedIdentifier", - xmlName: "SignedIdentifier", + var ServiceSetPropertiesHeaders = { + serializedName: "Service_setPropertiesHeaders", type: { name: "Composite", - className: "SignedIdentifier", + className: "ServiceSetPropertiesHeaders", modelProperties: { - id: { - serializedName: "Id", - required: true, - xmlName: "Id", + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", type: { name: "String" } }, - accessPolicy: { - serializedName: "AccessPolicy", - xmlName: "AccessPolicy", + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", type: { - name: "Composite", - className: "AccessPolicy" + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" } } } } }; - exports2.AccessPolicy = { - serializedName: "AccessPolicy", + var ServiceSetPropertiesExceptionHeaders = { + serializedName: "Service_setPropertiesExceptionHeaders", type: { name: "Composite", - className: "AccessPolicy", + className: "ServiceSetPropertiesExceptionHeaders", modelProperties: { - startsOn: { - serializedName: "Start", - xmlName: "Start", + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceGetPropertiesHeaders = { + serializedName: "Service_getPropertiesHeaders", + type: { + name: "Composite", + className: "ServiceGetPropertiesHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", type: { name: "String" } }, - expiresOn: { - serializedName: "Expiry", - xmlName: "Expiry", + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", type: { name: "String" } }, - permissions: { - serializedName: "Permission", - xmlName: "Permission", + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { name: "String" } @@ -52013,63 +65365,59 @@ var require_mappers = __commonJS({ } } }; - exports2.ListBlobsFlatSegmentResponse = { - serializedName: "ListBlobsFlatSegmentResponse", - xmlName: "EnumerationResults", + var ServiceGetPropertiesExceptionHeaders = { + serializedName: "Service_getPropertiesExceptionHeaders", type: { name: "Composite", - className: "ListBlobsFlatSegmentResponse", + className: "ServiceGetPropertiesExceptionHeaders", modelProperties: { - serviceEndpoint: { - serializedName: "ServiceEndpoint", - required: true, - xmlName: "ServiceEndpoint", - xmlIsAttribute: true, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { name: "String" } - }, - containerName: { - serializedName: "ContainerName", - required: true, - xmlName: "ContainerName", - xmlIsAttribute: true, + } + } + } + }; + var ServiceGetStatisticsHeaders = { + serializedName: "Service_getStatisticsHeaders", + type: { + name: "Composite", + className: "ServiceGetStatisticsHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", type: { name: "String" } }, - prefix: { - serializedName: "Prefix", - xmlName: "Prefix", + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", type: { name: "String" } }, - marker: { - serializedName: "Marker", - xmlName: "Marker", + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", type: { name: "String" } }, - maxPageSize: { - serializedName: "MaxResults", - xmlName: "MaxResults", - type: { - name: "Number" - } - }, - segment: { - serializedName: "Segment", - xmlName: "Blobs", + date: { + serializedName: "date", + xmlName: "date", type: { - name: "Composite", - className: "BlobFlatListSegment" + name: "DateTimeRfc1123" } }, - continuationToken: { - serializedName: "NextMarker", - xmlName: "NextMarker", + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { name: "String" } @@ -52077,136 +65425,128 @@ var require_mappers = __commonJS({ } } }; - exports2.BlobFlatListSegment = { - serializedName: "BlobFlatListSegment", - xmlName: "Blobs", + var ServiceGetStatisticsExceptionHeaders = { + serializedName: "Service_getStatisticsExceptionHeaders", type: { name: "Composite", - className: "BlobFlatListSegment", + className: "ServiceGetStatisticsExceptionHeaders", modelProperties: { - blobItems: { - serializedName: "BlobItems", - required: true, - xmlName: "BlobItems", - xmlElementName: "Blob", + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "BlobItemInternal" - } - } + name: "String" } } } } }; - exports2.BlobItemInternal = { - serializedName: "BlobItemInternal", - xmlName: "Blob", + var ServiceListContainersSegmentHeaders = { + serializedName: "Service_listContainersSegmentHeaders", type: { name: "Composite", - className: "BlobItemInternal", + className: "ServiceListContainersSegmentHeaders", modelProperties: { - name: { - serializedName: "Name", - xmlName: "Name", + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", type: { - name: "Composite", - className: "BlobName" + name: "String" } }, - deleted: { - serializedName: "Deleted", - required: true, - xmlName: "Deleted", + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", type: { - name: "Boolean" + name: "String" } }, - snapshot: { - serializedName: "Snapshot", - required: true, - xmlName: "Snapshot", + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", type: { name: "String" } }, - versionId: { - serializedName: "VersionId", - xmlName: "VersionId", + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { name: "String" } - }, - isCurrentVersion: { - serializedName: "IsCurrentVersion", - xmlName: "IsCurrentVersion", + } + } + } + }; + var ServiceListContainersSegmentExceptionHeaders = { + serializedName: "Service_listContainersSegmentExceptionHeaders", + type: { + name: "Composite", + className: "ServiceListContainersSegmentExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { - name: "Boolean" + name: "String" } - }, - properties: { - serializedName: "Properties", - xmlName: "Properties", + } + } + } + }; + var ServiceGetUserDelegationKeyHeaders = { + serializedName: "Service_getUserDelegationKeyHeaders", + type: { + name: "Composite", + className: "ServiceGetUserDelegationKeyHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", type: { - name: "Composite", - className: "BlobPropertiesInternal" + name: "String" } }, - metadata: { - serializedName: "Metadata", - xmlName: "Metadata", + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", type: { - name: "Dictionary", - value: { type: { name: "String" } } + name: "String" } }, - blobTags: { - serializedName: "BlobTags", - xmlName: "Tags", + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", type: { - name: "Composite", - className: "BlobTags" + name: "String" } }, - objectReplicationMetadata: { - serializedName: "ObjectReplicationMetadata", - xmlName: "OrMetadata", + date: { + serializedName: "date", + xmlName: "date", type: { - name: "Dictionary", - value: { type: { name: "String" } } + name: "DateTimeRfc1123" } }, - hasVersionsOnly: { - serializedName: "HasVersionsOnly", - xmlName: "HasVersionsOnly", + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { - name: "Boolean" + name: "String" } } } } }; - exports2.BlobName = { - serializedName: "BlobName", + var ServiceGetUserDelegationKeyExceptionHeaders = { + serializedName: "Service_getUserDelegationKeyExceptionHeaders", type: { name: "Composite", - className: "BlobName", + className: "ServiceGetUserDelegationKeyExceptionHeaders", modelProperties: { - encoded: { - serializedName: "Encoded", - xmlName: "Encoded", - xmlIsAttribute: true, - type: { - name: "Boolean" - } - }, - content: { - serializedName: "content", - xmlName: "content", - xmlIsMsText: true, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { name: "String" } @@ -52214,833 +65554,507 @@ var require_mappers = __commonJS({ } } }; - exports2.BlobPropertiesInternal = { - serializedName: "BlobPropertiesInternal", - xmlName: "Properties", + var ServiceGetAccountInfoHeaders = { + serializedName: "Service_getAccountInfoHeaders", type: { name: "Composite", - className: "BlobPropertiesInternal", + className: "ServiceGetAccountInfoHeaders", modelProperties: { - createdOn: { - serializedName: "Creation-Time", - xmlName: "Creation-Time", + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", type: { - name: "DateTimeRfc1123" + name: "String" } }, - lastModified: { - serializedName: "Last-Modified", - required: true, - xmlName: "Last-Modified", + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", type: { - name: "DateTimeRfc1123" + name: "String" } }, - etag: { - serializedName: "Etag", - required: true, - xmlName: "Etag", + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", type: { name: "String" } }, - contentLength: { - serializedName: "Content-Length", - xmlName: "Content-Length", + date: { + serializedName: "date", + xmlName: "date", type: { - name: "Number" + name: "DateTimeRfc1123" + } + }, + skuName: { + serializedName: "x-ms-sku-name", + xmlName: "x-ms-sku-name", + type: { + name: "Enum", + allowedValues: [ + "Standard_LRS", + "Standard_GRS", + "Standard_RAGRS", + "Standard_ZRS", + "Premium_LRS", + "Standard_GZRS", + "Premium_ZRS", + "Standard_RAGZRS" + ] + } + }, + accountKind: { + serializedName: "x-ms-account-kind", + xmlName: "x-ms-account-kind", + type: { + name: "Enum", + allowedValues: [ + "Storage", + "BlobStorage", + "StorageV2", + "FileStorage", + "BlockBlobStorage" + ] + } + }, + isHierarchicalNamespaceEnabled: { + serializedName: "x-ms-is-hns-enabled", + xmlName: "x-ms-is-hns-enabled", + type: { + name: "Boolean" } }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceGetAccountInfoExceptionHeaders = { + serializedName: "Service_getAccountInfoExceptionHeaders", + type: { + name: "Composite", + className: "ServiceGetAccountInfoExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceSubmitBatchHeaders = { + serializedName: "Service_submitBatchHeaders", + type: { + name: "Composite", + className: "ServiceSubmitBatchHeaders", + modelProperties: { contentType: { - serializedName: "Content-Type", - xmlName: "Content-Type", + serializedName: "content-type", + xmlName: "content-type", type: { name: "String" } }, - contentEncoding: { - serializedName: "Content-Encoding", - xmlName: "Content-Encoding", + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", type: { name: "String" } }, - contentLanguage: { - serializedName: "Content-Language", - xmlName: "Content-Language", + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", type: { name: "String" } }, - contentMD5: { - serializedName: "Content-MD5", - xmlName: "Content-MD5", + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", type: { - name: "ByteArray" + name: "String" } }, - contentDisposition: { - serializedName: "Content-Disposition", - xmlName: "Content-Disposition", + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { name: "String" } - }, - cacheControl: { - serializedName: "Cache-Control", - xmlName: "Cache-Control", + } + } + } + }; + var ServiceSubmitBatchExceptionHeaders = { + serializedName: "Service_submitBatchExceptionHeaders", + type: { + name: "Composite", + className: "ServiceSubmitBatchExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { name: "String" } - }, - blobSequenceNumber: { - serializedName: "x-ms-blob-sequence-number", - xmlName: "x-ms-blob-sequence-number", + } + } + } + }; + var ServiceFilterBlobsHeaders = { + serializedName: "Service_filterBlobsHeaders", + type: { + name: "Composite", + className: "ServiceFilterBlobsHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", type: { - name: "Number" + name: "String" } }, - blobType: { - serializedName: "BlobType", - xmlName: "BlobType", + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", type: { - name: "Enum", - allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"] + name: "String" } }, - leaseStatus: { - serializedName: "LeaseStatus", - xmlName: "LeaseStatus", + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", type: { - name: "Enum", - allowedValues: ["locked", "unlocked"] + name: "String" } }, - leaseState: { - serializedName: "LeaseState", - xmlName: "LeaseState", + date: { + serializedName: "date", + xmlName: "date", type: { - name: "Enum", - allowedValues: [ - "available", - "leased", - "expired", - "breaking", - "broken" - ] + name: "DateTimeRfc1123" } }, - leaseDuration: { - serializedName: "LeaseDuration", - xmlName: "LeaseDuration", + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { - name: "Enum", - allowedValues: ["infinite", "fixed"] + name: "String" } - }, - copyId: { - serializedName: "CopyId", - xmlName: "CopyId", + } + } + } + }; + var ServiceFilterBlobsExceptionHeaders = { + serializedName: "Service_filterBlobsExceptionHeaders", + type: { + name: "Composite", + className: "ServiceFilterBlobsExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerCreateHeaders = { + serializedName: "Container_createHeaders", + type: { + name: "Composite", + className: "ContainerCreateHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", type: { name: "String" } }, - copyStatus: { - serializedName: "CopyStatus", - xmlName: "CopyStatus", + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", type: { - name: "Enum", - allowedValues: ["pending", "success", "aborted", "failed"] + name: "DateTimeRfc1123" } }, - copySource: { - serializedName: "CopySource", - xmlName: "CopySource", + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", type: { name: "String" } }, - copyProgress: { - serializedName: "CopyProgress", - xmlName: "CopyProgress", + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", type: { name: "String" } }, - copyCompletedOn: { - serializedName: "CopyCompletionTime", - xmlName: "CopyCompletionTime", + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", type: { name: "DateTimeRfc1123" } }, - copyStatusDescription: { - serializedName: "CopyStatusDescription", - xmlName: "CopyStatusDescription", + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { name: "String" } - }, - serverEncrypted: { - serializedName: "ServerEncrypted", - xmlName: "ServerEncrypted", + } + } + } + }; + var ContainerCreateExceptionHeaders = { + serializedName: "Container_createExceptionHeaders", + type: { + name: "Composite", + className: "ContainerCreateExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { - name: "Boolean" + name: "String" } - }, - incrementalCopy: { - serializedName: "IncrementalCopy", - xmlName: "IncrementalCopy", + } + } + } + }; + var ContainerGetPropertiesHeaders = { + serializedName: "Container_getPropertiesHeaders", + type: { + name: "Composite", + className: "ContainerGetPropertiesHeaders", + modelProperties: { + metadata: { + serializedName: "x-ms-meta", + headerCollectionPrefix: "x-ms-meta-", + xmlName: "x-ms-meta", type: { - name: "Boolean" + name: "Dictionary", + value: { type: { name: "String" } } } }, - destinationSnapshot: { - serializedName: "DestinationSnapshot", - xmlName: "DestinationSnapshot", + etag: { + serializedName: "etag", + xmlName: "etag", type: { name: "String" } }, - deletedOn: { - serializedName: "DeletedTime", - xmlName: "DeletedTime", + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, - remainingRetentionDays: { - serializedName: "RemainingRetentionDays", - xmlName: "RemainingRetentionDays", + leaseDuration: { + serializedName: "x-ms-lease-duration", + xmlName: "x-ms-lease-duration", type: { - name: "Number" + name: "Enum", + allowedValues: ["infinite", "fixed"] } }, - accessTier: { - serializedName: "AccessTier", - xmlName: "AccessTier", + leaseState: { + serializedName: "x-ms-lease-state", + xmlName: "x-ms-lease-state", type: { name: "Enum", allowedValues: [ - "P4", - "P6", - "P10", - "P15", - "P20", - "P30", - "P40", - "P50", - "P60", - "P70", - "P80", - "Hot", - "Cool", - "Archive", - "Cold" + "available", + "leased", + "expired", + "breaking", + "broken" ] } }, - accessTierInferred: { - serializedName: "AccessTierInferred", - xmlName: "AccessTierInferred", + leaseStatus: { + serializedName: "x-ms-lease-status", + xmlName: "x-ms-lease-status", type: { - name: "Boolean" + name: "Enum", + allowedValues: ["locked", "unlocked"] } }, - archiveStatus: { - serializedName: "ArchiveStatus", - xmlName: "ArchiveStatus", + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", type: { - name: "Enum", - allowedValues: [ - "rehydrate-pending-to-hot", - "rehydrate-pending-to-cool", - "rehydrate-pending-to-cold" - ] + name: "String" } }, - customerProvidedKeySha256: { - serializedName: "CustomerProvidedKeySha256", - xmlName: "CustomerProvidedKeySha256", + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", type: { name: "String" } }, - encryptionScope: { - serializedName: "EncryptionScope", - xmlName: "EncryptionScope", + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", type: { name: "String" } }, - accessTierChangedOn: { - serializedName: "AccessTierChangeTime", - xmlName: "AccessTierChangeTime", + date: { + serializedName: "date", + xmlName: "date", type: { name: "DateTimeRfc1123" } }, - tagCount: { - serializedName: "TagCount", - xmlName: "TagCount", + blobPublicAccess: { + serializedName: "x-ms-blob-public-access", + xmlName: "x-ms-blob-public-access", type: { - name: "Number" + name: "Enum", + allowedValues: ["container", "blob"] } }, - expiresOn: { - serializedName: "Expiry-Time", - xmlName: "Expiry-Time", + hasImmutabilityPolicy: { + serializedName: "x-ms-has-immutability-policy", + xmlName: "x-ms-has-immutability-policy", type: { - name: "DateTimeRfc1123" + name: "Boolean" } }, - isSealed: { - serializedName: "Sealed", - xmlName: "Sealed", + hasLegalHold: { + serializedName: "x-ms-has-legal-hold", + xmlName: "x-ms-has-legal-hold", type: { name: "Boolean" } }, - rehydratePriority: { - serializedName: "RehydratePriority", - xmlName: "RehydratePriority", + defaultEncryptionScope: { + serializedName: "x-ms-default-encryption-scope", + xmlName: "x-ms-default-encryption-scope", type: { - name: "Enum", - allowedValues: ["High", "Standard"] + name: "String" } }, - lastAccessedOn: { - serializedName: "LastAccessTime", - xmlName: "LastAccessTime", + denyEncryptionScopeOverride: { + serializedName: "x-ms-deny-encryption-scope-override", + xmlName: "x-ms-deny-encryption-scope-override", type: { - name: "DateTimeRfc1123" + name: "Boolean" } }, - immutabilityPolicyExpiresOn: { - serializedName: "ImmutabilityPolicyUntilDate", - xmlName: "ImmutabilityPolicyUntilDate", + isImmutableStorageWithVersioningEnabled: { + serializedName: "x-ms-immutable-storage-with-versioning-enabled", + xmlName: "x-ms-immutable-storage-with-versioning-enabled", type: { - name: "DateTimeRfc1123" + name: "Boolean" } }, - immutabilityPolicyMode: { - serializedName: "ImmutabilityPolicyMode", - xmlName: "ImmutabilityPolicyMode", + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { - name: "Enum", - allowedValues: ["Mutable", "Unlocked", "Locked"] + name: "String" } - }, - legalHold: { - serializedName: "LegalHold", - xmlName: "LegalHold", + } + } + } + }; + var ContainerGetPropertiesExceptionHeaders = { + serializedName: "Container_getPropertiesExceptionHeaders", + type: { + name: "Composite", + className: "ContainerGetPropertiesExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { - name: "Boolean" + name: "String" } } } } }; - exports2.ListBlobsHierarchySegmentResponse = { - serializedName: "ListBlobsHierarchySegmentResponse", - xmlName: "EnumerationResults", + var ContainerDeleteHeaders = { + serializedName: "Container_deleteHeaders", type: { name: "Composite", - className: "ListBlobsHierarchySegmentResponse", + className: "ContainerDeleteHeaders", modelProperties: { - serviceEndpoint: { - serializedName: "ServiceEndpoint", - required: true, - xmlName: "ServiceEndpoint", - xmlIsAttribute: true, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", type: { name: "String" } }, - containerName: { - serializedName: "ContainerName", - required: true, - xmlName: "ContainerName", - xmlIsAttribute: true, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", type: { name: "String" } }, - prefix: { - serializedName: "Prefix", - xmlName: "Prefix", - type: { - name: "String" - } - }, - marker: { - serializedName: "Marker", - xmlName: "Marker", - type: { - name: "String" - } - }, - maxPageSize: { - serializedName: "MaxResults", - xmlName: "MaxResults", - type: { - name: "Number" - } - }, - delimiter: { - serializedName: "Delimiter", - xmlName: "Delimiter", - type: { - name: "String" - } - }, - segment: { - serializedName: "Segment", - xmlName: "Blobs", - type: { - name: "Composite", - className: "BlobHierarchyListSegment" - } - }, - continuationToken: { - serializedName: "NextMarker", - xmlName: "NextMarker", - type: { - name: "String" - } - } - } - } - }; - exports2.BlobHierarchyListSegment = { - serializedName: "BlobHierarchyListSegment", - xmlName: "Blobs", - type: { - name: "Composite", - className: "BlobHierarchyListSegment", - modelProperties: { - blobPrefixes: { - serializedName: "BlobPrefixes", - xmlName: "BlobPrefixes", - xmlElementName: "BlobPrefix", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "BlobPrefix" - } - } - } - }, - blobItems: { - serializedName: "BlobItems", - required: true, - xmlName: "BlobItems", - xmlElementName: "Blob", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "BlobItemInternal" - } - } - } - } - } - } - }; - exports2.BlobPrefix = { - serializedName: "BlobPrefix", - type: { - name: "Composite", - className: "BlobPrefix", - modelProperties: { - name: { - serializedName: "Name", - xmlName: "Name", - type: { - name: "Composite", - className: "BlobName" - } - } - } - } - }; - exports2.BlockLookupList = { - serializedName: "BlockLookupList", - xmlName: "BlockList", - type: { - name: "Composite", - className: "BlockLookupList", - modelProperties: { - committed: { - serializedName: "Committed", - xmlName: "Committed", - xmlElementName: "Committed", - type: { - name: "Sequence", - element: { - type: { - name: "String" - } - } - } - }, - uncommitted: { - serializedName: "Uncommitted", - xmlName: "Uncommitted", - xmlElementName: "Uncommitted", - type: { - name: "Sequence", - element: { - type: { - name: "String" - } - } - } - }, - latest: { - serializedName: "Latest", - xmlName: "Latest", - xmlElementName: "Latest", - type: { - name: "Sequence", - element: { - type: { - name: "String" - } - } - } - } - } - } - }; - exports2.BlockList = { - serializedName: "BlockList", - type: { - name: "Composite", - className: "BlockList", - modelProperties: { - committedBlocks: { - serializedName: "CommittedBlocks", - xmlName: "CommittedBlocks", - xmlIsWrapped: true, - xmlElementName: "Block", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "Block" - } - } - } - }, - uncommittedBlocks: { - serializedName: "UncommittedBlocks", - xmlName: "UncommittedBlocks", - xmlIsWrapped: true, - xmlElementName: "Block", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "Block" - } - } - } - } - } - } - }; - exports2.Block = { - serializedName: "Block", - type: { - name: "Composite", - className: "Block", - modelProperties: { - name: { - serializedName: "Name", - required: true, - xmlName: "Name", - type: { - name: "String" - } - }, - size: { - serializedName: "Size", - required: true, - xmlName: "Size", - type: { - name: "Number" - } - } - } - } - }; - exports2.PageList = { - serializedName: "PageList", - type: { - name: "Composite", - className: "PageList", - modelProperties: { - pageRange: { - serializedName: "PageRange", - xmlName: "PageRange", - xmlElementName: "PageRange", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "PageRange" - } - } - } - }, - clearRange: { - serializedName: "ClearRange", - xmlName: "ClearRange", - xmlElementName: "ClearRange", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "ClearRange" - } - } - } - }, - continuationToken: { - serializedName: "NextMarker", - xmlName: "NextMarker", - type: { - name: "String" - } - } - } - } - }; - exports2.PageRange = { - serializedName: "PageRange", - xmlName: "PageRange", - type: { - name: "Composite", - className: "PageRange", - modelProperties: { - start: { - serializedName: "Start", - required: true, - xmlName: "Start", - type: { - name: "Number" - } - }, - end: { - serializedName: "End", - required: true, - xmlName: "End", - type: { - name: "Number" - } - } - } - } - }; - exports2.ClearRange = { - serializedName: "ClearRange", - xmlName: "ClearRange", - type: { - name: "Composite", - className: "ClearRange", - modelProperties: { - start: { - serializedName: "Start", - required: true, - xmlName: "Start", - type: { - name: "Number" - } - }, - end: { - serializedName: "End", - required: true, - xmlName: "End", - type: { - name: "Number" - } - } - } - } - }; - exports2.QueryRequest = { - serializedName: "QueryRequest", - xmlName: "QueryRequest", - type: { - name: "Composite", - className: "QueryRequest", - modelProperties: { - queryType: { - serializedName: "QueryType", - required: true, - xmlName: "QueryType", - type: { - name: "String" - } - }, - expression: { - serializedName: "Expression", - required: true, - xmlName: "Expression", - type: { - name: "String" - } - }, - inputSerialization: { - serializedName: "InputSerialization", - xmlName: "InputSerialization", - type: { - name: "Composite", - className: "QuerySerialization" - } - }, - outputSerialization: { - serializedName: "OutputSerialization", - xmlName: "OutputSerialization", - type: { - name: "Composite", - className: "QuerySerialization" - } - } - } - } - }; - exports2.QuerySerialization = { - serializedName: "QuerySerialization", - type: { - name: "Composite", - className: "QuerySerialization", - modelProperties: { - format: { - serializedName: "Format", - xmlName: "Format", - type: { - name: "Composite", - className: "QueryFormat" - } - } - } - } - }; - exports2.QueryFormat = { - serializedName: "QueryFormat", - type: { - name: "Composite", - className: "QueryFormat", - modelProperties: { - type: { - serializedName: "Type", - required: true, - xmlName: "Type", - type: { - name: "Enum", - allowedValues: ["delimited", "json", "arrow", "parquet"] - } - }, - delimitedTextConfiguration: { - serializedName: "DelimitedTextConfiguration", - xmlName: "DelimitedTextConfiguration", - type: { - name: "Composite", - className: "DelimitedTextConfiguration" - } - }, - jsonTextConfiguration: { - serializedName: "JsonTextConfiguration", - xmlName: "JsonTextConfiguration", - type: { - name: "Composite", - className: "JsonTextConfiguration" - } - }, - arrowConfiguration: { - serializedName: "ArrowConfiguration", - xmlName: "ArrowConfiguration", - type: { - name: "Composite", - className: "ArrowConfiguration" - } - }, - parquetTextConfiguration: { - serializedName: "ParquetTextConfiguration", - xmlName: "ParquetTextConfiguration", - type: { - name: "Dictionary", - value: { type: { name: "any" } } - } - } - } - } - }; - exports2.DelimitedTextConfiguration = { - serializedName: "DelimitedTextConfiguration", - xmlName: "DelimitedTextConfiguration", - type: { - name: "Composite", - className: "DelimitedTextConfiguration", - modelProperties: { - columnSeparator: { - serializedName: "ColumnSeparator", - xmlName: "ColumnSeparator", - type: { - name: "String" - } - }, - fieldQuote: { - serializedName: "FieldQuote", - xmlName: "FieldQuote", + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", type: { name: "String" } }, - recordSeparator: { - serializedName: "RecordSeparator", - xmlName: "RecordSeparator", + date: { + serializedName: "date", + xmlName: "date", type: { - name: "String" + name: "DateTimeRfc1123" } }, - escapeChar: { - serializedName: "EscapeChar", - xmlName: "EscapeChar", + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { name: "String" } - }, - headersPresent: { - serializedName: "HeadersPresent", - xmlName: "HasHeaders", - type: { - name: "Boolean" - } } } } }; - exports2.JsonTextConfiguration = { - serializedName: "JsonTextConfiguration", - xmlName: "JsonTextConfiguration", + var ContainerDeleteExceptionHeaders = { + serializedName: "Container_deleteExceptionHeaders", type: { name: "Composite", - className: "JsonTextConfiguration", + className: "ContainerDeleteExceptionHeaders", modelProperties: { - recordSeparator: { - serializedName: "RecordSeparator", - xmlName: "RecordSeparator", + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", type: { name: "String" } @@ -53048,77 +66062,26 @@ var require_mappers = __commonJS({ } } }; - exports2.ArrowConfiguration = { - serializedName: "ArrowConfiguration", - xmlName: "ArrowConfiguration", - type: { - name: "Composite", - className: "ArrowConfiguration", - modelProperties: { - schema: { - serializedName: "Schema", - required: true, - xmlName: "Schema", - xmlIsWrapped: true, - xmlElementName: "Field", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "ArrowField" - } - } - } - } - } - } - }; - exports2.ArrowField = { - serializedName: "ArrowField", - xmlName: "Field", + var ContainerSetMetadataHeaders = { + serializedName: "Container_setMetadataHeaders", type: { name: "Composite", - className: "ArrowField", + className: "ContainerSetMetadataHeaders", modelProperties: { - type: { - serializedName: "Type", - required: true, - xmlName: "Type", - type: { - name: "String" - } - }, - name: { - serializedName: "Name", - xmlName: "Name", + etag: { + serializedName: "etag", + xmlName: "etag", type: { name: "String" } }, - precision: { - serializedName: "Precision", - xmlName: "Precision", + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", type: { - name: "Number" + name: "DateTimeRfc1123" } }, - scale: { - serializedName: "Scale", - xmlName: "Scale", - type: { - name: "Number" - } - } - } - } - }; - exports2.ServiceSetPropertiesHeaders = { - serializedName: "Service_setPropertiesHeaders", - type: { - name: "Composite", - className: "ServiceSetPropertiesHeaders", - modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", @@ -53140,6 +66103,13 @@ var require_mappers = __commonJS({ name: "String" } }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", @@ -53150,11 +66120,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ServiceSetPropertiesExceptionHeaders = { - serializedName: "Service_setPropertiesExceptionHeaders", + var ContainerSetMetadataExceptionHeaders = { + serializedName: "Container_setMetadataExceptionHeaders", type: { name: "Composite", - className: "ServiceSetPropertiesExceptionHeaders", + className: "ContainerSetMetadataExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -53166,65 +66136,34 @@ var require_mappers = __commonJS({ } } }; - exports2.ServiceGetPropertiesHeaders = { - serializedName: "Service_getPropertiesHeaders", + var ContainerGetAccessPolicyHeaders = { + serializedName: "Container_getAccessPolicyHeaders", type: { name: "Composite", - className: "ServiceGetPropertiesHeaders", + className: "ContainerGetAccessPolicyHeaders", modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", + blobPublicAccess: { + serializedName: "x-ms-blob-public-access", + xmlName: "x-ms-blob-public-access", type: { - name: "String" + name: "Enum", + allowedValues: ["container", "blob"] } }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", + etag: { + serializedName: "etag", + xmlName: "etag", type: { name: "String" } }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", type: { - name: "String" + name: "DateTimeRfc1123" } }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } - } - }; - exports2.ServiceGetPropertiesExceptionHeaders = { - serializedName: "Service_getPropertiesExceptionHeaders", - type: { - name: "Composite", - className: "ServiceGetPropertiesExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } - } - }; - exports2.ServiceGetStatisticsHeaders = { - serializedName: "Service_getStatisticsHeaders", - type: { - name: "Composite", - className: "ServiceGetStatisticsHeaders", - modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", @@ -53263,11 +66202,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ServiceGetStatisticsExceptionHeaders = { - serializedName: "Service_getStatisticsExceptionHeaders", + var ContainerGetAccessPolicyExceptionHeaders = { + serializedName: "Container_getAccessPolicyExceptionHeaders", type: { name: "Composite", - className: "ServiceGetStatisticsExceptionHeaders", + className: "ContainerGetAccessPolicyExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -53279,12 +66218,26 @@ var require_mappers = __commonJS({ } } }; - exports2.ServiceListContainersSegmentHeaders = { - serializedName: "Service_listContainersSegmentHeaders", + var ContainerSetAccessPolicyHeaders = { + serializedName: "Container_setAccessPolicyHeaders", type: { name: "Composite", - className: "ServiceListContainersSegmentHeaders", + className: "ContainerSetAccessPolicyHeaders", modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", @@ -53306,6 +66259,13 @@ var require_mappers = __commonJS({ name: "String" } }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", @@ -53316,11 +66276,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ServiceListContainersSegmentExceptionHeaders = { - serializedName: "Service_listContainersSegmentExceptionHeaders", + var ContainerSetAccessPolicyExceptionHeaders = { + serializedName: "Container_setAccessPolicyExceptionHeaders", type: { name: "Composite", - className: "ServiceListContainersSegmentExceptionHeaders", + className: "ContainerSetAccessPolicyExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -53332,11 +66292,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ServiceGetUserDelegationKeyHeaders = { - serializedName: "Service_getUserDelegationKeyHeaders", + var ContainerRestoreHeaders = { + serializedName: "Container_restoreHeaders", type: { name: "Composite", - className: "ServiceGetUserDelegationKeyHeaders", + className: "ContainerRestoreHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", @@ -53376,11 +66336,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ServiceGetUserDelegationKeyExceptionHeaders = { - serializedName: "Service_getUserDelegationKeyExceptionHeaders", + var ContainerRestoreExceptionHeaders = { + serializedName: "Container_restoreExceptionHeaders", type: { name: "Composite", - className: "ServiceGetUserDelegationKeyExceptionHeaders", + className: "ContainerRestoreExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -53392,11 +66352,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ServiceGetAccountInfoHeaders = { - serializedName: "Service_getAccountInfoHeaders", + var ContainerRenameHeaders = { + serializedName: "Container_renameHeaders", type: { name: "Composite", - className: "ServiceGetAccountInfoHeaders", + className: "ContainerRenameHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", @@ -53426,41 +66386,6 @@ var require_mappers = __commonJS({ name: "DateTimeRfc1123" } }, - skuName: { - serializedName: "x-ms-sku-name", - xmlName: "x-ms-sku-name", - type: { - name: "Enum", - allowedValues: [ - "Standard_LRS", - "Standard_GRS", - "Standard_RAGRS", - "Standard_ZRS", - "Premium_LRS" - ] - } - }, - accountKind: { - serializedName: "x-ms-account-kind", - xmlName: "x-ms-account-kind", - type: { - name: "Enum", - allowedValues: [ - "Storage", - "BlobStorage", - "StorageV2", - "FileStorage", - "BlockBlobStorage" - ] - } - }, - isHierarchicalNamespaceEnabled: { - serializedName: "x-ms-is-hns-enabled", - xmlName: "x-ms-is-hns-enabled", - type: { - name: "Boolean" - } - }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", @@ -53471,11 +66396,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ServiceGetAccountInfoExceptionHeaders = { - serializedName: "Service_getAccountInfoExceptionHeaders", + var ContainerRenameExceptionHeaders = { + serializedName: "Container_renameExceptionHeaders", type: { name: "Composite", - className: "ServiceGetAccountInfoExceptionHeaders", + className: "ContainerRenameExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -53487,11 +66412,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ServiceSubmitBatchHeaders = { - serializedName: "Service_submitBatchHeaders", + var ContainerSubmitBatchHeaders = { + serializedName: "Container_submitBatchHeaders", type: { name: "Composite", - className: "ServiceSubmitBatchHeaders", + className: "ContainerSubmitBatchHeaders", modelProperties: { contentType: { serializedName: "content-type", @@ -53513,29 +66438,15 @@ var require_mappers = __commonJS({ type: { name: "String" } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } } } } }; - exports2.ServiceSubmitBatchExceptionHeaders = { - serializedName: "Service_submitBatchExceptionHeaders", + var ContainerSubmitBatchExceptionHeaders = { + serializedName: "Container_submitBatchExceptionHeaders", type: { name: "Composite", - className: "ServiceSubmitBatchExceptionHeaders", + className: "ContainerSubmitBatchExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -53547,11 +66458,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ServiceFilterBlobsHeaders = { - serializedName: "Service_filterBlobsHeaders", + var ContainerFilterBlobsHeaders = { + serializedName: "Container_filterBlobsHeaders", type: { name: "Composite", - className: "ServiceFilterBlobsHeaders", + className: "ContainerFilterBlobsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", @@ -53580,22 +66491,15 @@ var require_mappers = __commonJS({ type: { name: "DateTimeRfc1123" } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } } } } }; - exports2.ServiceFilterBlobsExceptionHeaders = { - serializedName: "Service_filterBlobsExceptionHeaders", + var ContainerFilterBlobsExceptionHeaders = { + serializedName: "Container_filterBlobsExceptionHeaders", type: { name: "Composite", - className: "ServiceFilterBlobsExceptionHeaders", + className: "ContainerFilterBlobsExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -53607,11 +66511,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerCreateHeaders = { - serializedName: "Container_createHeaders", + var ContainerAcquireLeaseHeaders = { + serializedName: "Container_acquireLeaseHeaders", type: { name: "Composite", - className: "ContainerCreateHeaders", + className: "ContainerAcquireLeaseHeaders", modelProperties: { etag: { serializedName: "etag", @@ -53627,6 +66531,13 @@ var require_mappers = __commonJS({ name: "DateTimeRfc1123" } }, + leaseId: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", @@ -53654,22 +66565,15 @@ var require_mappers = __commonJS({ type: { name: "DateTimeRfc1123" } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } } } } }; - exports2.ContainerCreateExceptionHeaders = { - serializedName: "Container_createExceptionHeaders", + var ContainerAcquireLeaseExceptionHeaders = { + serializedName: "Container_acquireLeaseExceptionHeaders", type: { name: "Composite", - className: "ContainerCreateExceptionHeaders", + className: "ContainerAcquireLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -53681,21 +66585,12 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerGetPropertiesHeaders = { - serializedName: "Container_getPropertiesHeaders", + var ContainerReleaseLeaseHeaders = { + serializedName: "Container_releaseLeaseHeaders", type: { name: "Composite", - className: "ContainerGetPropertiesHeaders", + className: "ContainerReleaseLeaseHeaders", modelProperties: { - metadata: { - serializedName: "x-ms-meta", - headerCollectionPrefix: "x-ms-meta-", - xmlName: "x-ms-meta", - type: { - name: "Dictionary", - value: { type: { name: "String" } } - } - }, etag: { serializedName: "etag", xmlName: "etag", @@ -53710,36 +66605,6 @@ var require_mappers = __commonJS({ name: "DateTimeRfc1123" } }, - leaseDuration: { - serializedName: "x-ms-lease-duration", - xmlName: "x-ms-lease-duration", - type: { - name: "Enum", - allowedValues: ["infinite", "fixed"] - } - }, - leaseState: { - serializedName: "x-ms-lease-state", - xmlName: "x-ms-lease-state", - type: { - name: "Enum", - allowedValues: [ - "available", - "leased", - "expired", - "breaking", - "broken" - ] - } - }, - leaseStatus: { - serializedName: "x-ms-lease-status", - xmlName: "x-ms-lease-status", - type: { - name: "Enum", - allowedValues: ["locked", "unlocked"] - } - }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", @@ -53767,65 +66632,15 @@ var require_mappers = __commonJS({ type: { name: "DateTimeRfc1123" } - }, - blobPublicAccess: { - serializedName: "x-ms-blob-public-access", - xmlName: "x-ms-blob-public-access", - type: { - name: "Enum", - allowedValues: ["container", "blob"] - } - }, - hasImmutabilityPolicy: { - serializedName: "x-ms-has-immutability-policy", - xmlName: "x-ms-has-immutability-policy", - type: { - name: "Boolean" - } - }, - hasLegalHold: { - serializedName: "x-ms-has-legal-hold", - xmlName: "x-ms-has-legal-hold", - type: { - name: "Boolean" - } - }, - defaultEncryptionScope: { - serializedName: "x-ms-default-encryption-scope", - xmlName: "x-ms-default-encryption-scope", - type: { - name: "String" - } - }, - denyEncryptionScopeOverride: { - serializedName: "x-ms-deny-encryption-scope-override", - xmlName: "x-ms-deny-encryption-scope-override", - type: { - name: "Boolean" - } - }, - isImmutableStorageWithVersioningEnabled: { - serializedName: "x-ms-immutable-storage-with-versioning-enabled", - xmlName: "x-ms-immutable-storage-with-versioning-enabled", - type: { - name: "Boolean" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } } } } }; - exports2.ContainerGetPropertiesExceptionHeaders = { - serializedName: "Container_getPropertiesExceptionHeaders", + var ContainerReleaseLeaseExceptionHeaders = { + serializedName: "Container_releaseLeaseExceptionHeaders", type: { name: "Composite", - className: "ContainerGetPropertiesExceptionHeaders", + className: "ContainerReleaseLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -53837,12 +66652,33 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerDeleteHeaders = { - serializedName: "Container_deleteHeaders", + var ContainerRenewLeaseHeaders = { + serializedName: "Container_renewLeaseHeaders", type: { name: "Composite", - className: "ContainerDeleteHeaders", + className: "ContainerRenewLeaseHeaders", modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", @@ -53870,22 +66706,15 @@ var require_mappers = __commonJS({ type: { name: "DateTimeRfc1123" } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } } } } }; - exports2.ContainerDeleteExceptionHeaders = { - serializedName: "Container_deleteExceptionHeaders", + var ContainerRenewLeaseExceptionHeaders = { + serializedName: "Container_renewLeaseExceptionHeaders", type: { name: "Composite", - className: "ContainerDeleteExceptionHeaders", + className: "ContainerRenewLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -53897,11 +66726,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerSetMetadataHeaders = { - serializedName: "Container_setMetadataHeaders", + var ContainerBreakLeaseHeaders = { + serializedName: "Container_breakLeaseHeaders", type: { name: "Composite", - className: "ContainerSetMetadataHeaders", + className: "ContainerBreakLeaseHeaders", modelProperties: { etag: { serializedName: "etag", @@ -53917,6 +66746,13 @@ var require_mappers = __commonJS({ name: "DateTimeRfc1123" } }, + leaseTime: { + serializedName: "x-ms-lease-time", + xmlName: "x-ms-lease-time", + type: { + name: "Number" + } + }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", @@ -53944,22 +66780,15 @@ var require_mappers = __commonJS({ type: { name: "DateTimeRfc1123" } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } } } } }; - exports2.ContainerSetMetadataExceptionHeaders = { - serializedName: "Container_setMetadataExceptionHeaders", + var ContainerBreakLeaseExceptionHeaders = { + serializedName: "Container_breakLeaseExceptionHeaders", type: { name: "Composite", - className: "ContainerSetMetadataExceptionHeaders", + className: "ContainerBreakLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -53971,20 +66800,12 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerGetAccessPolicyHeaders = { - serializedName: "Container_getAccessPolicyHeaders", + var ContainerChangeLeaseHeaders = { + serializedName: "Container_changeLeaseHeaders", type: { name: "Composite", - className: "ContainerGetAccessPolicyHeaders", + className: "ContainerChangeLeaseHeaders", modelProperties: { - blobPublicAccess: { - serializedName: "x-ms-blob-public-access", - xmlName: "x-ms-blob-public-access", - type: { - name: "Enum", - allowedValues: ["container", "blob"] - } - }, etag: { serializedName: "etag", xmlName: "etag", @@ -53999,6 +66820,13 @@ var require_mappers = __commonJS({ name: "DateTimeRfc1123" } }, + leaseId: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", @@ -54026,22 +66854,15 @@ var require_mappers = __commonJS({ type: { name: "DateTimeRfc1123" } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } } } } }; - exports2.ContainerGetAccessPolicyExceptionHeaders = { - serializedName: "Container_getAccessPolicyExceptionHeaders", + var ContainerChangeLeaseExceptionHeaders = { + serializedName: "Container_changeLeaseExceptionHeaders", type: { name: "Composite", - className: "ContainerGetAccessPolicyExceptionHeaders", + className: "ContainerChangeLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -54053,26 +66874,19 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerSetAccessPolicyHeaders = { - serializedName: "Container_setAccessPolicyHeaders", + var ContainerListBlobFlatSegmentHeaders = { + serializedName: "Container_listBlobFlatSegmentHeaders", type: { name: "Composite", - className: "ContainerSetAccessPolicyHeaders", + className: "ContainerListBlobFlatSegmentHeaders", modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", + contentType: { + serializedName: "content-type", + xmlName: "content-type", type: { name: "String" } }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", @@ -54111,11 +66925,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerSetAccessPolicyExceptionHeaders = { - serializedName: "Container_setAccessPolicyExceptionHeaders", + var ContainerListBlobFlatSegmentExceptionHeaders = { + serializedName: "Container_listBlobFlatSegmentExceptionHeaders", type: { name: "Composite", - className: "ContainerSetAccessPolicyExceptionHeaders", + className: "ContainerListBlobFlatSegmentExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -54127,12 +66941,19 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerRestoreHeaders = { - serializedName: "Container_restoreHeaders", + var ContainerListBlobFlatSegmentApacheArrowHeaders = { + serializedName: "Container_listBlobFlatSegmentApacheArrowHeaders", type: { name: "Composite", - className: "ContainerRestoreHeaders", + className: "ContainerListBlobFlatSegmentApacheArrowHeaders", modelProperties: { + contentType: { + serializedName: "content-type", + xmlName: "content-type", + type: { + name: "String" + } + }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", @@ -54160,22 +66981,15 @@ var require_mappers = __commonJS({ type: { name: "DateTimeRfc1123" } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } } } } }; - exports2.ContainerRestoreExceptionHeaders = { - serializedName: "Container_restoreExceptionHeaders", + var ContainerListBlobFlatSegmentApacheArrowExceptionHeaders = { + serializedName: "Container_listBlobFlatSegmentApacheArrowExceptionHeaders", type: { name: "Composite", - className: "ContainerRestoreExceptionHeaders", + className: "ContainerListBlobFlatSegmentApacheArrowExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -54187,12 +67001,19 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerRenameHeaders = { - serializedName: "Container_renameHeaders", + var ContainerListBlobHierarchySegmentHeaders = { + serializedName: "Container_listBlobHierarchySegmentHeaders", type: { name: "Composite", - className: "ContainerRenameHeaders", + className: "ContainerListBlobHierarchySegmentHeaders", modelProperties: { + contentType: { + serializedName: "content-type", + xmlName: "content-type", + type: { + name: "String" + } + }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", @@ -54231,11 +67052,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerRenameExceptionHeaders = { - serializedName: "Container_renameExceptionHeaders", + var ContainerListBlobHierarchySegmentExceptionHeaders = { + serializedName: "Container_listBlobHierarchySegmentExceptionHeaders", type: { name: "Composite", - className: "ContainerRenameExceptionHeaders", + className: "ContainerListBlobHierarchySegmentExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -54247,11 +67068,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerSubmitBatchHeaders = { - serializedName: "Container_submitBatchHeaders", + var ContainerListBlobHierarchySegmentApacheArrowHeaders = { + serializedName: "Container_listBlobHierarchySegmentApacheArrowHeaders", type: { name: "Composite", - className: "ContainerSubmitBatchHeaders", + className: "ContainerListBlobHierarchySegmentApacheArrowHeaders", modelProperties: { contentType: { serializedName: "content-type", @@ -54260,6 +67081,13 @@ var require_mappers = __commonJS({ name: "String" } }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", @@ -54273,15 +67101,22 @@ var require_mappers = __commonJS({ type: { name: "String" } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } } } } }; - exports2.ContainerSubmitBatchExceptionHeaders = { - serializedName: "Container_submitBatchExceptionHeaders", + var ContainerListBlobHierarchySegmentApacheArrowExceptionHeaders = { + serializedName: "Container_listBlobHierarchySegmentApacheArrowExceptionHeaders", type: { name: "Composite", - className: "ContainerSubmitBatchExceptionHeaders", + className: "ContainerListBlobHierarchySegmentApacheArrowExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", @@ -54293,11 +67128,11 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerFilterBlobsHeaders = { - serializedName: "Container_filterBlobsHeaders", + var ContainerGetAccountInfoHeaders = { + serializedName: "Container_getAccountInfoHeaders", type: { name: "Composite", - className: "ContainerFilterBlobsHeaders", + className: "ContainerGetAccountInfoHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", @@ -54326,569 +67161,22 @@ var require_mappers = __commonJS({ type: { name: "DateTimeRfc1123" } - } - } - } - }; - exports2.ContainerFilterBlobsExceptionHeaders = { - serializedName: "Container_filterBlobsExceptionHeaders", - type: { - name: "Composite", - className: "ContainerFilterBlobsExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", + }, + skuName: { + serializedName: "x-ms-sku-name", + xmlName: "x-ms-sku-name", type: { - name: "String" - } - } - } - } - }; - exports2.ContainerAcquireLeaseHeaders = { - serializedName: "Container_acquireLeaseHeaders", - type: { - name: "Composite", - className: "ContainerAcquireLeaseHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - leaseId: { - serializedName: "x-ms-lease-id", - xmlName: "x-ms-lease-id", - type: { - name: "String" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } - } - }; - exports2.ContainerAcquireLeaseExceptionHeaders = { - serializedName: "Container_acquireLeaseExceptionHeaders", - type: { - name: "Composite", - className: "ContainerAcquireLeaseExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } - } - }; - exports2.ContainerReleaseLeaseHeaders = { - serializedName: "Container_releaseLeaseHeaders", - type: { - name: "Composite", - className: "ContainerReleaseLeaseHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } - } - }; - exports2.ContainerReleaseLeaseExceptionHeaders = { - serializedName: "Container_releaseLeaseExceptionHeaders", - type: { - name: "Composite", - className: "ContainerReleaseLeaseExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } - } - }; - exports2.ContainerRenewLeaseHeaders = { - serializedName: "Container_renewLeaseHeaders", - type: { - name: "Composite", - className: "ContainerRenewLeaseHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - leaseId: { - serializedName: "x-ms-lease-id", - xmlName: "x-ms-lease-id", - type: { - name: "String" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } - } - }; - exports2.ContainerRenewLeaseExceptionHeaders = { - serializedName: "Container_renewLeaseExceptionHeaders", - type: { - name: "Composite", - className: "ContainerRenewLeaseExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } - } - }; - exports2.ContainerBreakLeaseHeaders = { - serializedName: "Container_breakLeaseHeaders", - type: { - name: "Composite", - className: "ContainerBreakLeaseHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - leaseTime: { - serializedName: "x-ms-lease-time", - xmlName: "x-ms-lease-time", - type: { - name: "Number" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } - } - }; - exports2.ContainerBreakLeaseExceptionHeaders = { - serializedName: "Container_breakLeaseExceptionHeaders", - type: { - name: "Composite", - className: "ContainerBreakLeaseExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } - } - }; - exports2.ContainerChangeLeaseHeaders = { - serializedName: "Container_changeLeaseHeaders", - type: { - name: "Composite", - className: "ContainerChangeLeaseHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - leaseId: { - serializedName: "x-ms-lease-id", - xmlName: "x-ms-lease-id", - type: { - name: "String" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } - } - }; - exports2.ContainerChangeLeaseExceptionHeaders = { - serializedName: "Container_changeLeaseExceptionHeaders", - type: { - name: "Composite", - className: "ContainerChangeLeaseExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } - } - }; - exports2.ContainerListBlobFlatSegmentHeaders = { - serializedName: "Container_listBlobFlatSegmentHeaders", - type: { - name: "Composite", - className: "ContainerListBlobFlatSegmentHeaders", - modelProperties: { - contentType: { - serializedName: "content-type", - xmlName: "content-type", - type: { - name: "String" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } - } - }; - exports2.ContainerListBlobFlatSegmentExceptionHeaders = { - serializedName: "Container_listBlobFlatSegmentExceptionHeaders", - type: { - name: "Composite", - className: "ContainerListBlobFlatSegmentExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } - } - }; - exports2.ContainerListBlobHierarchySegmentHeaders = { - serializedName: "Container_listBlobHierarchySegmentHeaders", - type: { - name: "Composite", - className: "ContainerListBlobHierarchySegmentHeaders", - modelProperties: { - contentType: { - serializedName: "content-type", - xmlName: "content-type", - type: { - name: "String" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } - } - }; - exports2.ContainerListBlobHierarchySegmentExceptionHeaders = { - serializedName: "Container_listBlobHierarchySegmentExceptionHeaders", - type: { - name: "Composite", - className: "ContainerListBlobHierarchySegmentExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } - } - }; - exports2.ContainerGetAccountInfoHeaders = { - serializedName: "Container_getAccountInfoHeaders", - type: { - name: "Composite", - className: "ContainerGetAccountInfoHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - skuName: { - serializedName: "x-ms-sku-name", - xmlName: "x-ms-sku-name", - type: { - name: "Enum", - allowedValues: [ - "Standard_LRS", - "Standard_GRS", - "Standard_RAGRS", - "Standard_ZRS", - "Premium_LRS" - ] + name: "Enum", + allowedValues: [ + "Standard_LRS", + "Standard_GRS", + "Standard_RAGRS", + "Standard_ZRS", + "Premium_LRS", + "Standard_GZRS", + "Premium_ZRS", + "Standard_RAGZRS" + ] } }, accountKind: { @@ -54915,7 +67203,7 @@ var require_mappers = __commonJS({ } } }; - exports2.ContainerGetAccountInfoExceptionHeaders = { + var ContainerGetAccountInfoExceptionHeaders = { serializedName: "Container_getAccountInfoExceptionHeaders", type: { name: "Composite", @@ -54931,7 +67219,7 @@ var require_mappers = __commonJS({ } } }; - exports2.BlobDownloadHeaders = { + var BlobDownloadHeaders = { serializedName: "Blob_downloadHeaders", type: { name: "Composite", @@ -55254,6 +67542,48 @@ var require_mappers = __commonJS({ name: "Boolean" } }, + structuredBodyType: { + serializedName: "x-ms-structured-body", + xmlName: "x-ms-structured-body", + type: { + name: "String" + } + }, + structuredContentLength: { + serializedName: "x-ms-structured-content-length", + xmlName: "x-ms-structured-content-length", + type: { + name: "Number" + } + }, + accessTier: { + serializedName: "x-ms-access-tier", + xmlName: "x-ms-access-tier", + type: { + name: "String" + } + }, + accessTierInferred: { + serializedName: "x-ms-access-tier-inferred", + xmlName: "x-ms-access-tier-inferred", + type: { + name: "Boolean" + } + }, + accessTierChangedOn: { + serializedName: "x-ms-access-tier-change-time", + xmlName: "x-ms-access-tier-change-time", + type: { + name: "DateTimeRfc1123" + } + }, + smartAccessTier: { + serializedName: "x-ms-smart-access-tier", + xmlName: "x-ms-smart-access-tier", + type: { + name: "String" + } + }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", @@ -55271,7 +67601,7 @@ var require_mappers = __commonJS({ } } }; - exports2.BlobDownloadExceptionHeaders = { + var BlobDownloadExceptionHeaders = { serializedName: "Blob_downloadExceptionHeaders", type: { name: "Composite", @@ -55287,7 +67617,7 @@ var require_mappers = __commonJS({ } } }; - exports2.BlobGetPropertiesHeaders = { + var BlobGetPropertiesHeaders = { serializedName: "Blob_getPropertiesHeaders", type: { name: "Composite", @@ -55581,6 +67911,13 @@ var require_mappers = __commonJS({ name: "DateTimeRfc1123" } }, + smartAccessTier: { + serializedName: "x-ms-smart-access-tier", + xmlName: "x-ms-smart-access-tier", + type: { + name: "String" + } + }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", @@ -55663,7 +68000,7 @@ var require_mappers = __commonJS({ } } }; - exports2.BlobGetPropertiesExceptionHeaders = { + var BlobGetPropertiesExceptionHeaders = { serializedName: "Blob_getPropertiesExceptionHeaders", type: { name: "Composite", @@ -55679,7 +68016,7 @@ var require_mappers = __commonJS({ } } }; - exports2.BlobDeleteHeaders = { + var BlobDeleteHeaders = { serializedName: "Blob_deleteHeaders", type: { name: "Composite", @@ -55721,8756 +68058,25843 @@ var require_mappers = __commonJS({ } } } - } + } + }; + var BlobDeleteExceptionHeaders = { + serializedName: "Blob_deleteExceptionHeaders", + type: { + name: "Composite", + className: "BlobDeleteExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobUndeleteHeaders = { + serializedName: "Blob_undeleteHeaders", + type: { + name: "Composite", + className: "BlobUndeleteHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobUndeleteExceptionHeaders = { + serializedName: "Blob_undeleteExceptionHeaders", + type: { + name: "Composite", + className: "BlobUndeleteExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetExpiryHeaders = { + serializedName: "Blob_setExpiryHeaders", + type: { + name: "Composite", + className: "BlobSetExpiryHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobSetExpiryExceptionHeaders = { + serializedName: "Blob_setExpiryExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetExpiryExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetHttpHeadersHeaders = { + serializedName: "Blob_setHttpHeadersHeaders", + type: { + name: "Composite", + className: "BlobSetHttpHeadersHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetHttpHeadersExceptionHeaders = { + serializedName: "Blob_setHttpHeadersExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetHttpHeadersExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetImmutabilityPolicyHeaders = { + serializedName: "Blob_setImmutabilityPolicyHeaders", + type: { + name: "Composite", + className: "BlobSetImmutabilityPolicyHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyExpiry: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyMode: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + } + } + } + }; + var BlobSetImmutabilityPolicyExceptionHeaders = { + serializedName: "Blob_setImmutabilityPolicyExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetImmutabilityPolicyExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobDeleteImmutabilityPolicyHeaders = { + serializedName: "Blob_deleteImmutabilityPolicyHeaders", + type: { + name: "Composite", + className: "BlobDeleteImmutabilityPolicyHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobDeleteImmutabilityPolicyExceptionHeaders = { + serializedName: "Blob_deleteImmutabilityPolicyExceptionHeaders", + type: { + name: "Composite", + className: "BlobDeleteImmutabilityPolicyExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetLegalHoldHeaders = { + serializedName: "Blob_setLegalHoldHeaders", + type: { + name: "Composite", + className: "BlobSetLegalHoldHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + legalHold: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + } + } + } + }; + var BlobSetLegalHoldExceptionHeaders = { + serializedName: "Blob_setLegalHoldExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetLegalHoldExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetMetadataHeaders = { + serializedName: "Blob_setMetadataHeaders", + type: { + name: "Composite", + className: "BlobSetMetadataHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetMetadataExceptionHeaders = { + serializedName: "Blob_setMetadataExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetMetadataExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobAcquireLeaseHeaders = { + serializedName: "Blob_acquireLeaseHeaders", + type: { + name: "Composite", + className: "BlobAcquireLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobAcquireLeaseExceptionHeaders = { + serializedName: "Blob_acquireLeaseExceptionHeaders", + type: { + name: "Composite", + className: "BlobAcquireLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobReleaseLeaseHeaders = { + serializedName: "Blob_releaseLeaseHeaders", + type: { + name: "Composite", + className: "BlobReleaseLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobReleaseLeaseExceptionHeaders = { + serializedName: "Blob_releaseLeaseExceptionHeaders", + type: { + name: "Composite", + className: "BlobReleaseLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobRenewLeaseHeaders = { + serializedName: "Blob_renewLeaseHeaders", + type: { + name: "Composite", + className: "BlobRenewLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobRenewLeaseExceptionHeaders = { + serializedName: "Blob_renewLeaseExceptionHeaders", + type: { + name: "Composite", + className: "BlobRenewLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobChangeLeaseHeaders = { + serializedName: "Blob_changeLeaseHeaders", + type: { + name: "Composite", + className: "BlobChangeLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobChangeLeaseExceptionHeaders = { + serializedName: "Blob_changeLeaseExceptionHeaders", + type: { + name: "Composite", + className: "BlobChangeLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobBreakLeaseHeaders = { + serializedName: "Blob_breakLeaseHeaders", + type: { + name: "Composite", + className: "BlobBreakLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseTime: { + serializedName: "x-ms-lease-time", + xmlName: "x-ms-lease-time", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobBreakLeaseExceptionHeaders = { + serializedName: "Blob_breakLeaseExceptionHeaders", + type: { + name: "Composite", + className: "BlobBreakLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobCreateSnapshotHeaders = { + serializedName: "Blob_createSnapshotHeaders", + type: { + name: "Composite", + className: "BlobCreateSnapshotHeaders", + modelProperties: { + snapshot: { + serializedName: "x-ms-snapshot", + xmlName: "x-ms-snapshot", + type: { + name: "String" + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobCreateSnapshotExceptionHeaders = { + serializedName: "Blob_createSnapshotExceptionHeaders", + type: { + name: "Composite", + className: "BlobCreateSnapshotExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobStartCopyFromURLHeaders = { + serializedName: "Blob_startCopyFromURLHeaders", + type: { + name: "Composite", + className: "BlobStartCopyFromURLHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + xmlName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + xmlName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: ["pending", "success", "aborted", "failed"] + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobStartCopyFromURLExceptionHeaders = { + serializedName: "Blob_startCopyFromURLExceptionHeaders", + type: { + name: "Composite", + className: "BlobStartCopyFromURLExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + }, + copySourceErrorCode: { + serializedName: "x-ms-copy-source-error-code", + xmlName: "x-ms-copy-source-error-code", + type: { + name: "String" + } + }, + copySourceStatusCode: { + serializedName: "x-ms-copy-source-status-code", + xmlName: "x-ms-copy-source-status-code", + type: { + name: "Number" + } + } + } + } + }; + var BlobCopyFromURLHeaders = { + serializedName: "Blob_copyFromURLHeaders", + type: { + name: "Composite", + className: "BlobCopyFromURLHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + xmlName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyStatus: { + defaultValue: "success", + isConstant: true, + serializedName: "x-ms-copy-status", + type: { + name: "String" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobCopyFromURLExceptionHeaders = { + serializedName: "Blob_copyFromURLExceptionHeaders", + type: { + name: "Composite", + className: "BlobCopyFromURLExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + }, + copySourceErrorCode: { + serializedName: "x-ms-copy-source-error-code", + xmlName: "x-ms-copy-source-error-code", + type: { + name: "String" + } + }, + copySourceStatusCode: { + serializedName: "x-ms-copy-source-status-code", + xmlName: "x-ms-copy-source-status-code", + type: { + name: "Number" + } + } + } + } + }; + var BlobAbortCopyFromURLHeaders = { + serializedName: "Blob_abortCopyFromURLHeaders", + type: { + name: "Composite", + className: "BlobAbortCopyFromURLHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobAbortCopyFromURLExceptionHeaders = { + serializedName: "Blob_abortCopyFromURLExceptionHeaders", + type: { + name: "Composite", + className: "BlobAbortCopyFromURLExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetTierHeaders = { + serializedName: "Blob_setTierHeaders", + type: { + name: "Composite", + className: "BlobSetTierHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetTierExceptionHeaders = { + serializedName: "Blob_setTierExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetTierExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobGetAccountInfoHeaders = { + serializedName: "Blob_getAccountInfoHeaders", + type: { + name: "Composite", + className: "BlobGetAccountInfoHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + skuName: { + serializedName: "x-ms-sku-name", + xmlName: "x-ms-sku-name", + type: { + name: "Enum", + allowedValues: [ + "Standard_LRS", + "Standard_GRS", + "Standard_RAGRS", + "Standard_ZRS", + "Premium_LRS", + "Standard_GZRS", + "Premium_ZRS", + "Standard_RAGZRS" + ] + } + }, + accountKind: { + serializedName: "x-ms-account-kind", + xmlName: "x-ms-account-kind", + type: { + name: "Enum", + allowedValues: [ + "Storage", + "BlobStorage", + "StorageV2", + "FileStorage", + "BlockBlobStorage" + ] + } + }, + isHierarchicalNamespaceEnabled: { + serializedName: "x-ms-is-hns-enabled", + xmlName: "x-ms-is-hns-enabled", + type: { + name: "Boolean" + } + } + } + } + }; + var BlobGetAccountInfoExceptionHeaders = { + serializedName: "Blob_getAccountInfoExceptionHeaders", + type: { + name: "Composite", + className: "BlobGetAccountInfoExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobQueryHeaders = { + serializedName: "Blob_queryHeaders", + type: { + name: "Composite", + className: "BlobQueryHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + metadata: { + serializedName: "x-ms-meta", + headerCollectionPrefix: "x-ms-meta-", + xmlName: "x-ms-meta", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + }, + contentLength: { + serializedName: "content-length", + xmlName: "content-length", + type: { + name: "Number" + } + }, + contentType: { + serializedName: "content-type", + xmlName: "content-type", + type: { + name: "String" + } + }, + contentRange: { + serializedName: "content-range", + xmlName: "content-range", + type: { + name: "String" + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + contentEncoding: { + serializedName: "content-encoding", + xmlName: "content-encoding", + type: { + name: "String" + } + }, + cacheControl: { + serializedName: "cache-control", + xmlName: "cache-control", + type: { + name: "String" + } + }, + contentDisposition: { + serializedName: "content-disposition", + xmlName: "content-disposition", + type: { + name: "String" + } + }, + contentLanguage: { + serializedName: "content-language", + xmlName: "content-language", + type: { + name: "String" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + blobType: { + serializedName: "x-ms-blob-type", + xmlName: "x-ms-blob-type", + type: { + name: "Enum", + allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"] + } + }, + copyCompletionTime: { + serializedName: "x-ms-copy-completion-time", + xmlName: "x-ms-copy-completion-time", + type: { + name: "DateTimeRfc1123" + } + }, + copyStatusDescription: { + serializedName: "x-ms-copy-status-description", + xmlName: "x-ms-copy-status-description", + type: { + name: "String" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + xmlName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyProgress: { + serializedName: "x-ms-copy-progress", + xmlName: "x-ms-copy-progress", + type: { + name: "String" + } + }, + copySource: { + serializedName: "x-ms-copy-source", + xmlName: "x-ms-copy-source", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + xmlName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: ["pending", "success", "aborted", "failed"] + } + }, + leaseDuration: { + serializedName: "x-ms-lease-duration", + xmlName: "x-ms-lease-duration", + type: { + name: "Enum", + allowedValues: ["infinite", "fixed"] + } + }, + leaseState: { + serializedName: "x-ms-lease-state", + xmlName: "x-ms-lease-state", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseStatus: { + serializedName: "x-ms-lease-status", + xmlName: "x-ms-lease-status", + type: { + name: "Enum", + allowedValues: ["locked", "unlocked"] + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + acceptRanges: { + serializedName: "accept-ranges", + xmlName: "accept-ranges", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + blobCommittedBlockCount: { + serializedName: "x-ms-blob-committed-block-count", + xmlName: "x-ms-blob-committed-block-count", + type: { + name: "Number" + } + }, + isServerEncrypted: { + serializedName: "x-ms-server-encrypted", + xmlName: "x-ms-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + blobContentMD5: { + serializedName: "x-ms-blob-content-md5", + xmlName: "x-ms-blob-content-md5", + type: { + name: "ByteArray" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + }, + contentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + } + } + } + }; + var BlobQueryExceptionHeaders = { + serializedName: "Blob_queryExceptionHeaders", + type: { + name: "Composite", + className: "BlobQueryExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobGetTagsHeaders = { + serializedName: "Blob_getTagsHeaders", + type: { + name: "Composite", + className: "BlobGetTagsHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobGetTagsExceptionHeaders = { + serializedName: "Blob_getTagsExceptionHeaders", + type: { + name: "Composite", + className: "BlobGetTagsExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetTagsHeaders = { + serializedName: "Blob_setTagsHeaders", + type: { + name: "Composite", + className: "BlobSetTagsHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetTagsExceptionHeaders = { + serializedName: "Blob_setTagsExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetTagsExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobCreateHeaders = { + serializedName: "PageBlob_createHeaders", + type: { + name: "Composite", + className: "PageBlobCreateHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobCreateExceptionHeaders = { + serializedName: "PageBlob_createExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobCreateExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobUploadPagesHeaders = { + serializedName: "PageBlob_uploadPagesHeaders", + type: { + name: "Composite", + className: "PageBlobUploadPagesHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + structuredBodyType: { + serializedName: "x-ms-structured-body", + xmlName: "x-ms-structured-body", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobUploadPagesExceptionHeaders = { + serializedName: "PageBlob_uploadPagesExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobUploadPagesExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobClearPagesHeaders = { + serializedName: "PageBlob_clearPagesHeaders", + type: { + name: "Composite", + className: "PageBlobClearPagesHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobClearPagesExceptionHeaders = { + serializedName: "PageBlob_clearPagesExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobClearPagesExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobUploadPagesFromURLHeaders = { + serializedName: "PageBlob_uploadPagesFromURLHeaders", + type: { + name: "Composite", + className: "PageBlobUploadPagesFromURLHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobUploadPagesFromURLExceptionHeaders = { + serializedName: "PageBlob_uploadPagesFromURLExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobUploadPagesFromURLExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + }, + copySourceErrorCode: { + serializedName: "x-ms-copy-source-error-code", + xmlName: "x-ms-copy-source-error-code", + type: { + name: "String" + } + }, + copySourceStatusCode: { + serializedName: "x-ms-copy-source-status-code", + xmlName: "x-ms-copy-source-status-code", + type: { + name: "Number" + } + } + } + } + }; + var PageBlobGetPageRangesHeaders = { + serializedName: "PageBlob_getPageRangesHeaders", + type: { + name: "Composite", + className: "PageBlobGetPageRangesHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + blobContentLength: { + serializedName: "x-ms-blob-content-length", + xmlName: "x-ms-blob-content-length", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobGetPageRangesExceptionHeaders = { + serializedName: "PageBlob_getPageRangesExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobGetPageRangesExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobGetPageRangesDiffHeaders = { + serializedName: "PageBlob_getPageRangesDiffHeaders", + type: { + name: "Composite", + className: "PageBlobGetPageRangesDiffHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + blobContentLength: { + serializedName: "x-ms-blob-content-length", + xmlName: "x-ms-blob-content-length", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobGetPageRangesDiffExceptionHeaders = { + serializedName: "PageBlob_getPageRangesDiffExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobGetPageRangesDiffExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobResizeHeaders = { + serializedName: "PageBlob_resizeHeaders", + type: { + name: "Composite", + className: "PageBlobResizeHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobResizeExceptionHeaders = { + serializedName: "PageBlob_resizeExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobResizeExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobUpdateSequenceNumberHeaders = { + serializedName: "PageBlob_updateSequenceNumberHeaders", + type: { + name: "Composite", + className: "PageBlobUpdateSequenceNumberHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobUpdateSequenceNumberExceptionHeaders = { + serializedName: "PageBlob_updateSequenceNumberExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobUpdateSequenceNumberExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobCopyIncrementalHeaders = { + serializedName: "PageBlob_copyIncrementalHeaders", + type: { + name: "Composite", + className: "PageBlobCopyIncrementalHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + xmlName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + xmlName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: ["pending", "success", "aborted", "failed"] + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobCopyIncrementalExceptionHeaders = { + serializedName: "PageBlob_copyIncrementalExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobCopyIncrementalExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var AppendBlobCreateHeaders = { + serializedName: "AppendBlob_createHeaders", + type: { + name: "Composite", + className: "AppendBlobCreateHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var AppendBlobCreateExceptionHeaders = { + serializedName: "AppendBlob_createExceptionHeaders", + type: { + name: "Composite", + className: "AppendBlobCreateExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var AppendBlobAppendBlockHeaders = { + serializedName: "AppendBlob_appendBlockHeaders", + type: { + name: "Composite", + className: "AppendBlobAppendBlockHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + blobAppendOffset: { + serializedName: "x-ms-blob-append-offset", + xmlName: "x-ms-blob-append-offset", + type: { + name: "String" + } + }, + blobCommittedBlockCount: { + serializedName: "x-ms-blob-committed-block-count", + xmlName: "x-ms-blob-committed-block-count", + type: { + name: "Number" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + structuredBodyType: { + serializedName: "x-ms-structured-body", + xmlName: "x-ms-structured-body", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var AppendBlobAppendBlockExceptionHeaders = { + serializedName: "AppendBlob_appendBlockExceptionHeaders", + type: { + name: "Composite", + className: "AppendBlobAppendBlockExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var AppendBlobAppendBlockFromUrlHeaders = { + serializedName: "AppendBlob_appendBlockFromUrlHeaders", + type: { + name: "Composite", + className: "AppendBlobAppendBlockFromUrlHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + blobAppendOffset: { + serializedName: "x-ms-blob-append-offset", + xmlName: "x-ms-blob-append-offset", + type: { + name: "String" + } + }, + blobCommittedBlockCount: { + serializedName: "x-ms-blob-committed-block-count", + xmlName: "x-ms-blob-committed-block-count", + type: { + name: "Number" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var AppendBlobAppendBlockFromUrlExceptionHeaders = { + serializedName: "AppendBlob_appendBlockFromUrlExceptionHeaders", + type: { + name: "Composite", + className: "AppendBlobAppendBlockFromUrlExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + }, + copySourceErrorCode: { + serializedName: "x-ms-copy-source-error-code", + xmlName: "x-ms-copy-source-error-code", + type: { + name: "String" + } + }, + copySourceStatusCode: { + serializedName: "x-ms-copy-source-status-code", + xmlName: "x-ms-copy-source-status-code", + type: { + name: "Number" + } + } + } + } + }; + var AppendBlobSealHeaders = { + serializedName: "AppendBlob_sealHeaders", + type: { + name: "Composite", + className: "AppendBlobSealHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isSealed: { + serializedName: "x-ms-blob-sealed", + xmlName: "x-ms-blob-sealed", + type: { + name: "Boolean" + } + } + } + } + }; + var AppendBlobSealExceptionHeaders = { + serializedName: "AppendBlob_sealExceptionHeaders", + type: { + name: "Composite", + className: "AppendBlobSealExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobUploadHeaders = { + serializedName: "BlockBlob_uploadHeaders", + type: { + name: "Composite", + className: "BlockBlobUploadHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + structuredBodyType: { + serializedName: "x-ms-structured-body", + xmlName: "x-ms-structured-body", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobUploadExceptionHeaders = { + serializedName: "BlockBlob_uploadExceptionHeaders", + type: { + name: "Composite", + className: "BlockBlobUploadExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobPutBlobFromUrlHeaders = { + serializedName: "BlockBlob_putBlobFromUrlHeaders", + type: { + name: "Composite", + className: "BlockBlobPutBlobFromUrlHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobPutBlobFromUrlExceptionHeaders = { + serializedName: "BlockBlob_putBlobFromUrlExceptionHeaders", + type: { + name: "Composite", + className: "BlockBlobPutBlobFromUrlExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + }, + copySourceErrorCode: { + serializedName: "x-ms-copy-source-error-code", + xmlName: "x-ms-copy-source-error-code", + type: { + name: "String" + } + }, + copySourceStatusCode: { + serializedName: "x-ms-copy-source-status-code", + xmlName: "x-ms-copy-source-status-code", + type: { + name: "Number" + } + } + } + } + }; + var BlockBlobStageBlockHeaders = { + serializedName: "BlockBlob_stageBlockHeaders", + type: { + name: "Composite", + className: "BlockBlobStageBlockHeaders", + modelProperties: { + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + structuredBodyType: { + serializedName: "x-ms-structured-body", + xmlName: "x-ms-structured-body", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobStageBlockExceptionHeaders = { + serializedName: "BlockBlob_stageBlockExceptionHeaders", + type: { + name: "Composite", + className: "BlockBlobStageBlockExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobStageBlockFromURLHeaders = { + serializedName: "BlockBlob_stageBlockFromURLHeaders", + type: { + name: "Composite", + className: "BlockBlobStageBlockFromURLHeaders", + modelProperties: { + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobStageBlockFromURLExceptionHeaders = { + serializedName: "BlockBlob_stageBlockFromURLExceptionHeaders", + type: { + name: "Composite", + className: "BlockBlobStageBlockFromURLExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + }, + copySourceErrorCode: { + serializedName: "x-ms-copy-source-error-code", + xmlName: "x-ms-copy-source-error-code", + type: { + name: "String" + } + }, + copySourceStatusCode: { + serializedName: "x-ms-copy-source-status-code", + xmlName: "x-ms-copy-source-status-code", + type: { + name: "Number" + } + } + } + } + }; + var BlockBlobCommitBlockListHeaders = { + serializedName: "BlockBlob_commitBlockListHeaders", + type: { + name: "Composite", + className: "BlockBlobCommitBlockListHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobCommitBlockListExceptionHeaders = { + serializedName: "BlockBlob_commitBlockListExceptionHeaders", + type: { + name: "Composite", + className: "BlockBlobCommitBlockListExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobGetBlockListHeaders = { + serializedName: "BlockBlob_getBlockListHeaders", + type: { + name: "Composite", + className: "BlockBlobGetBlockListHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + contentType: { + serializedName: "content-type", + xmlName: "content-type", + type: { + name: "String" + } + }, + blobContentLength: { + serializedName: "x-ms-blob-content-length", + xmlName: "x-ms-blob-content-length", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobGetBlockListExceptionHeaders = { + serializedName: "BlockBlob_getBlockListExceptionHeaders", + type: { + name: "Composite", + className: "BlockBlobGetBlockListExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/models/parameters.js +var require_parameters = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/models/parameters.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var parameters_exports = {}; + __export2(parameters_exports, { + accept: () => accept, + accept1: () => accept1, + accept2: () => accept2, + accept3: () => accept3, + access: () => access, + accessTierIfModifiedSince: () => accessTierIfModifiedSince, + accessTierIfUnmodifiedSince: () => accessTierIfUnmodifiedSince, + action: () => action, + action1: () => action1, + action2: () => action2, + action3: () => action3, + action4: () => action4, + appendPosition: () => appendPosition, + blobCacheControl: () => blobCacheControl, + blobContentDisposition: () => blobContentDisposition, + blobContentEncoding: () => blobContentEncoding, + blobContentLanguage: () => blobContentLanguage, + blobContentLength: () => blobContentLength, + blobContentMD5: () => blobContentMD5, + blobContentType: () => blobContentType, + blobDeleteType: () => blobDeleteType, + blobSequenceNumber: () => blobSequenceNumber, + blobServiceProperties: () => blobServiceProperties, + blobTagsString: () => blobTagsString, + blobType: () => blobType, + blobType1: () => blobType1, + blobType2: () => blobType2, + blockId: () => blockId, + blocks: () => blocks, + body: () => body, + body1: () => body1, + breakPeriod: () => breakPeriod, + comp: () => comp, + comp1: () => comp1, + comp10: () => comp10, + comp11: () => comp11, + comp12: () => comp12, + comp13: () => comp13, + comp14: () => comp14, + comp15: () => comp15, + comp16: () => comp16, + comp17: () => comp17, + comp18: () => comp18, + comp19: () => comp19, + comp2: () => comp2, + comp20: () => comp20, + comp21: () => comp21, + comp22: () => comp22, + comp23: () => comp23, + comp24: () => comp24, + comp25: () => comp25, + comp3: () => comp3, + comp4: () => comp4, + comp5: () => comp5, + comp6: () => comp6, + comp7: () => comp7, + comp8: () => comp8, + comp9: () => comp9, + containerAcl: () => containerAcl, + contentLength: () => contentLength, + contentType: () => contentType, + contentType1: () => contentType1, + copyActionAbortConstant: () => copyActionAbortConstant, + copyId: () => copyId, + copySource: () => copySource, + copySourceAuthorization: () => copySourceAuthorization, + copySourceBlobProperties: () => copySourceBlobProperties, + copySourceTags: () => copySourceTags, + defaultEncryptionScope: () => defaultEncryptionScope, + deleteSnapshots: () => deleteSnapshots, + deletedContainerName: () => deletedContainerName, + deletedContainerVersion: () => deletedContainerVersion, + delimiter: () => delimiter, + duration: () => duration, + encryptionAlgorithm: () => encryptionAlgorithm, + encryptionKey: () => encryptionKey, + encryptionKeySha256: () => encryptionKeySha256, + encryptionScope: () => encryptionScope, + endBefore: () => endBefore, + expiresOn: () => expiresOn, + expiryOptions: () => expiryOptions, + fileRequestIntent: () => fileRequestIntent, + ifMatch: () => ifMatch, + ifMatch1: () => ifMatch1, + ifModifiedSince: () => ifModifiedSince, + ifModifiedSince1: () => ifModifiedSince1, + ifNoneMatch: () => ifNoneMatch, + ifNoneMatch1: () => ifNoneMatch1, + ifSequenceNumberEqualTo: () => ifSequenceNumberEqualTo, + ifSequenceNumberLessThan: () => ifSequenceNumberLessThan, + ifSequenceNumberLessThanOrEqualTo: () => ifSequenceNumberLessThanOrEqualTo, + ifTags: () => ifTags, + ifUnmodifiedSince: () => ifUnmodifiedSince, + ifUnmodifiedSince1: () => ifUnmodifiedSince1, + immutabilityPolicyExpiry: () => immutabilityPolicyExpiry, + immutabilityPolicyMode: () => immutabilityPolicyMode, + include: () => include, + include1: () => include1, + keyInfo: () => keyInfo, + leaseId: () => leaseId, + leaseId1: () => leaseId1, + legalHold: () => legalHold, + legalHold1: () => legalHold1, + listType: () => listType, + marker: () => marker, + maxPageSize: () => maxPageSize, + maxSize: () => maxSize, + metadata: () => metadata, + multipartContentType: () => multipartContentType, + pageWrite: () => pageWrite, + pageWrite1: () => pageWrite1, + prefix: () => prefix, + prevSnapshotUrl: () => prevSnapshotUrl, + preventEncryptionScopeOverride: () => preventEncryptionScopeOverride, + prevsnapshot: () => prevsnapshot, + proposedLeaseId: () => proposedLeaseId, + proposedLeaseId1: () => proposedLeaseId1, + queryRequest: () => queryRequest, + range: () => range2, + range1: () => range1, + rangeGetContentCRC64: () => rangeGetContentCRC64, + rangeGetContentMD5: () => rangeGetContentMD5, + rehydratePriority: () => rehydratePriority, + requestId: () => requestId, + restype: () => restype, + restype1: () => restype1, + restype2: () => restype2, + sealBlob: () => sealBlob, + sequenceNumberAction: () => sequenceNumberAction, + snapshot: () => snapshot, + sourceContainerName: () => sourceContainerName, + sourceContentCrc64: () => sourceContentCrc64, + sourceContentMD5: () => sourceContentMD5, + sourceEncryptionAlgorithm: () => sourceEncryptionAlgorithm, + sourceEncryptionKey: () => sourceEncryptionKey, + sourceEncryptionKeySha256: () => sourceEncryptionKeySha256, + sourceIfMatch: () => sourceIfMatch, + sourceIfModifiedSince: () => sourceIfModifiedSince, + sourceIfNoneMatch: () => sourceIfNoneMatch, + sourceIfTags: () => sourceIfTags, + sourceIfUnmodifiedSince: () => sourceIfUnmodifiedSince, + sourceLeaseId: () => sourceLeaseId, + sourceRange: () => sourceRange, + sourceRange1: () => sourceRange1, + sourceUrl: () => sourceUrl, + startFrom: () => startFrom, + structuredBodyType: () => structuredBodyType, + structuredContentLength: () => structuredContentLength, + tags: () => tags, + tier: () => tier, + tier1: () => tier1, + timeoutInSeconds: () => timeoutInSeconds, + transactionalContentCrc64: () => transactionalContentCrc64, + transactionalContentMD5: () => transactionalContentMD5, + url: () => url2, + version: () => version, + versionId: () => versionId, + where: () => where, + xMsRequiresSync: () => xMsRequiresSync + }); + module2.exports = __toCommonJS2(parameters_exports); + var import_mappers = require_mappers(); + var contentType = { + parameterPath: ["options", "contentType"], + mapper: { + defaultValue: "application/xml", + isConstant: true, + serializedName: "Content-Type", + type: { + name: "String" + } + } + }; + var blobServiceProperties = { + parameterPath: "blobServiceProperties", + mapper: import_mappers.BlobServiceProperties + }; + var accept = { + parameterPath: "accept", + mapper: { + defaultValue: "application/xml", + isConstant: true, + serializedName: "Accept", + type: { + name: "String" + } + } + }; + var url2 = { + parameterPath: "url", + mapper: { + serializedName: "url", + required: true, + xmlName: "url", + type: { + name: "String" + } + }, + skipEncoding: true + }; + var restype = { + parameterPath: "restype", + mapper: { + defaultValue: "service", + isConstant: true, + serializedName: "restype", + type: { + name: "String" + } + } + }; + var comp = { + parameterPath: "comp", + mapper: { + defaultValue: "properties", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var timeoutInSeconds = { + parameterPath: ["options", "timeoutInSeconds"], + mapper: { + constraints: { + InclusiveMinimum: 0 + }, + serializedName: "timeout", + xmlName: "timeout", + type: { + name: "Number" + } + } + }; + var version = { + parameterPath: "version", + mapper: { + defaultValue: "2026-10-06", + isConstant: true, + serializedName: "x-ms-version", + type: { + name: "String" + } + } + }; + var requestId = { + parameterPath: ["options", "requestId"], + mapper: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + } + }; + var accept1 = { + parameterPath: "accept", + mapper: { + defaultValue: "application/xml", + isConstant: true, + serializedName: "Accept", + type: { + name: "String" + } + } + }; + var comp1 = { + parameterPath: "comp", + mapper: { + defaultValue: "stats", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var comp2 = { + parameterPath: "comp", + mapper: { + defaultValue: "list", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var prefix = { + parameterPath: ["options", "prefix"], + mapper: { + serializedName: "prefix", + xmlName: "prefix", + type: { + name: "String" + } + } + }; + var marker = { + parameterPath: ["options", "marker"], + mapper: { + serializedName: "marker", + xmlName: "marker", + type: { + name: "String" + } + } + }; + var maxPageSize = { + parameterPath: ["options", "maxPageSize"], + mapper: { + constraints: { + InclusiveMinimum: 1 + }, + serializedName: "maxresults", + xmlName: "maxresults", + type: { + name: "Number" + } + } + }; + var include = { + parameterPath: ["options", "include"], + mapper: { + serializedName: "include", + xmlName: "include", + xmlElementName: "ListContainersIncludeType", + type: { + name: "Sequence", + element: { + type: { + name: "Enum", + allowedValues: ["metadata", "deleted", "system"] + } + } + } + }, + collectionFormat: "CSV" + }; + var keyInfo = { + parameterPath: "keyInfo", + mapper: import_mappers.KeyInfo + }; + var comp3 = { + parameterPath: "comp", + mapper: { + defaultValue: "userdelegationkey", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var restype1 = { + parameterPath: "restype", + mapper: { + defaultValue: "account", + isConstant: true, + serializedName: "restype", + type: { + name: "String" + } + } + }; + var body = { + parameterPath: "body", + mapper: { + serializedName: "body", + required: true, + xmlName: "body", + type: { + name: "Stream" + } + } + }; + var comp4 = { + parameterPath: "comp", + mapper: { + defaultValue: "batch", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var contentLength = { + parameterPath: "contentLength", + mapper: { + serializedName: "Content-Length", + required: true, + xmlName: "Content-Length", + type: { + name: "Number" + } + } + }; + var multipartContentType = { + parameterPath: "multipartContentType", + mapper: { + serializedName: "Content-Type", + required: true, + xmlName: "Content-Type", + type: { + name: "String" + } + } + }; + var comp5 = { + parameterPath: "comp", + mapper: { + defaultValue: "blobs", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var where = { + parameterPath: ["options", "where"], + mapper: { + serializedName: "where", + xmlName: "where", + type: { + name: "String" + } + } + }; + var restype2 = { + parameterPath: "restype", + mapper: { + defaultValue: "container", + isConstant: true, + serializedName: "restype", + type: { + name: "String" + } + } + }; + var metadata = { + parameterPath: ["options", "metadata"], + mapper: { + serializedName: "x-ms-meta", + xmlName: "x-ms-meta", + headerCollectionPrefix: "x-ms-meta-", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + } + }; + var access = { + parameterPath: ["options", "access"], + mapper: { + serializedName: "x-ms-blob-public-access", + xmlName: "x-ms-blob-public-access", + type: { + name: "Enum", + allowedValues: ["container", "blob"] + } + } + }; + var defaultEncryptionScope = { + parameterPath: [ + "options", + "containerEncryptionScope", + "defaultEncryptionScope" + ], + mapper: { + serializedName: "x-ms-default-encryption-scope", + xmlName: "x-ms-default-encryption-scope", + type: { + name: "String" + } + } + }; + var preventEncryptionScopeOverride = { + parameterPath: [ + "options", + "containerEncryptionScope", + "preventEncryptionScopeOverride" + ], + mapper: { + serializedName: "x-ms-deny-encryption-scope-override", + xmlName: "x-ms-deny-encryption-scope-override", + type: { + name: "Boolean" + } + } + }; + var leaseId = { + parameterPath: ["options", "leaseAccessConditions", "leaseId"], + mapper: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + } + }; + var ifModifiedSince = { + parameterPath: ["options", "modifiedAccessConditions", "ifModifiedSince"], + mapper: { + serializedName: "If-Modified-Since", + xmlName: "If-Modified-Since", + type: { + name: "DateTimeRfc1123" + } + } + }; + var ifUnmodifiedSince = { + parameterPath: ["options", "modifiedAccessConditions", "ifUnmodifiedSince"], + mapper: { + serializedName: "If-Unmodified-Since", + xmlName: "If-Unmodified-Since", + type: { + name: "DateTimeRfc1123" + } + } + }; + var comp6 = { + parameterPath: "comp", + mapper: { + defaultValue: "metadata", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var comp7 = { + parameterPath: "comp", + mapper: { + defaultValue: "acl", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var containerAcl = { + parameterPath: ["options", "containerAcl"], + mapper: { + serializedName: "containerAcl", + xmlName: "SignedIdentifiers", + xmlIsWrapped: true, + xmlElementName: "SignedIdentifier", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "SignedIdentifier" + } + } + } + } + }; + var comp8 = { + parameterPath: "comp", + mapper: { + defaultValue: "undelete", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var deletedContainerName = { + parameterPath: ["options", "deletedContainerName"], + mapper: { + serializedName: "x-ms-deleted-container-name", + xmlName: "x-ms-deleted-container-name", + type: { + name: "String" + } + } + }; + var deletedContainerVersion = { + parameterPath: ["options", "deletedContainerVersion"], + mapper: { + serializedName: "x-ms-deleted-container-version", + xmlName: "x-ms-deleted-container-version", + type: { + name: "String" + } + } + }; + var comp9 = { + parameterPath: "comp", + mapper: { + defaultValue: "rename", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var sourceContainerName = { + parameterPath: "sourceContainerName", + mapper: { + serializedName: "x-ms-source-container-name", + required: true, + xmlName: "x-ms-source-container-name", + type: { + name: "String" + } + } + }; + var sourceLeaseId = { + parameterPath: ["options", "sourceLeaseId"], + mapper: { + serializedName: "x-ms-source-lease-id", + xmlName: "x-ms-source-lease-id", + type: { + name: "String" + } + } + }; + var comp10 = { + parameterPath: "comp", + mapper: { + defaultValue: "lease", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var action = { + parameterPath: "action", + mapper: { + defaultValue: "acquire", + isConstant: true, + serializedName: "x-ms-lease-action", + type: { + name: "String" + } + } + }; + var duration = { + parameterPath: ["options", "duration"], + mapper: { + serializedName: "x-ms-lease-duration", + xmlName: "x-ms-lease-duration", + type: { + name: "Number" + } + } + }; + var proposedLeaseId = { + parameterPath: ["options", "proposedLeaseId"], + mapper: { + serializedName: "x-ms-proposed-lease-id", + xmlName: "x-ms-proposed-lease-id", + type: { + name: "String" + } + } + }; + var action1 = { + parameterPath: "action", + mapper: { + defaultValue: "release", + isConstant: true, + serializedName: "x-ms-lease-action", + type: { + name: "String" + } + } + }; + var leaseId1 = { + parameterPath: "leaseId", + mapper: { + serializedName: "x-ms-lease-id", + required: true, + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + } + }; + var action2 = { + parameterPath: "action", + mapper: { + defaultValue: "renew", + isConstant: true, + serializedName: "x-ms-lease-action", + type: { + name: "String" + } + } + }; + var action3 = { + parameterPath: "action", + mapper: { + defaultValue: "break", + isConstant: true, + serializedName: "x-ms-lease-action", + type: { + name: "String" + } + } + }; + var breakPeriod = { + parameterPath: ["options", "breakPeriod"], + mapper: { + serializedName: "x-ms-lease-break-period", + xmlName: "x-ms-lease-break-period", + type: { + name: "Number" + } + } + }; + var action4 = { + parameterPath: "action", + mapper: { + defaultValue: "change", + isConstant: true, + serializedName: "x-ms-lease-action", + type: { + name: "String" + } + } + }; + var proposedLeaseId1 = { + parameterPath: "proposedLeaseId", + mapper: { + serializedName: "x-ms-proposed-lease-id", + required: true, + xmlName: "x-ms-proposed-lease-id", + type: { + name: "String" + } + } + }; + var include1 = { + parameterPath: ["options", "include"], + mapper: { + serializedName: "include", + xmlName: "include", + xmlElementName: "ListBlobsIncludeItem", + type: { + name: "Sequence", + element: { + type: { + name: "Enum", + allowedValues: [ + "copy", + "deleted", + "metadata", + "snapshots", + "uncommittedblobs", + "versions", + "tags", + "immutabilitypolicy", + "legalhold", + "deletedwithversions" + ] + } + } + } + }, + collectionFormat: "CSV" + }; + var startFrom = { + parameterPath: ["options", "startFrom"], + mapper: { + serializedName: "startFrom", + xmlName: "startFrom", + type: { + name: "String" + } + } + }; + var accept2 = { + parameterPath: "accept", + mapper: { + defaultValue: "application/vnd.apache.arrow.stream,application/xml", + isConstant: true, + serializedName: "Accept", + type: { + name: "String" + } + } + }; + var endBefore = { + parameterPath: ["options", "endBefore"], + mapper: { + serializedName: "endBefore", + xmlName: "endBefore", + type: { + name: "String" + } + } + }; + var delimiter = { + parameterPath: "delimiter", + mapper: { + serializedName: "delimiter", + required: true, + xmlName: "delimiter", + type: { + name: "String" + } + } + }; + var snapshot = { + parameterPath: ["options", "snapshot"], + mapper: { + serializedName: "snapshot", + xmlName: "snapshot", + type: { + name: "String" + } + } + }; + var versionId = { + parameterPath: ["options", "versionId"], + mapper: { + serializedName: "versionid", + xmlName: "versionid", + type: { + name: "String" + } + } + }; + var range2 = { + parameterPath: ["options", "range"], + mapper: { + serializedName: "x-ms-range", + xmlName: "x-ms-range", + type: { + name: "String" + } + } + }; + var rangeGetContentMD5 = { + parameterPath: ["options", "rangeGetContentMD5"], + mapper: { + serializedName: "x-ms-range-get-content-md5", + xmlName: "x-ms-range-get-content-md5", + type: { + name: "Boolean" + } + } + }; + var rangeGetContentCRC64 = { + parameterPath: ["options", "rangeGetContentCRC64"], + mapper: { + serializedName: "x-ms-range-get-content-crc64", + xmlName: "x-ms-range-get-content-crc64", + type: { + name: "Boolean" + } + } + }; + var structuredBodyType = { + parameterPath: ["options", "structuredBodyType"], + mapper: { + serializedName: "x-ms-structured-body", + xmlName: "x-ms-structured-body", + type: { + name: "String" + } + } + }; + var encryptionKey = { + parameterPath: ["options", "cpkInfo", "encryptionKey"], + mapper: { + serializedName: "x-ms-encryption-key", + xmlName: "x-ms-encryption-key", + type: { + name: "String" + } + } + }; + var encryptionKeySha256 = { + parameterPath: ["options", "cpkInfo", "encryptionKeySha256"], + mapper: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + } + }; + var encryptionAlgorithm = { + parameterPath: ["options", "cpkInfo", "encryptionAlgorithm"], + mapper: { + serializedName: "x-ms-encryption-algorithm", + xmlName: "x-ms-encryption-algorithm", + type: { + name: "String" + } + } + }; + var ifMatch = { + parameterPath: ["options", "modifiedAccessConditions", "ifMatch"], + mapper: { + serializedName: "If-Match", + xmlName: "If-Match", + type: { + name: "String" + } + } + }; + var ifNoneMatch = { + parameterPath: ["options", "modifiedAccessConditions", "ifNoneMatch"], + mapper: { + serializedName: "If-None-Match", + xmlName: "If-None-Match", + type: { + name: "String" + } + } + }; + var ifTags = { + parameterPath: ["options", "modifiedAccessConditions", "ifTags"], + mapper: { + serializedName: "x-ms-if-tags", + xmlName: "x-ms-if-tags", + type: { + name: "String" + } + } + }; + var deleteSnapshots = { + parameterPath: ["options", "deleteSnapshots"], + mapper: { + serializedName: "x-ms-delete-snapshots", + xmlName: "x-ms-delete-snapshots", + type: { + name: "Enum", + allowedValues: ["include", "only"] + } + } + }; + var blobDeleteType = { + parameterPath: ["options", "blobDeleteType"], + mapper: { + serializedName: "deletetype", + xmlName: "deletetype", + type: { + name: "String" + } + } + }; + var accessTierIfModifiedSince = { + parameterPath: ["options", "accessTierIfModifiedSince"], + mapper: { + serializedName: "x-ms-access-tier-if-modified-since", + xmlName: "x-ms-access-tier-if-modified-since", + type: { + name: "DateTimeRfc1123" + } + } + }; + var accessTierIfUnmodifiedSince = { + parameterPath: ["options", "accessTierIfUnmodifiedSince"], + mapper: { + serializedName: "x-ms-access-tier-if-unmodified-since", + xmlName: "x-ms-access-tier-if-unmodified-since", + type: { + name: "DateTimeRfc1123" + } + } + }; + var comp11 = { + parameterPath: "comp", + mapper: { + defaultValue: "expiry", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var expiryOptions = { + parameterPath: "expiryOptions", + mapper: { + serializedName: "x-ms-expiry-option", + required: true, + xmlName: "x-ms-expiry-option", + type: { + name: "String" + } + } + }; + var expiresOn = { + parameterPath: ["options", "expiresOn"], + mapper: { + serializedName: "x-ms-expiry-time", + xmlName: "x-ms-expiry-time", + type: { + name: "String" + } + } + }; + var blobCacheControl = { + parameterPath: ["options", "blobHttpHeaders", "blobCacheControl"], + mapper: { + serializedName: "x-ms-blob-cache-control", + xmlName: "x-ms-blob-cache-control", + type: { + name: "String" + } + } + }; + var blobContentType = { + parameterPath: ["options", "blobHttpHeaders", "blobContentType"], + mapper: { + serializedName: "x-ms-blob-content-type", + xmlName: "x-ms-blob-content-type", + type: { + name: "String" + } + } + }; + var blobContentMD5 = { + parameterPath: ["options", "blobHttpHeaders", "blobContentMD5"], + mapper: { + serializedName: "x-ms-blob-content-md5", + xmlName: "x-ms-blob-content-md5", + type: { + name: "ByteArray" + } + } + }; + var blobContentEncoding = { + parameterPath: ["options", "blobHttpHeaders", "blobContentEncoding"], + mapper: { + serializedName: "x-ms-blob-content-encoding", + xmlName: "x-ms-blob-content-encoding", + type: { + name: "String" + } + } + }; + var blobContentLanguage = { + parameterPath: ["options", "blobHttpHeaders", "blobContentLanguage"], + mapper: { + serializedName: "x-ms-blob-content-language", + xmlName: "x-ms-blob-content-language", + type: { + name: "String" + } + } + }; + var blobContentDisposition = { + parameterPath: ["options", "blobHttpHeaders", "blobContentDisposition"], + mapper: { + serializedName: "x-ms-blob-content-disposition", + xmlName: "x-ms-blob-content-disposition", + type: { + name: "String" + } + } + }; + var comp12 = { + parameterPath: "comp", + mapper: { + defaultValue: "immutabilityPolicies", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var immutabilityPolicyExpiry = { + parameterPath: ["options", "immutabilityPolicyExpiry"], + mapper: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", + type: { + name: "DateTimeRfc1123" + } + } + }; + var immutabilityPolicyMode = { + parameterPath: ["options", "immutabilityPolicyMode"], + mapper: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + } + }; + var comp13 = { + parameterPath: "comp", + mapper: { + defaultValue: "legalhold", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var legalHold = { + parameterPath: "legalHold", + mapper: { + serializedName: "x-ms-legal-hold", + required: true, + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + } + }; + var encryptionScope = { + parameterPath: ["options", "encryptionScope"], + mapper: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + } + }; + var comp14 = { + parameterPath: "comp", + mapper: { + defaultValue: "snapshot", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var tier = { + parameterPath: ["options", "tier"], + mapper: { + serializedName: "x-ms-access-tier", + xmlName: "x-ms-access-tier", + type: { + name: "Enum", + allowedValues: [ + "P4", + "P6", + "P10", + "P15", + "P20", + "P30", + "P40", + "P50", + "P60", + "P70", + "P80", + "Hot", + "Cool", + "Archive", + "Cold", + "Smart" + ] + } + } + }; + var rehydratePriority = { + parameterPath: ["options", "rehydratePriority"], + mapper: { + serializedName: "x-ms-rehydrate-priority", + xmlName: "x-ms-rehydrate-priority", + type: { + name: "Enum", + allowedValues: ["High", "Standard"] + } + } + }; + var sourceIfModifiedSince = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfModifiedSince" + ], + mapper: { + serializedName: "x-ms-source-if-modified-since", + xmlName: "x-ms-source-if-modified-since", + type: { + name: "DateTimeRfc1123" + } + } + }; + var sourceIfUnmodifiedSince = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfUnmodifiedSince" + ], + mapper: { + serializedName: "x-ms-source-if-unmodified-since", + xmlName: "x-ms-source-if-unmodified-since", + type: { + name: "DateTimeRfc1123" + } + } + }; + var sourceIfMatch = { + parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfMatch"], + mapper: { + serializedName: "x-ms-source-if-match", + xmlName: "x-ms-source-if-match", + type: { + name: "String" + } + } + }; + var sourceIfNoneMatch = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfNoneMatch" + ], + mapper: { + serializedName: "x-ms-source-if-none-match", + xmlName: "x-ms-source-if-none-match", + type: { + name: "String" + } + } + }; + var sourceIfTags = { + parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfTags"], + mapper: { + serializedName: "x-ms-source-if-tags", + xmlName: "x-ms-source-if-tags", + type: { + name: "String" + } + } + }; + var copySource = { + parameterPath: "copySource", + mapper: { + serializedName: "x-ms-copy-source", + required: true, + xmlName: "x-ms-copy-source", + type: { + name: "String" + } + } + }; + var blobTagsString = { + parameterPath: ["options", "blobTagsString"], + mapper: { + serializedName: "x-ms-tags", + xmlName: "x-ms-tags", + type: { + name: "String" + } + } + }; + var sealBlob = { + parameterPath: ["options", "sealBlob"], + mapper: { + serializedName: "x-ms-seal-blob", + xmlName: "x-ms-seal-blob", + type: { + name: "Boolean" + } + } + }; + var legalHold1 = { + parameterPath: ["options", "legalHold"], + mapper: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + } + }; + var xMsRequiresSync = { + parameterPath: "xMsRequiresSync", + mapper: { + defaultValue: "true", + isConstant: true, + serializedName: "x-ms-requires-sync", + type: { + name: "String" + } + } + }; + var sourceContentMD5 = { + parameterPath: ["options", "sourceContentMD5"], + mapper: { + serializedName: "x-ms-source-content-md5", + xmlName: "x-ms-source-content-md5", + type: { + name: "ByteArray" + } + } + }; + var copySourceAuthorization = { + parameterPath: ["options", "copySourceAuthorization"], + mapper: { + serializedName: "x-ms-copy-source-authorization", + xmlName: "x-ms-copy-source-authorization", + type: { + name: "String" + } + } + }; + var copySourceTags = { + parameterPath: ["options", "copySourceTags"], + mapper: { + serializedName: "x-ms-copy-source-tag-option", + xmlName: "x-ms-copy-source-tag-option", + type: { + name: "Enum", + allowedValues: ["REPLACE", "COPY"] + } + } + }; + var fileRequestIntent = { + parameterPath: ["options", "fileRequestIntent"], + mapper: { + serializedName: "x-ms-file-request-intent", + xmlName: "x-ms-file-request-intent", + type: { + name: "String" + } + } + }; + var comp15 = { + parameterPath: "comp", + mapper: { + defaultValue: "copy", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var copyActionAbortConstant = { + parameterPath: "copyActionAbortConstant", + mapper: { + defaultValue: "abort", + isConstant: true, + serializedName: "x-ms-copy-action", + type: { + name: "String" + } + } + }; + var copyId = { + parameterPath: "copyId", + mapper: { + serializedName: "copyid", + required: true, + xmlName: "copyid", + type: { + name: "String" + } + } + }; + var comp16 = { + parameterPath: "comp", + mapper: { + defaultValue: "tier", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var tier1 = { + parameterPath: "tier", + mapper: { + serializedName: "x-ms-access-tier", + required: true, + xmlName: "x-ms-access-tier", + type: { + name: "Enum", + allowedValues: [ + "P4", + "P6", + "P10", + "P15", + "P20", + "P30", + "P40", + "P50", + "P60", + "P70", + "P80", + "Hot", + "Cool", + "Archive", + "Cold", + "Smart" + ] + } + } + }; + var queryRequest = { + parameterPath: ["options", "queryRequest"], + mapper: import_mappers.QueryRequest + }; + var comp17 = { + parameterPath: "comp", + mapper: { + defaultValue: "query", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var comp18 = { + parameterPath: "comp", + mapper: { + defaultValue: "tags", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var ifModifiedSince1 = { + parameterPath: ["options", "blobModifiedAccessConditions", "ifModifiedSince"], + mapper: { + serializedName: "x-ms-blob-if-modified-since", + xmlName: "x-ms-blob-if-modified-since", + type: { + name: "DateTimeRfc1123" + } + } + }; + var ifUnmodifiedSince1 = { + parameterPath: [ + "options", + "blobModifiedAccessConditions", + "ifUnmodifiedSince" + ], + mapper: { + serializedName: "x-ms-blob-if-unmodified-since", + xmlName: "x-ms-blob-if-unmodified-since", + type: { + name: "DateTimeRfc1123" + } + } + }; + var ifMatch1 = { + parameterPath: ["options", "blobModifiedAccessConditions", "ifMatch"], + mapper: { + serializedName: "x-ms-blob-if-match", + xmlName: "x-ms-blob-if-match", + type: { + name: "String" + } + } + }; + var ifNoneMatch1 = { + parameterPath: ["options", "blobModifiedAccessConditions", "ifNoneMatch"], + mapper: { + serializedName: "x-ms-blob-if-none-match", + xmlName: "x-ms-blob-if-none-match", + type: { + name: "String" + } + } + }; + var tags = { + parameterPath: ["options", "tags"], + mapper: import_mappers.BlobTags + }; + var transactionalContentMD5 = { + parameterPath: ["options", "transactionalContentMD5"], + mapper: { + serializedName: "Content-MD5", + xmlName: "Content-MD5", + type: { + name: "ByteArray" + } + } + }; + var transactionalContentCrc64 = { + parameterPath: ["options", "transactionalContentCrc64"], + mapper: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + } + }; + var blobType = { + parameterPath: "blobType", + mapper: { + defaultValue: "PageBlob", + isConstant: true, + serializedName: "x-ms-blob-type", + type: { + name: "String" + } + } + }; + var blobContentLength = { + parameterPath: "blobContentLength", + mapper: { + serializedName: "x-ms-blob-content-length", + required: true, + xmlName: "x-ms-blob-content-length", + type: { + name: "Number" + } + } + }; + var blobSequenceNumber = { + parameterPath: ["options", "blobSequenceNumber"], + mapper: { + defaultValue: 0, + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + } + }; + var contentType1 = { + parameterPath: ["options", "contentType"], + mapper: { + defaultValue: "application/octet-stream", + isConstant: true, + serializedName: "Content-Type", + type: { + name: "String" + } + } + }; + var body1 = { + parameterPath: "body", + mapper: { + serializedName: "body", + required: true, + xmlName: "body", + type: { + name: "Stream" + } + } + }; + var accept3 = { + parameterPath: "accept", + mapper: { + defaultValue: "application/xml", + isConstant: true, + serializedName: "Accept", + type: { + name: "String" + } + } + }; + var comp19 = { + parameterPath: "comp", + mapper: { + defaultValue: "page", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var pageWrite = { + parameterPath: "pageWrite", + mapper: { + defaultValue: "update", + isConstant: true, + serializedName: "x-ms-page-write", + type: { + name: "String" + } + } + }; + var ifSequenceNumberLessThanOrEqualTo = { + parameterPath: [ + "options", + "sequenceNumberAccessConditions", + "ifSequenceNumberLessThanOrEqualTo" + ], + mapper: { + serializedName: "x-ms-if-sequence-number-le", + xmlName: "x-ms-if-sequence-number-le", + type: { + name: "Number" + } + } + }; + var ifSequenceNumberLessThan = { + parameterPath: [ + "options", + "sequenceNumberAccessConditions", + "ifSequenceNumberLessThan" + ], + mapper: { + serializedName: "x-ms-if-sequence-number-lt", + xmlName: "x-ms-if-sequence-number-lt", + type: { + name: "Number" + } + } + }; + var ifSequenceNumberEqualTo = { + parameterPath: [ + "options", + "sequenceNumberAccessConditions", + "ifSequenceNumberEqualTo" + ], + mapper: { + serializedName: "x-ms-if-sequence-number-eq", + xmlName: "x-ms-if-sequence-number-eq", + type: { + name: "Number" + } + } + }; + var structuredContentLength = { + parameterPath: ["options", "structuredContentLength"], + mapper: { + serializedName: "x-ms-structured-content-length", + xmlName: "x-ms-structured-content-length", + type: { + name: "Number" + } + } + }; + var pageWrite1 = { + parameterPath: "pageWrite", + mapper: { + defaultValue: "clear", + isConstant: true, + serializedName: "x-ms-page-write", + type: { + name: "String" + } + } + }; + var sourceUrl = { + parameterPath: "sourceUrl", + mapper: { + serializedName: "x-ms-copy-source", + required: true, + xmlName: "x-ms-copy-source", + type: { + name: "String" + } + } + }; + var sourceRange = { + parameterPath: "sourceRange", + mapper: { + serializedName: "x-ms-source-range", + required: true, + xmlName: "x-ms-source-range", + type: { + name: "String" + } + } + }; + var sourceContentCrc64 = { + parameterPath: ["options", "sourceContentCrc64"], + mapper: { + serializedName: "x-ms-source-content-crc64", + xmlName: "x-ms-source-content-crc64", + type: { + name: "ByteArray" + } + } + }; + var range1 = { + parameterPath: "range", + mapper: { + serializedName: "x-ms-range", + required: true, + xmlName: "x-ms-range", + type: { + name: "String" + } + } + }; + var sourceEncryptionKey = { + parameterPath: ["options", "sourceCpkInfo", "sourceEncryptionKey"], + mapper: { + serializedName: "x-ms-source-encryption-key", + xmlName: "x-ms-source-encryption-key", + type: { + name: "String" + } + } + }; + var sourceEncryptionKeySha256 = { + parameterPath: ["options", "sourceCpkInfo", "sourceEncryptionKeySha256"], + mapper: { + serializedName: "x-ms-source-encryption-key-sha256", + xmlName: "x-ms-source-encryption-key-sha256", + type: { + name: "String" + } + } + }; + var sourceEncryptionAlgorithm = { + parameterPath: ["options", "sourceCpkInfo", "sourceEncryptionAlgorithm"], + mapper: { + serializedName: "x-ms-source-encryption-algorithm", + xmlName: "x-ms-source-encryption-algorithm", + type: { + name: "String" + } + } + }; + var comp20 = { + parameterPath: "comp", + mapper: { + defaultValue: "pagelist", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var prevsnapshot = { + parameterPath: ["options", "prevsnapshot"], + mapper: { + serializedName: "prevsnapshot", + xmlName: "prevsnapshot", + type: { + name: "String" + } + } + }; + var prevSnapshotUrl = { + parameterPath: ["options", "prevSnapshotUrl"], + mapper: { + serializedName: "x-ms-previous-snapshot-url", + xmlName: "x-ms-previous-snapshot-url", + type: { + name: "String" + } + } + }; + var sequenceNumberAction = { + parameterPath: "sequenceNumberAction", + mapper: { + serializedName: "x-ms-sequence-number-action", + required: true, + xmlName: "x-ms-sequence-number-action", + type: { + name: "Enum", + allowedValues: ["max", "update", "increment"] + } + } + }; + var comp21 = { + parameterPath: "comp", + mapper: { + defaultValue: "incrementalcopy", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var blobType1 = { + parameterPath: "blobType", + mapper: { + defaultValue: "AppendBlob", + isConstant: true, + serializedName: "x-ms-blob-type", + type: { + name: "String" + } + } + }; + var comp22 = { + parameterPath: "comp", + mapper: { + defaultValue: "appendblock", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var maxSize = { + parameterPath: ["options", "appendPositionAccessConditions", "maxSize"], + mapper: { + serializedName: "x-ms-blob-condition-maxsize", + xmlName: "x-ms-blob-condition-maxsize", + type: { + name: "Number" + } + } + }; + var appendPosition = { + parameterPath: [ + "options", + "appendPositionAccessConditions", + "appendPosition" + ], + mapper: { + serializedName: "x-ms-blob-condition-appendpos", + xmlName: "x-ms-blob-condition-appendpos", + type: { + name: "Number" + } + } + }; + var sourceRange1 = { + parameterPath: ["options", "sourceRange"], + mapper: { + serializedName: "x-ms-source-range", + xmlName: "x-ms-source-range", + type: { + name: "String" + } + } + }; + var comp23 = { + parameterPath: "comp", + mapper: { + defaultValue: "seal", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var blobType2 = { + parameterPath: "blobType", + mapper: { + defaultValue: "BlockBlob", + isConstant: true, + serializedName: "x-ms-blob-type", + type: { + name: "String" + } + } + }; + var copySourceBlobProperties = { + parameterPath: ["options", "copySourceBlobProperties"], + mapper: { + serializedName: "x-ms-copy-source-blob-properties", + xmlName: "x-ms-copy-source-blob-properties", + type: { + name: "Boolean" + } + } + }; + var comp24 = { + parameterPath: "comp", + mapper: { + defaultValue: "block", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var blockId = { + parameterPath: "blockId", + mapper: { + serializedName: "blockid", + required: true, + xmlName: "blockid", + type: { + name: "String" + } + } + }; + var blocks = { + parameterPath: "blocks", + mapper: import_mappers.BlockLookupList + }; + var comp25 = { + parameterPath: "comp", + mapper: { + defaultValue: "blocklist", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var listType = { + parameterPath: "listType", + mapper: { + defaultValue: "committed", + serializedName: "blocklisttype", + required: true, + xmlName: "blocklisttype", + type: { + name: "Enum", + allowedValues: ["committed", "uncommitted", "all"] + } + } + }; + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/service.js +var require_service = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/service.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var service_exports = {}; + __export2(service_exports, { + ServiceImpl: () => ServiceImpl + }); + module2.exports = __toCommonJS2(service_exports); + var coreClient = __toESM2(require_commonjs8()); + var Mappers = __toESM2(require_mappers()); + var Parameters = __toESM2(require_parameters()); + var ServiceImpl = class { + client; + /** + * Initialize a new instance of the class Service class. + * @param client Reference to the service client + */ + constructor(client) { + this.client = client; + } + /** + * Sets properties for a storage account's Blob service endpoint, including properties for Storage + * Analytics and CORS (Cross-Origin Resource Sharing) rules + * @param blobServiceProperties The StorageService properties. + * @param options The options parameters. + */ + setProperties(blobServiceProperties, options) { + return this.client.sendOperationRequest( + { blobServiceProperties, options }, + setPropertiesOperationSpec + ); + } + /** + * gets the properties of a storage account's Blob service, including properties for Storage Analytics + * and CORS (Cross-Origin Resource Sharing) rules. + * @param options The options parameters. + */ + getProperties(options) { + return this.client.sendOperationRequest( + { options }, + getPropertiesOperationSpec + ); + } + /** + * Retrieves statistics related to replication for the Blob service. It is only available on the + * secondary location endpoint when read-access geo-redundant replication is enabled for the storage + * account. + * @param options The options parameters. + */ + getStatistics(options) { + return this.client.sendOperationRequest( + { options }, + getStatisticsOperationSpec + ); + } + /** + * The List Containers Segment operation returns a list of the containers under the specified account + * @param options The options parameters. + */ + listContainersSegment(options) { + return this.client.sendOperationRequest( + { options }, + listContainersSegmentOperationSpec + ); + } + /** + * Retrieves a user delegation key for the Blob service. This is only a valid operation when using + * bearer token authentication. + * @param keyInfo Key information + * @param options The options parameters. + */ + getUserDelegationKey(keyInfo, options) { + return this.client.sendOperationRequest( + { keyInfo, options }, + getUserDelegationKeyOperationSpec + ); + } + /** + * Returns the sku name and account kind + * @param options The options parameters. + */ + getAccountInfo(options) { + return this.client.sendOperationRequest( + { options }, + getAccountInfoOperationSpec + ); + } + /** + * The Batch operation allows multiple API calls to be embedded into a single HTTP request. + * @param contentLength The length of the request. + * @param multipartContentType Required. The value of this header must be multipart/mixed with a batch + * boundary. Example header value: multipart/mixed; boundary=batch_ + * @param body Initial data + * @param options The options parameters. + */ + submitBatch(contentLength, multipartContentType, body, options) { + return this.client.sendOperationRequest( + { contentLength, multipartContentType, body, options }, + submitBatchOperationSpec + ); + } + /** + * The Filter Blobs operation enables callers to list blobs across all containers whose tags match a + * given search expression. Filter blobs searches across all containers within a storage account but + * can be scoped within the expression to a single container. + * @param options The options parameters. + */ + filterBlobs(options) { + return this.client.sendOperationRequest( + { options }, + filterBlobsOperationSpec + ); + } + }; + var xmlSerializer = coreClient.createSerializer( + Mappers, + /* isXml */ + true + ); + var setPropertiesOperationSpec = { + path: "/", + httpMethod: "PUT", + responses: { + 202: { + headersMapper: Mappers.ServiceSetPropertiesHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ServiceSetPropertiesExceptionHeaders + } + }, + requestBody: Parameters.blobServiceProperties, + queryParameters: [ + Parameters.restype, + Parameters.comp, + Parameters.timeoutInSeconds + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.contentType, + Parameters.accept, + Parameters.version, + Parameters.requestId + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer + }; + var getPropertiesOperationSpec = { + path: "/", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.BlobServiceProperties, + headersMapper: Mappers.ServiceGetPropertiesHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ServiceGetPropertiesExceptionHeaders + } + }, + queryParameters: [ + Parameters.restype, + Parameters.comp, + Parameters.timeoutInSeconds + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1 + ], + isXML: true, + serializer: xmlSerializer + }; + var getStatisticsOperationSpec = { + path: "/", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.BlobServiceStatistics, + headersMapper: Mappers.ServiceGetStatisticsHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ServiceGetStatisticsExceptionHeaders + } + }, + queryParameters: [ + Parameters.restype, + Parameters.timeoutInSeconds, + Parameters.comp1 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1 + ], + isXML: true, + serializer: xmlSerializer + }; + var listContainersSegmentOperationSpec = { + path: "/", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.ListContainersSegmentResponse, + headersMapper: Mappers.ServiceListContainersSegmentHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ServiceListContainersSegmentExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.comp2, + Parameters.prefix, + Parameters.marker, + Parameters.maxPageSize, + Parameters.include + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1 + ], + isXML: true, + serializer: xmlSerializer + }; + var getUserDelegationKeyOperationSpec = { + path: "/", + httpMethod: "POST", + responses: { + 200: { + bodyMapper: Mappers.UserDelegationKey, + headersMapper: Mappers.ServiceGetUserDelegationKeyHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ServiceGetUserDelegationKeyExceptionHeaders + } + }, + requestBody: Parameters.keyInfo, + queryParameters: [ + Parameters.restype, + Parameters.timeoutInSeconds, + Parameters.comp3 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.contentType, + Parameters.accept, + Parameters.version, + Parameters.requestId + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer + }; + var getAccountInfoOperationSpec = { + path: "/", + httpMethod: "GET", + responses: { + 200: { + headersMapper: Mappers.ServiceGetAccountInfoHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ServiceGetAccountInfoExceptionHeaders + } + }, + queryParameters: [ + Parameters.comp, + Parameters.timeoutInSeconds, + Parameters.restype1 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1 + ], + isXML: true, + serializer: xmlSerializer + }; + var submitBatchOperationSpec = { + path: "/", + httpMethod: "POST", + responses: { + 202: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: Mappers.ServiceSubmitBatchHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ServiceSubmitBatchExceptionHeaders + } + }, + requestBody: Parameters.body, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp4], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.accept, + Parameters.version, + Parameters.requestId, + Parameters.contentLength, + Parameters.multipartContentType + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer + }; + var filterBlobsOperationSpec = { + path: "/", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.FilterBlobSegment, + headersMapper: Mappers.ServiceFilterBlobsHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ServiceFilterBlobsExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.marker, + Parameters.maxPageSize, + Parameters.comp5, + Parameters.where + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1 + ], + isXML: true, + serializer: xmlSerializer + }; + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/container.js +var require_container = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/container.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var container_exports = {}; + __export2(container_exports, { + ContainerImpl: () => ContainerImpl + }); + module2.exports = __toCommonJS2(container_exports); + var coreClient = __toESM2(require_commonjs8()); + var Mappers = __toESM2(require_mappers()); + var Parameters = __toESM2(require_parameters()); + var ContainerImpl = class { + client; + /** + * Initialize a new instance of the class Container class. + * @param client Reference to the service client + */ + constructor(client) { + this.client = client; + } + /** + * creates a new container under the specified account. If the container with the same name already + * exists, the operation fails + * @param options The options parameters. + */ + create(options) { + return this.client.sendOperationRequest({ options }, createOperationSpec); + } + /** + * returns all user-defined metadata and system properties for the specified container. The data + * returned does not include the container's list of blobs + * @param options The options parameters. + */ + getProperties(options) { + return this.client.sendOperationRequest( + { options }, + getPropertiesOperationSpec + ); + } + /** + * operation marks the specified container for deletion. The container and any blobs contained within + * it are later deleted during garbage collection + * @param options The options parameters. + */ + delete(options) { + return this.client.sendOperationRequest({ options }, deleteOperationSpec); + } + /** + * operation sets one or more user-defined name-value pairs for the specified container. + * @param options The options parameters. + */ + setMetadata(options) { + return this.client.sendOperationRequest( + { options }, + setMetadataOperationSpec + ); + } + /** + * gets the permissions for the specified container. The permissions indicate whether container data + * may be accessed publicly. + * @param options The options parameters. + */ + getAccessPolicy(options) { + return this.client.sendOperationRequest( + { options }, + getAccessPolicyOperationSpec + ); + } + /** + * sets the permissions for the specified container. The permissions indicate whether blobs in a + * container may be accessed publicly. + * @param options The options parameters. + */ + setAccessPolicy(options) { + return this.client.sendOperationRequest( + { options }, + setAccessPolicyOperationSpec + ); + } + /** + * Restores a previously-deleted container. + * @param options The options parameters. + */ + restore(options) { + return this.client.sendOperationRequest({ options }, restoreOperationSpec); + } + /** + * Renames an existing container. + * @param sourceContainerName Required. Specifies the name of the container to rename. + * @param options The options parameters. + */ + rename(sourceContainerName, options) { + return this.client.sendOperationRequest( + { sourceContainerName, options }, + renameOperationSpec + ); + } + /** + * The Batch operation allows multiple API calls to be embedded into a single HTTP request. + * @param contentLength The length of the request. + * @param multipartContentType Required. The value of this header must be multipart/mixed with a batch + * boundary. Example header value: multipart/mixed; boundary=batch_ + * @param body Initial data + * @param options The options parameters. + */ + submitBatch(contentLength, multipartContentType, body, options) { + return this.client.sendOperationRequest( + { contentLength, multipartContentType, body, options }, + submitBatchOperationSpec + ); + } + /** + * The Filter Blobs operation enables callers to list blobs in a container whose tags match a given + * search expression. Filter blobs searches within the given container. + * @param options The options parameters. + */ + filterBlobs(options) { + return this.client.sendOperationRequest( + { options }, + filterBlobsOperationSpec + ); + } + /** + * [Update] establishes and manages a lock on a container for delete operations. The lock duration can + * be 15 to 60 seconds, or can be infinite + * @param options The options parameters. + */ + acquireLease(options) { + return this.client.sendOperationRequest( + { options }, + acquireLeaseOperationSpec + ); + } + /** + * [Update] establishes and manages a lock on a container for delete operations. The lock duration can + * be 15 to 60 seconds, or can be infinite + * @param leaseId Specifies the current lease ID on the resource. + * @param options The options parameters. + */ + releaseLease(leaseId, options) { + return this.client.sendOperationRequest( + { leaseId, options }, + releaseLeaseOperationSpec + ); + } + /** + * [Update] establishes and manages a lock on a container for delete operations. The lock duration can + * be 15 to 60 seconds, or can be infinite + * @param leaseId Specifies the current lease ID on the resource. + * @param options The options parameters. + */ + renewLease(leaseId, options) { + return this.client.sendOperationRequest( + { leaseId, options }, + renewLeaseOperationSpec + ); + } + /** + * [Update] establishes and manages a lock on a container for delete operations. The lock duration can + * be 15 to 60 seconds, or can be infinite + * @param options The options parameters. + */ + breakLease(options) { + return this.client.sendOperationRequest( + { options }, + breakLeaseOperationSpec + ); + } + /** + * [Update] establishes and manages a lock on a container for delete operations. The lock duration can + * be 15 to 60 seconds, or can be infinite + * @param leaseId Specifies the current lease ID on the resource. + * @param proposedLeaseId Proposed lease ID, in a GUID string format. The Blob service returns 400 + * (Invalid request) if the proposed lease ID is not in the correct format. See Guid Constructor + * (String) for a list of valid GUID string formats. + * @param options The options parameters. + */ + changeLease(leaseId, proposedLeaseId, options) { + return this.client.sendOperationRequest( + { leaseId, proposedLeaseId, options }, + changeLeaseOperationSpec + ); + } + /** + * [Update] The List Blobs operation returns a list of the blobs under the specified container + * @param options The options parameters. + */ + listBlobFlatSegment(options) { + return this.client.sendOperationRequest( + { options }, + listBlobFlatSegmentOperationSpec + ); + } + /** + * The List Blobs operation returns a list of the blobs under the specified container. This operation + * is for Apache Arrow use case so response is returned as raw to be deserialized by the client. + * @param options The options parameters. + */ + listBlobFlatSegmentApacheArrow(options) { + return this.client.sendOperationRequest( + { options }, + listBlobFlatSegmentApacheArrowOperationSpec + ); + } + /** + * [Update] The List Blobs operation returns a list of the blobs under the specified container + * @param delimiter When the request includes this parameter, the operation returns a BlobPrefix + * element in the response body that acts as a placeholder for all blobs whose names begin with the + * same substring up to the appearance of the delimiter character. The delimiter may be a single + * character or a string. + * @param options The options parameters. + */ + listBlobHierarchySegment(delimiter, options) { + return this.client.sendOperationRequest( + { delimiter, options }, + listBlobHierarchySegmentOperationSpec + ); + } + /** + * [Update] The List Blobs operation returns a list of the blobs under the specified container. This + * operation is for Apache Arrow use case so response is returned as raw to be deserialized by the + * client. + * @param delimiter When the request includes this parameter, the operation returns a BlobPrefix + * element in the response body that acts as a placeholder for all blobs whose names begin with the + * same substring up to the appearance of the delimiter character. The delimiter may be a single + * character or a string. + * @param options The options parameters. + */ + listBlobHierarchySegmentApacheArrow(delimiter, options) { + return this.client.sendOperationRequest( + { delimiter, options }, + listBlobHierarchySegmentApacheArrowOperationSpec + ); + } + /** + * Returns the sku name and account kind + * @param options The options parameters. + */ + getAccountInfo(options) { + return this.client.sendOperationRequest( + { options }, + getAccountInfoOperationSpec + ); + } + }; + var xmlSerializer = coreClient.createSerializer( + Mappers, + /* isXml */ + true + ); + var createOperationSpec = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.ContainerCreateHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerCreateExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.restype2], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.metadata, + Parameters.access, + Parameters.defaultEncryptionScope, + Parameters.preventEncryptionScopeOverride + ], + isXML: true, + serializer: xmlSerializer + }; + var getPropertiesOperationSpec = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + headersMapper: Mappers.ContainerGetPropertiesHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerGetPropertiesExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.restype2], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId + ], + isXML: true, + serializer: xmlSerializer + }; + var deleteOperationSpec = { + path: "/{containerName}", + httpMethod: "DELETE", + responses: { + 202: { + headersMapper: Mappers.ContainerDeleteHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerDeleteExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.restype2], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince + ], + isXML: true, + serializer: xmlSerializer + }; + var setMetadataOperationSpec = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.ContainerSetMetadataHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerSetMetadataExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.restype2, + Parameters.comp6 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.metadata, + Parameters.leaseId, + Parameters.ifModifiedSince + ], + isXML: true, + serializer: xmlSerializer + }; + var getAccessPolicyOperationSpec = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: { + type: { + name: "Sequence", + element: { + type: { name: "Composite", className: "SignedIdentifier" } + } + }, + serializedName: "SignedIdentifiers", + xmlName: "SignedIdentifiers", + xmlIsWrapped: true, + xmlElementName: "SignedIdentifier" + }, + headersMapper: Mappers.ContainerGetAccessPolicyHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerGetAccessPolicyExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.restype2, + Parameters.comp7 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId + ], + isXML: true, + serializer: xmlSerializer + }; + var setAccessPolicyOperationSpec = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.ContainerSetAccessPolicyHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerSetAccessPolicyExceptionHeaders + } + }, + requestBody: Parameters.containerAcl, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.restype2, + Parameters.comp7 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.contentType, + Parameters.accept, + Parameters.version, + Parameters.requestId, + Parameters.access, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer + }; + var restoreOperationSpec = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.ContainerRestoreHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerRestoreExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.restype2, + Parameters.comp8 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.deletedContainerName, + Parameters.deletedContainerVersion + ], + isXML: true, + serializer: xmlSerializer + }; + var renameOperationSpec = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.ContainerRenameHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerRenameExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.restype2, + Parameters.comp9 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.sourceContainerName, + Parameters.sourceLeaseId + ], + isXML: true, + serializer: xmlSerializer + }; + var submitBatchOperationSpec = { + path: "/{containerName}", + httpMethod: "POST", + responses: { + 202: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: Mappers.ContainerSubmitBatchHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerSubmitBatchExceptionHeaders + } + }, + requestBody: Parameters.body, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.comp4, + Parameters.restype2 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.accept, + Parameters.version, + Parameters.requestId, + Parameters.contentLength, + Parameters.multipartContentType + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer + }; + var filterBlobsOperationSpec = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.FilterBlobSegment, + headersMapper: Mappers.ContainerFilterBlobsHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerFilterBlobsExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.marker, + Parameters.maxPageSize, + Parameters.comp5, + Parameters.where, + Parameters.restype2 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1 + ], + isXML: true, + serializer: xmlSerializer + }; + var acquireLeaseOperationSpec = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.ContainerAcquireLeaseHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerAcquireLeaseExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.restype2, + Parameters.comp10 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.action, + Parameters.duration, + Parameters.proposedLeaseId + ], + isXML: true, + serializer: xmlSerializer + }; + var releaseLeaseOperationSpec = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.ContainerReleaseLeaseHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerReleaseLeaseExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.restype2, + Parameters.comp10 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.action1, + Parameters.leaseId1 + ], + isXML: true, + serializer: xmlSerializer + }; + var renewLeaseOperationSpec = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.ContainerRenewLeaseHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerRenewLeaseExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.restype2, + Parameters.comp10 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.leaseId1, + Parameters.action2 + ], + isXML: true, + serializer: xmlSerializer + }; + var breakLeaseOperationSpec = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 202: { + headersMapper: Mappers.ContainerBreakLeaseHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerBreakLeaseExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.restype2, + Parameters.comp10 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.action3, + Parameters.breakPeriod + ], + isXML: true, + serializer: xmlSerializer + }; + var changeLeaseOperationSpec = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.ContainerChangeLeaseHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerChangeLeaseExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.restype2, + Parameters.comp10 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.leaseId1, + Parameters.action4, + Parameters.proposedLeaseId1 + ], + isXML: true, + serializer: xmlSerializer + }; + var listBlobFlatSegmentOperationSpec = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.ListBlobsFlatSegmentResponse, + headersMapper: Mappers.ContainerListBlobFlatSegmentHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerListBlobFlatSegmentExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.comp2, + Parameters.prefix, + Parameters.marker, + Parameters.maxPageSize, + Parameters.restype2, + Parameters.include1, + Parameters.startFrom + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1 + ], + isXML: true, + serializer: xmlSerializer + }; + var listBlobFlatSegmentApacheArrowOperationSpec = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: Mappers.ContainerListBlobFlatSegmentApacheArrowHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerListBlobFlatSegmentApacheArrowExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.comp2, + Parameters.prefix, + Parameters.marker, + Parameters.maxPageSize, + Parameters.restype2, + Parameters.include1, + Parameters.startFrom, + Parameters.endBefore + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept2 + ], + isXML: true, + serializer: xmlSerializer + }; + var listBlobHierarchySegmentOperationSpec = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.ListBlobsHierarchySegmentResponse, + headersMapper: Mappers.ContainerListBlobHierarchySegmentHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerListBlobHierarchySegmentExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.comp2, + Parameters.prefix, + Parameters.marker, + Parameters.maxPageSize, + Parameters.restype2, + Parameters.include1, + Parameters.startFrom, + Parameters.delimiter + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1 + ], + isXML: true, + serializer: xmlSerializer + }; + var listBlobHierarchySegmentApacheArrowOperationSpec = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: Mappers.ContainerListBlobHierarchySegmentApacheArrowHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerListBlobHierarchySegmentApacheArrowExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.comp2, + Parameters.prefix, + Parameters.marker, + Parameters.maxPageSize, + Parameters.restype2, + Parameters.include1, + Parameters.startFrom, + Parameters.endBefore, + Parameters.delimiter + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept2 + ], + isXML: true, + serializer: xmlSerializer + }; + var getAccountInfoOperationSpec = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + headersMapper: Mappers.ContainerGetAccountInfoHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.ContainerGetAccountInfoExceptionHeaders + } + }, + queryParameters: [ + Parameters.comp, + Parameters.timeoutInSeconds, + Parameters.restype1 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1 + ], + isXML: true, + serializer: xmlSerializer + }; + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/blob.js +var require_blob = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/blob.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var blob_exports = {}; + __export2(blob_exports, { + BlobImpl: () => BlobImpl + }); + module2.exports = __toCommonJS2(blob_exports); + var coreClient = __toESM2(require_commonjs8()); + var Mappers = __toESM2(require_mappers()); + var Parameters = __toESM2(require_parameters()); + var BlobImpl = class { + client; + /** + * Initialize a new instance of the class Blob class. + * @param client Reference to the service client + */ + constructor(client) { + this.client = client; + } + /** + * The Download operation reads or downloads a blob from the system, including its metadata and + * properties. You can also call Download to read a snapshot. + * @param options The options parameters. + */ + download(options) { + return this.client.sendOperationRequest({ options }, downloadOperationSpec); + } + /** + * The Get Properties operation returns all user-defined metadata, standard HTTP properties, and system + * properties for the blob. It does not return the content of the blob. + * @param options The options parameters. + */ + getProperties(options) { + return this.client.sendOperationRequest( + { options }, + getPropertiesOperationSpec + ); + } + /** + * If the storage account's soft delete feature is disabled then, when a blob is deleted, it is + * permanently removed from the storage account. If the storage account's soft delete feature is + * enabled, then, when a blob is deleted, it is marked for deletion and becomes inaccessible + * immediately. However, the blob service retains the blob or snapshot for the number of days specified + * by the DeleteRetentionPolicy section of [Storage service properties] + * (Set-Blob-Service-Properties.md). After the specified number of days has passed, the blob's data is + * permanently removed from the storage account. Note that you continue to be charged for the + * soft-deleted blob's storage until it is permanently removed. Use the List Blobs API and specify the + * "include=deleted" query parameter to discover which blobs and snapshots have been soft deleted. You + * can then use the Undelete Blob API to restore a soft-deleted blob. All other operations on a + * soft-deleted blob or snapshot causes the service to return an HTTP status code of 404 + * (ResourceNotFound). + * @param options The options parameters. + */ + delete(options) { + return this.client.sendOperationRequest({ options }, deleteOperationSpec); + } + /** + * Undelete a blob that was previously soft deleted + * @param options The options parameters. + */ + undelete(options) { + return this.client.sendOperationRequest({ options }, undeleteOperationSpec); + } + /** + * Sets the time a blob will expire and be deleted. + * @param expiryOptions Required. Indicates mode of the expiry time + * @param options The options parameters. + */ + setExpiry(expiryOptions, options) { + return this.client.sendOperationRequest( + { expiryOptions, options }, + setExpiryOperationSpec + ); + } + /** + * The Set HTTP Headers operation sets system properties on the blob + * @param options The options parameters. + */ + setHttpHeaders(options) { + return this.client.sendOperationRequest( + { options }, + setHttpHeadersOperationSpec + ); + } + /** + * The Set Immutability Policy operation sets the immutability policy on the blob + * @param options The options parameters. + */ + setImmutabilityPolicy(options) { + return this.client.sendOperationRequest( + { options }, + setImmutabilityPolicyOperationSpec + ); + } + /** + * The Delete Immutability Policy operation deletes the immutability policy on the blob + * @param options The options parameters. + */ + deleteImmutabilityPolicy(options) { + return this.client.sendOperationRequest( + { options }, + deleteImmutabilityPolicyOperationSpec + ); + } + /** + * The Set Legal Hold operation sets a legal hold on the blob. + * @param legalHold Specified if a legal hold should be set on the blob. + * @param options The options parameters. + */ + setLegalHold(legalHold, options) { + return this.client.sendOperationRequest( + { legalHold, options }, + setLegalHoldOperationSpec + ); + } + /** + * The Set Blob Metadata operation sets user-defined metadata for the specified blob as one or more + * name-value pairs + * @param options The options parameters. + */ + setMetadata(options) { + return this.client.sendOperationRequest( + { options }, + setMetadataOperationSpec + ); + } + /** + * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete + * operations + * @param options The options parameters. + */ + acquireLease(options) { + return this.client.sendOperationRequest( + { options }, + acquireLeaseOperationSpec + ); + } + /** + * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete + * operations + * @param leaseId Specifies the current lease ID on the resource. + * @param options The options parameters. + */ + releaseLease(leaseId, options) { + return this.client.sendOperationRequest( + { leaseId, options }, + releaseLeaseOperationSpec + ); + } + /** + * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete + * operations + * @param leaseId Specifies the current lease ID on the resource. + * @param options The options parameters. + */ + renewLease(leaseId, options) { + return this.client.sendOperationRequest( + { leaseId, options }, + renewLeaseOperationSpec + ); + } + /** + * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete + * operations + * @param leaseId Specifies the current lease ID on the resource. + * @param proposedLeaseId Proposed lease ID, in a GUID string format. The Blob service returns 400 + * (Invalid request) if the proposed lease ID is not in the correct format. See Guid Constructor + * (String) for a list of valid GUID string formats. + * @param options The options parameters. + */ + changeLease(leaseId, proposedLeaseId, options) { + return this.client.sendOperationRequest( + { leaseId, proposedLeaseId, options }, + changeLeaseOperationSpec + ); + } + /** + * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete + * operations + * @param options The options parameters. + */ + breakLease(options) { + return this.client.sendOperationRequest( + { options }, + breakLeaseOperationSpec + ); + } + /** + * The Create Snapshot operation creates a read-only snapshot of a blob + * @param options The options parameters. + */ + createSnapshot(options) { + return this.client.sendOperationRequest( + { options }, + createSnapshotOperationSpec + ); + } + /** + * The Start Copy From URL operation copies a blob or an internet resource to a new blob. + * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to + * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would + * appear in a request URI. The source blob must either be public or must be authenticated via a shared + * access signature. + * @param options The options parameters. + */ + startCopyFromURL(copySource, options) { + return this.client.sendOperationRequest( + { copySource, options }, + startCopyFromURLOperationSpec + ); + } + /** + * The Copy From URL operation copies a blob or an internet resource to a new blob. It will not return + * a response until the copy is complete. + * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to + * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would + * appear in a request URI. The source blob must either be public or must be authenticated via a shared + * access signature. + * @param options The options parameters. + */ + copyFromURL(copySource, options) { + return this.client.sendOperationRequest( + { copySource, options }, + copyFromURLOperationSpec + ); + } + /** + * The Abort Copy From URL operation aborts a pending Copy From URL operation, and leaves a destination + * blob with zero length and full metadata. + * @param copyId The copy identifier provided in the x-ms-copy-id header of the original Copy Blob + * operation. + * @param options The options parameters. + */ + abortCopyFromURL(copyId, options) { + return this.client.sendOperationRequest( + { copyId, options }, + abortCopyFromURLOperationSpec + ); + } + /** + * The Set Tier operation sets the tier on a blob. The operation is allowed on a page blob in a premium + * storage account and on a block blob in a blob storage account (locally redundant storage only). A + * premium page blob's tier determines the allowed size, IOPS, and bandwidth of the blob. A block + * blob's tier determines Hot/Cool/Archive storage type. This operation does not update the blob's + * ETag. + * @param tier Indicates the tier to be set on the blob. + * @param options The options parameters. + */ + setTier(tier, options) { + return this.client.sendOperationRequest( + { tier, options }, + setTierOperationSpec + ); + } + /** + * Returns the sku name and account kind + * @param options The options parameters. + */ + getAccountInfo(options) { + return this.client.sendOperationRequest( + { options }, + getAccountInfoOperationSpec + ); + } + /** + * The Query operation enables users to select/project on blob data by providing simple query + * expressions. + * @param options The options parameters. + */ + query(options) { + return this.client.sendOperationRequest({ options }, queryOperationSpec); + } + /** + * The Get Tags operation enables users to get the tags associated with a blob. + * @param options The options parameters. + */ + getTags(options) { + return this.client.sendOperationRequest({ options }, getTagsOperationSpec); + } + /** + * The Set Tags operation enables users to set tags on a blob. + * @param options The options parameters. + */ + setTags(options) { + return this.client.sendOperationRequest({ options }, setTagsOperationSpec); + } + }; + var xmlSerializer = coreClient.createSerializer( + Mappers, + /* isXml */ + true + ); + var downloadOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: Mappers.BlobDownloadHeaders + }, + 206: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: Mappers.BlobDownloadHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobDownloadExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.snapshot, + Parameters.versionId + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.range, + Parameters.rangeGetContentMD5, + Parameters.rangeGetContentCRC64, + Parameters.structuredBodyType, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags + ], + isXML: true, + serializer: xmlSerializer + }; + var getPropertiesOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "HEAD", + responses: { + 200: { + headersMapper: Mappers.BlobGetPropertiesHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobGetPropertiesExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.snapshot, + Parameters.versionId + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags + ], + isXML: true, + serializer: xmlSerializer + }; + var deleteOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "DELETE", + responses: { + 202: { + headersMapper: Mappers.BlobDeleteHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobDeleteExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.snapshot, + Parameters.versionId, + Parameters.blobDeleteType + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.deleteSnapshots, + Parameters.accessTierIfModifiedSince, + Parameters.accessTierIfUnmodifiedSince + ], + isXML: true, + serializer: xmlSerializer + }; + var undeleteOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.BlobUndeleteHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobUndeleteExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp8], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1 + ], + isXML: true, + serializer: xmlSerializer + }; + var setExpiryOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.BlobSetExpiryHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobSetExpiryExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp11], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.expiryOptions, + Parameters.expiresOn + ], + isXML: true, + serializer: xmlSerializer + }; + var setHttpHeadersOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.BlobSetHttpHeadersHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobSetHttpHeadersExceptionHeaders + } + }, + queryParameters: [Parameters.comp, Parameters.timeoutInSeconds], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.blobCacheControl, + Parameters.blobContentType, + Parameters.blobContentMD5, + Parameters.blobContentEncoding, + Parameters.blobContentLanguage, + Parameters.blobContentDisposition + ], + isXML: true, + serializer: xmlSerializer + }; + var setImmutabilityPolicyOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.BlobSetImmutabilityPolicyHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobSetImmutabilityPolicyExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.snapshot, + Parameters.versionId, + Parameters.comp12 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.ifUnmodifiedSince, + Parameters.immutabilityPolicyExpiry, + Parameters.immutabilityPolicyMode + ], + isXML: true, + serializer: xmlSerializer + }; + var deleteImmutabilityPolicyOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "DELETE", + responses: { + 200: { + headersMapper: Mappers.BlobDeleteImmutabilityPolicyHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobDeleteImmutabilityPolicyExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.snapshot, + Parameters.versionId, + Parameters.comp12 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1 + ], + isXML: true, + serializer: xmlSerializer + }; + var setLegalHoldOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.BlobSetLegalHoldHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobSetLegalHoldExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.snapshot, + Parameters.versionId, + Parameters.comp13 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.legalHold + ], + isXML: true, + serializer: xmlSerializer + }; + var setMetadataOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.BlobSetMetadataHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobSetMetadataExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp6], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.metadata, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.encryptionScope + ], + isXML: true, + serializer: xmlSerializer + }; + var acquireLeaseOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.BlobAcquireLeaseHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobAcquireLeaseExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp10], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.action, + Parameters.duration, + Parameters.proposedLeaseId, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags + ], + isXML: true, + serializer: xmlSerializer + }; + var releaseLeaseOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.BlobReleaseLeaseHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobReleaseLeaseExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp10], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.action1, + Parameters.leaseId1, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags + ], + isXML: true, + serializer: xmlSerializer + }; + var renewLeaseOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.BlobRenewLeaseHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobRenewLeaseExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp10], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.leaseId1, + Parameters.action2, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags + ], + isXML: true, + serializer: xmlSerializer + }; + var changeLeaseOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.BlobChangeLeaseHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobChangeLeaseExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp10], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.leaseId1, + Parameters.action4, + Parameters.proposedLeaseId1, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags + ], + isXML: true, + serializer: xmlSerializer + }; + var breakLeaseOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 202: { + headersMapper: Mappers.BlobBreakLeaseHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobBreakLeaseExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp10], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.action3, + Parameters.breakPeriod, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags + ], + isXML: true, + serializer: xmlSerializer + }; + var createSnapshotOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.BlobCreateSnapshotHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobCreateSnapshotExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp14], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.metadata, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.encryptionScope + ], + isXML: true, + serializer: xmlSerializer + }; + var startCopyFromURLOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 202: { + headersMapper: Mappers.BlobStartCopyFromURLHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobStartCopyFromURLExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.metadata, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.immutabilityPolicyExpiry, + Parameters.immutabilityPolicyMode, + Parameters.tier, + Parameters.rehydratePriority, + Parameters.sourceIfModifiedSince, + Parameters.sourceIfUnmodifiedSince, + Parameters.sourceIfMatch, + Parameters.sourceIfNoneMatch, + Parameters.sourceIfTags, + Parameters.copySource, + Parameters.blobTagsString, + Parameters.sealBlob, + Parameters.legalHold1 + ], + isXML: true, + serializer: xmlSerializer + }; + var copyFromURLOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 202: { + headersMapper: Mappers.BlobCopyFromURLHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobCopyFromURLExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.metadata, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.immutabilityPolicyExpiry, + Parameters.immutabilityPolicyMode, + Parameters.encryptionScope, + Parameters.tier, + Parameters.sourceIfModifiedSince, + Parameters.sourceIfUnmodifiedSince, + Parameters.sourceIfMatch, + Parameters.sourceIfNoneMatch, + Parameters.copySource, + Parameters.blobTagsString, + Parameters.legalHold1, + Parameters.xMsRequiresSync, + Parameters.sourceContentMD5, + Parameters.copySourceAuthorization, + Parameters.copySourceTags, + Parameters.fileRequestIntent + ], + isXML: true, + serializer: xmlSerializer + }; + var abortCopyFromURLOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 204: { + headersMapper: Mappers.BlobAbortCopyFromURLHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobAbortCopyFromURLExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.comp15, + Parameters.copyId + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.copyActionAbortConstant + ], + isXML: true, + serializer: xmlSerializer + }; + var setTierOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.BlobSetTierHeaders + }, + 202: { + headersMapper: Mappers.BlobSetTierHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobSetTierExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.snapshot, + Parameters.versionId, + Parameters.comp16 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.ifTags, + Parameters.rehydratePriority, + Parameters.tier1 + ], + isXML: true, + serializer: xmlSerializer + }; + var getAccountInfoOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "GET", + responses: { + 200: { + headersMapper: Mappers.BlobGetAccountInfoHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobGetAccountInfoExceptionHeaders + } + }, + queryParameters: [ + Parameters.comp, + Parameters.timeoutInSeconds, + Parameters.restype1 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1 + ], + isXML: true, + serializer: xmlSerializer + }; + var queryOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "POST", + responses: { + 200: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: Mappers.BlobQueryHeaders + }, + 206: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: Mappers.BlobQueryHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobQueryExceptionHeaders + } + }, + requestBody: Parameters.queryRequest, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.snapshot, + Parameters.comp17 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.contentType, + Parameters.accept, + Parameters.version, + Parameters.requestId, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer + }; + var getTagsOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.BlobTags, + headersMapper: Mappers.BlobGetTagsHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobGetTagsExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.snapshot, + Parameters.versionId, + Parameters.comp18 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.ifTags, + Parameters.ifModifiedSince1, + Parameters.ifUnmodifiedSince1, + Parameters.ifMatch1, + Parameters.ifNoneMatch1 + ], + isXML: true, + serializer: xmlSerializer + }; + var setTagsOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 204: { + headersMapper: Mappers.BlobSetTagsHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlobSetTagsExceptionHeaders + } + }, + requestBody: Parameters.tags, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.versionId, + Parameters.comp18 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.contentType, + Parameters.accept, + Parameters.version, + Parameters.requestId, + Parameters.leaseId, + Parameters.ifTags, + Parameters.ifModifiedSince1, + Parameters.ifUnmodifiedSince1, + Parameters.ifMatch1, + Parameters.ifNoneMatch1, + Parameters.transactionalContentMD5, + Parameters.transactionalContentCrc64 + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer + }; + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/pageBlob.js +var require_pageBlob = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/pageBlob.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var pageBlob_exports = {}; + __export2(pageBlob_exports, { + PageBlobImpl: () => PageBlobImpl + }); + module2.exports = __toCommonJS2(pageBlob_exports); + var coreClient = __toESM2(require_commonjs8()); + var Mappers = __toESM2(require_mappers()); + var Parameters = __toESM2(require_parameters()); + var PageBlobImpl = class { + client; + /** + * Initialize a new instance of the class PageBlob class. + * @param client Reference to the service client + */ + constructor(client) { + this.client = client; + } + /** + * The Create operation creates a new page blob. + * @param contentLength The length of the request. + * @param blobContentLength This header specifies the maximum size for the page blob, up to 1 TB. The + * page blob size must be aligned to a 512-byte boundary. + * @param options The options parameters. + */ + create(contentLength, blobContentLength, options) { + return this.client.sendOperationRequest( + { contentLength, blobContentLength, options }, + createOperationSpec + ); + } + /** + * The Upload Pages operation writes a range of pages to a page blob + * @param contentLength The length of the request. + * @param body Initial data + * @param options The options parameters. + */ + uploadPages(contentLength, body, options) { + return this.client.sendOperationRequest( + { contentLength, body, options }, + uploadPagesOperationSpec + ); + } + /** + * The Clear Pages operation clears a set of pages from a page blob + * @param contentLength The length of the request. + * @param options The options parameters. + */ + clearPages(contentLength, options) { + return this.client.sendOperationRequest( + { contentLength, options }, + clearPagesOperationSpec + ); + } + /** + * The Upload Pages operation writes a range of pages to a page blob where the contents are read from a + * URL + * @param sourceUrl Specify a URL to the copy source. + * @param sourceRange Bytes of source data in the specified range. The length of this range should + * match the ContentLength header and x-ms-range/Range destination range header. + * @param contentLength The length of the request. + * @param range The range of bytes to which the source range would be written. The range should be 512 + * aligned and range-end is required. + * @param options The options parameters. + */ + uploadPagesFromURL(sourceUrl, sourceRange, contentLength, range2, options) { + return this.client.sendOperationRequest( + { sourceUrl, sourceRange, contentLength, range: range2, options }, + uploadPagesFromURLOperationSpec + ); + } + /** + * The Get Page Ranges operation returns the list of valid page ranges for a page blob or snapshot of a + * page blob + * @param options The options parameters. + */ + getPageRanges(options) { + return this.client.sendOperationRequest( + { options }, + getPageRangesOperationSpec + ); + } + /** + * The Get Page Ranges Diff operation returns the list of valid page ranges for a page blob that were + * changed between target blob and previous snapshot. + * @param options The options parameters. + */ + getPageRangesDiff(options) { + return this.client.sendOperationRequest( + { options }, + getPageRangesDiffOperationSpec + ); + } + /** + * Resize the Blob + * @param blobContentLength This header specifies the maximum size for the page blob, up to 1 TB. The + * page blob size must be aligned to a 512-byte boundary. + * @param options The options parameters. + */ + resize(blobContentLength, options) { + return this.client.sendOperationRequest( + { blobContentLength, options }, + resizeOperationSpec + ); + } + /** + * Update the sequence number of the blob + * @param sequenceNumberAction Required if the x-ms-blob-sequence-number header is set for the request. + * This property applies to page blobs only. This property indicates how the service should modify the + * blob's sequence number + * @param options The options parameters. + */ + updateSequenceNumber(sequenceNumberAction, options) { + return this.client.sendOperationRequest( + { sequenceNumberAction, options }, + updateSequenceNumberOperationSpec + ); + } + /** + * The Copy Incremental operation copies a snapshot of the source page blob to a destination page blob. + * The snapshot is copied such that only the differential changes between the previously copied + * snapshot are transferred to the destination. The copied snapshots are complete copies of the + * original snapshot and can be read or copied from as usual. This API is supported since REST version + * 2016-05-31. + * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to + * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would + * appear in a request URI. The source blob must either be public or must be authenticated via a shared + * access signature. + * @param options The options parameters. + */ + copyIncremental(copySource, options) { + return this.client.sendOperationRequest( + { copySource, options }, + copyIncrementalOperationSpec + ); + } + }; + var xmlSerializer = coreClient.createSerializer( + Mappers, + /* isXml */ + true + ); + var createOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.PageBlobCreateHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.PageBlobCreateExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.contentLength, + Parameters.metadata, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.blobCacheControl, + Parameters.blobContentType, + Parameters.blobContentMD5, + Parameters.blobContentEncoding, + Parameters.blobContentLanguage, + Parameters.blobContentDisposition, + Parameters.immutabilityPolicyExpiry, + Parameters.immutabilityPolicyMode, + Parameters.encryptionScope, + Parameters.tier, + Parameters.blobTagsString, + Parameters.legalHold1, + Parameters.blobType, + Parameters.blobContentLength, + Parameters.blobSequenceNumber + ], + isXML: true, + serializer: xmlSerializer + }; + var uploadPagesOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.PageBlobUploadPagesHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.PageBlobUploadPagesExceptionHeaders + } + }, + requestBody: Parameters.body1, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp19], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.contentLength, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.range, + Parameters.structuredBodyType, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.encryptionScope, + Parameters.transactionalContentMD5, + Parameters.transactionalContentCrc64, + Parameters.contentType1, + Parameters.accept3, + Parameters.pageWrite, + Parameters.ifSequenceNumberLessThanOrEqualTo, + Parameters.ifSequenceNumberLessThan, + Parameters.ifSequenceNumberEqualTo, + Parameters.structuredContentLength + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "binary", + serializer: xmlSerializer + }; + var clearPagesOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.PageBlobClearPagesHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.PageBlobClearPagesExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp19], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.contentLength, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.range, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.encryptionScope, + Parameters.ifSequenceNumberLessThanOrEqualTo, + Parameters.ifSequenceNumberLessThan, + Parameters.ifSequenceNumberEqualTo, + Parameters.pageWrite1 + ], + isXML: true, + serializer: xmlSerializer + }; + var uploadPagesFromURLOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.PageBlobUploadPagesFromURLHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.PageBlobUploadPagesFromURLExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp19], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.contentLength, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.encryptionScope, + Parameters.sourceIfModifiedSince, + Parameters.sourceIfUnmodifiedSince, + Parameters.sourceIfMatch, + Parameters.sourceIfNoneMatch, + Parameters.sourceContentMD5, + Parameters.copySourceAuthorization, + Parameters.fileRequestIntent, + Parameters.pageWrite, + Parameters.ifSequenceNumberLessThanOrEqualTo, + Parameters.ifSequenceNumberLessThan, + Parameters.ifSequenceNumberEqualTo, + Parameters.sourceUrl, + Parameters.sourceRange, + Parameters.sourceContentCrc64, + Parameters.range1, + Parameters.sourceEncryptionKey, + Parameters.sourceEncryptionKeySha256, + Parameters.sourceEncryptionAlgorithm + ], + isXML: true, + serializer: xmlSerializer + }; + var getPageRangesOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.PageList, + headersMapper: Mappers.PageBlobGetPageRangesHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.PageBlobGetPageRangesExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.marker, + Parameters.maxPageSize, + Parameters.snapshot, + Parameters.comp20 + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.range, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags + ], + isXML: true, + serializer: xmlSerializer + }; + var getPageRangesDiffOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.PageList, + headersMapper: Mappers.PageBlobGetPageRangesDiffHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.PageBlobGetPageRangesDiffExceptionHeaders + } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.marker, + Parameters.maxPageSize, + Parameters.snapshot, + Parameters.comp20, + Parameters.prevsnapshot + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.range, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.prevSnapshotUrl + ], + isXML: true, + serializer: xmlSerializer + }; + var resizeOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.PageBlobResizeHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.PageBlobResizeExceptionHeaders + } + }, + queryParameters: [Parameters.comp, Parameters.timeoutInSeconds], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.encryptionScope, + Parameters.blobContentLength + ], + isXML: true, + serializer: xmlSerializer + }; + var updateSequenceNumberOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.PageBlobUpdateSequenceNumberHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.PageBlobUpdateSequenceNumberExceptionHeaders + } + }, + queryParameters: [Parameters.comp, Parameters.timeoutInSeconds], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.blobSequenceNumber, + Parameters.sequenceNumberAction + ], + isXML: true, + serializer: xmlSerializer + }; + var copyIncrementalOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 202: { + headersMapper: Mappers.PageBlobCopyIncrementalHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.PageBlobCopyIncrementalExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp21], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.copySource + ], + isXML: true, + serializer: xmlSerializer + }; + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/appendBlob.js +var require_appendBlob = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/appendBlob.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var appendBlob_exports = {}; + __export2(appendBlob_exports, { + AppendBlobImpl: () => AppendBlobImpl + }); + module2.exports = __toCommonJS2(appendBlob_exports); + var coreClient = __toESM2(require_commonjs8()); + var Mappers = __toESM2(require_mappers()); + var Parameters = __toESM2(require_parameters()); + var AppendBlobImpl = class { + client; + /** + * Initialize a new instance of the class AppendBlob class. + * @param client Reference to the service client + */ + constructor(client) { + this.client = client; + } + /** + * The Create Append Blob operation creates a new append blob. + * @param contentLength The length of the request. + * @param options The options parameters. + */ + create(contentLength, options) { + return this.client.sendOperationRequest( + { contentLength, options }, + createOperationSpec + ); + } + /** + * The Append Block operation commits a new block of data to the end of an existing append blob. The + * Append Block operation is permitted only if the blob was created with x-ms-blob-type set to + * AppendBlob. Append Block is supported only on version 2015-02-21 version or later. + * @param contentLength The length of the request. + * @param body Initial data + * @param options The options parameters. + */ + appendBlock(contentLength, body, options) { + return this.client.sendOperationRequest( + { contentLength, body, options }, + appendBlockOperationSpec + ); + } + /** + * The Append Block operation commits a new block of data to the end of an existing append blob where + * the contents are read from a source url. The Append Block operation is permitted only if the blob + * was created with x-ms-blob-type set to AppendBlob. Append Block is supported only on version + * 2015-02-21 version or later. + * @param sourceUrl Specify a URL to the copy source. + * @param contentLength The length of the request. + * @param options The options parameters. + */ + appendBlockFromUrl(sourceUrl, contentLength, options) { + return this.client.sendOperationRequest( + { sourceUrl, contentLength, options }, + appendBlockFromUrlOperationSpec + ); + } + /** + * The Seal operation seals the Append Blob to make it read-only. Seal is supported only on version + * 2019-12-12 version or later. + * @param options The options parameters. + */ + seal(options) { + return this.client.sendOperationRequest({ options }, sealOperationSpec); + } + }; + var xmlSerializer = coreClient.createSerializer( + Mappers, + /* isXml */ + true + ); + var createOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.AppendBlobCreateHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.AppendBlobCreateExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.contentLength, + Parameters.metadata, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.blobCacheControl, + Parameters.blobContentType, + Parameters.blobContentMD5, + Parameters.blobContentEncoding, + Parameters.blobContentLanguage, + Parameters.blobContentDisposition, + Parameters.immutabilityPolicyExpiry, + Parameters.immutabilityPolicyMode, + Parameters.encryptionScope, + Parameters.blobTagsString, + Parameters.legalHold1, + Parameters.blobType1 + ], + isXML: true, + serializer: xmlSerializer + }; + var appendBlockOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.AppendBlobAppendBlockHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.AppendBlobAppendBlockExceptionHeaders + } + }, + requestBody: Parameters.body1, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp22], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.contentLength, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.structuredBodyType, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.encryptionScope, + Parameters.transactionalContentMD5, + Parameters.transactionalContentCrc64, + Parameters.contentType1, + Parameters.accept3, + Parameters.structuredContentLength, + Parameters.maxSize, + Parameters.appendPosition + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "binary", + serializer: xmlSerializer + }; + var appendBlockFromUrlOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.AppendBlobAppendBlockFromUrlHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.AppendBlobAppendBlockFromUrlExceptionHeaders + } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp22], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.contentLength, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.encryptionScope, + Parameters.sourceIfModifiedSince, + Parameters.sourceIfUnmodifiedSince, + Parameters.sourceIfMatch, + Parameters.sourceIfNoneMatch, + Parameters.sourceContentMD5, + Parameters.copySourceAuthorization, + Parameters.fileRequestIntent, + Parameters.transactionalContentMD5, + Parameters.sourceUrl, + Parameters.sourceContentCrc64, + Parameters.sourceEncryptionKey, + Parameters.sourceEncryptionKeySha256, + Parameters.sourceEncryptionAlgorithm, + Parameters.maxSize, + Parameters.appendPosition, + Parameters.sourceRange1 + ], + isXML: true, + serializer: xmlSerializer }; - exports2.BlobDeleteExceptionHeaders = { - serializedName: "Blob_deleteExceptionHeaders", - type: { - name: "Composite", - className: "BlobDeleteExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + var sealOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: Mappers.AppendBlobSealHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.AppendBlobSealExceptionHeaders } + }, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp23], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.appendPosition + ], + isXML: true, + serializer: xmlSerializer + }; + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/blockBlob.js +var require_blockBlob = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/blockBlob.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobUndeleteHeaders = { - serializedName: "Blob_undeleteHeaders", - type: { - name: "Composite", - className: "BlobUndeleteHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var blockBlob_exports = {}; + __export2(blockBlob_exports, { + BlockBlobImpl: () => BlockBlobImpl + }); + module2.exports = __toCommonJS2(blockBlob_exports); + var coreClient = __toESM2(require_commonjs8()); + var Mappers = __toESM2(require_mappers()); + var Parameters = __toESM2(require_parameters()); + var BlockBlobImpl = class { + client; + /** + * Initialize a new instance of the class BlockBlob class. + * @param client Reference to the service client + */ + constructor(client) { + this.client = client; + } + /** + * The Upload Block Blob operation updates the content of an existing block blob. Updating an existing + * block blob overwrites any existing metadata on the blob. Partial updates are not supported with Put + * Blob; the content of the existing blob is overwritten with the content of the new blob. To perform a + * partial update of the content of a block blob, use the Put Block List operation. + * @param contentLength The length of the request. + * @param body Initial data + * @param options The options parameters. + */ + upload(contentLength, body, options) { + return this.client.sendOperationRequest( + { contentLength, body, options }, + uploadOperationSpec + ); + } + /** + * The Put Blob from URL operation creates a new Block Blob where the contents of the blob are read + * from a given URL. This API is supported beginning with the 2020-04-08 version. Partial updates are + * not supported with Put Blob from URL; the content of an existing blob is overwritten with the + * content of the new blob. To perform partial updates to a block blob’s contents using a source URL, + * use the Put Block from URL API in conjunction with Put Block List. + * @param contentLength The length of the request. + * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to + * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would + * appear in a request URI. The source blob must either be public or must be authenticated via a shared + * access signature. + * @param options The options parameters. + */ + putBlobFromUrl(contentLength, copySource, options) { + return this.client.sendOperationRequest( + { contentLength, copySource, options }, + putBlobFromUrlOperationSpec + ); + } + /** + * The Stage Block operation creates a new block to be committed as part of a blob + * @param blockId A valid Base64 string value that identifies the block. Prior to encoding, the string + * must be less than or equal to 64 bytes in size. For a given blob, the length of the value specified + * for the blockid parameter must be the same size for each block. + * @param contentLength The length of the request. + * @param body Initial data + * @param options The options parameters. + */ + stageBlock(blockId, contentLength, body, options) { + return this.client.sendOperationRequest( + { blockId, contentLength, body, options }, + stageBlockOperationSpec + ); + } + /** + * The Stage Block operation creates a new block to be committed as part of a blob where the contents + * are read from a URL. + * @param blockId A valid Base64 string value that identifies the block. Prior to encoding, the string + * must be less than or equal to 64 bytes in size. For a given blob, the length of the value specified + * for the blockid parameter must be the same size for each block. + * @param contentLength The length of the request. + * @param sourceUrl Specify a URL to the copy source. + * @param options The options parameters. + */ + stageBlockFromURL(blockId, contentLength, sourceUrl, options) { + return this.client.sendOperationRequest( + { blockId, contentLength, sourceUrl, options }, + stageBlockFromURLOperationSpec + ); + } + /** + * The Commit Block List operation writes a blob by specifying the list of block IDs that make up the + * blob. In order to be written as part of a blob, a block must have been successfully written to the + * server in a prior Put Block operation. You can call Put Block List to update a blob by uploading + * only those blocks that have changed, then committing the new and existing blocks together. You can + * do this by specifying whether to commit a block from the committed block list or from the + * uncommitted block list, or to commit the most recently uploaded version of the block, whichever list + * it may belong to. + * @param blocks Blob Blocks. + * @param options The options parameters. + */ + commitBlockList(blocks, options) { + return this.client.sendOperationRequest( + { blocks, options }, + commitBlockListOperationSpec + ); + } + /** + * The Get Block List operation retrieves the list of blocks that have been uploaded as part of a block + * blob + * @param listType Specifies whether to return the list of committed blocks, the list of uncommitted + * blocks, or both lists together. + * @param options The options parameters. + */ + getBlockList(listType, options) { + return this.client.sendOperationRequest( + { listType, options }, + getBlockListOperationSpec + ); } }; - exports2.BlobUndeleteExceptionHeaders = { - serializedName: "Blob_undeleteExceptionHeaders", - type: { - name: "Composite", - className: "BlobUndeleteExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + var xmlSerializer = coreClient.createSerializer( + Mappers, + /* isXml */ + true + ); + var uploadOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.BlockBlobUploadHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlockBlobUploadExceptionHeaders } - } + }, + requestBody: Parameters.body1, + queryParameters: [Parameters.timeoutInSeconds], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.contentLength, + Parameters.metadata, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.structuredBodyType, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.blobCacheControl, + Parameters.blobContentType, + Parameters.blobContentMD5, + Parameters.blobContentEncoding, + Parameters.blobContentLanguage, + Parameters.blobContentDisposition, + Parameters.immutabilityPolicyExpiry, + Parameters.immutabilityPolicyMode, + Parameters.encryptionScope, + Parameters.tier, + Parameters.blobTagsString, + Parameters.legalHold1, + Parameters.transactionalContentMD5, + Parameters.transactionalContentCrc64, + Parameters.contentType1, + Parameters.accept3, + Parameters.structuredContentLength, + Parameters.blobType2 + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "binary", + serializer: xmlSerializer }; - exports2.BlobSetExpiryHeaders = { - serializedName: "Blob_setExpiryHeaders", - type: { - name: "Composite", - className: "BlobSetExpiryHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } + var putBlobFromUrlOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.BlockBlobPutBlobFromUrlHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlockBlobPutBlobFromUrlExceptionHeaders } - } + }, + queryParameters: [Parameters.timeoutInSeconds], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.contentLength, + Parameters.metadata, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.blobCacheControl, + Parameters.blobContentType, + Parameters.blobContentMD5, + Parameters.blobContentEncoding, + Parameters.blobContentLanguage, + Parameters.blobContentDisposition, + Parameters.encryptionScope, + Parameters.tier, + Parameters.sourceIfModifiedSince, + Parameters.sourceIfUnmodifiedSince, + Parameters.sourceIfMatch, + Parameters.sourceIfNoneMatch, + Parameters.sourceIfTags, + Parameters.copySource, + Parameters.blobTagsString, + Parameters.sourceContentMD5, + Parameters.copySourceAuthorization, + Parameters.copySourceTags, + Parameters.fileRequestIntent, + Parameters.transactionalContentMD5, + Parameters.sourceEncryptionKey, + Parameters.sourceEncryptionKeySha256, + Parameters.sourceEncryptionAlgorithm, + Parameters.blobType2, + Parameters.copySourceBlobProperties + ], + isXML: true, + serializer: xmlSerializer }; - exports2.BlobSetExpiryExceptionHeaders = { - serializedName: "Blob_setExpiryExceptionHeaders", - type: { - name: "Composite", - className: "BlobSetExpiryExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + var stageBlockOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.BlockBlobStageBlockHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlockBlobStageBlockExceptionHeaders } - } + }, + requestBody: Parameters.body1, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.comp24, + Parameters.blockId + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.contentLength, + Parameters.leaseId, + Parameters.structuredBodyType, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.encryptionScope, + Parameters.transactionalContentMD5, + Parameters.transactionalContentCrc64, + Parameters.contentType1, + Parameters.accept3, + Parameters.structuredContentLength + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "binary", + serializer: xmlSerializer }; - exports2.BlobSetHttpHeadersHeaders = { - serializedName: "Blob_setHttpHeadersHeaders", - type: { - name: "Composite", - className: "BlobSetHttpHeadersHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - blobSequenceNumber: { - serializedName: "x-ms-blob-sequence-number", - xmlName: "x-ms-blob-sequence-number", - type: { - name: "Number" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + var stageBlockFromURLOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.BlockBlobStageBlockFromURLHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlockBlobStageBlockFromURLExceptionHeaders } - } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.comp24, + Parameters.blockId + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.contentLength, + Parameters.leaseId, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.encryptionScope, + Parameters.sourceIfModifiedSince, + Parameters.sourceIfUnmodifiedSince, + Parameters.sourceIfMatch, + Parameters.sourceIfNoneMatch, + Parameters.sourceContentMD5, + Parameters.copySourceAuthorization, + Parameters.fileRequestIntent, + Parameters.sourceUrl, + Parameters.sourceContentCrc64, + Parameters.sourceEncryptionKey, + Parameters.sourceEncryptionKeySha256, + Parameters.sourceEncryptionAlgorithm, + Parameters.sourceRange1 + ], + isXML: true, + serializer: xmlSerializer }; - exports2.BlobSetHttpHeadersExceptionHeaders = { - serializedName: "Blob_setHttpHeadersExceptionHeaders", - type: { - name: "Composite", - className: "BlobSetHttpHeadersExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + var commitBlockListOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: Mappers.BlockBlobCommitBlockListHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlockBlobCommitBlockListExceptionHeaders } - } + }, + requestBody: Parameters.blocks, + queryParameters: [Parameters.timeoutInSeconds, Parameters.comp25], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.contentType, + Parameters.accept, + Parameters.version, + Parameters.requestId, + Parameters.metadata, + Parameters.leaseId, + Parameters.ifModifiedSince, + Parameters.ifUnmodifiedSince, + Parameters.encryptionKey, + Parameters.encryptionKeySha256, + Parameters.encryptionAlgorithm, + Parameters.ifMatch, + Parameters.ifNoneMatch, + Parameters.ifTags, + Parameters.blobCacheControl, + Parameters.blobContentType, + Parameters.blobContentMD5, + Parameters.blobContentEncoding, + Parameters.blobContentLanguage, + Parameters.blobContentDisposition, + Parameters.immutabilityPolicyExpiry, + Parameters.immutabilityPolicyMode, + Parameters.encryptionScope, + Parameters.tier, + Parameters.blobTagsString, + Parameters.legalHold1, + Parameters.transactionalContentMD5, + Parameters.transactionalContentCrc64 + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer }; - exports2.BlobSetImmutabilityPolicyHeaders = { - serializedName: "Blob_setImmutabilityPolicyHeaders", - type: { - name: "Composite", - className: "BlobSetImmutabilityPolicyHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - immutabilityPolicyExpiry: { - serializedName: "x-ms-immutability-policy-until-date", - xmlName: "x-ms-immutability-policy-until-date", - type: { - name: "DateTimeRfc1123" - } - }, - immutabilityPolicyMode: { - serializedName: "x-ms-immutability-policy-mode", - xmlName: "x-ms-immutability-policy-mode", - type: { - name: "Enum", - allowedValues: ["Mutable", "Unlocked", "Locked"] - } - } + var getBlockListOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.BlockList, + headersMapper: Mappers.BlockBlobGetBlockListHeaders + }, + default: { + bodyMapper: Mappers.StorageError, + headersMapper: Mappers.BlockBlobGetBlockListExceptionHeaders } + }, + queryParameters: [ + Parameters.timeoutInSeconds, + Parameters.snapshot, + Parameters.comp25, + Parameters.listType + ], + urlParameters: [Parameters.url], + headerParameters: [ + Parameters.version, + Parameters.requestId, + Parameters.accept1, + Parameters.leaseId, + Parameters.ifTags + ], + isXML: true, + serializer: xmlSerializer + }; + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/index.js +var require_operations = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/index.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobSetImmutabilityPolicyExceptionHeaders = { - serializedName: "Blob_setImmutabilityPolicyExceptionHeaders", - type: { - name: "Composite", - className: "BlobSetImmutabilityPolicyExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var operations_exports = {}; + module2.exports = __toCommonJS2(operations_exports); + __reExport(operations_exports, require_service(), module2.exports); + __reExport(operations_exports, require_container(), module2.exports); + __reExport(operations_exports, require_blob(), module2.exports); + __reExport(operations_exports, require_pageBlob(), module2.exports); + __reExport(operations_exports, require_appendBlob(), module2.exports); + __reExport(operations_exports, require_blockBlob(), module2.exports); + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/storageClient.js +var require_storageClient = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/storageClient.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobDeleteImmutabilityPolicyHeaders = { - serializedName: "Blob_deleteImmutabilityPolicyHeaders", - type: { - name: "Composite", - className: "BlobDeleteImmutabilityPolicyHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var storageClient_exports = {}; + __export2(storageClient_exports, { + StorageClient: () => StorageClient2 + }); + module2.exports = __toCommonJS2(storageClient_exports); + var coreHttpCompat = __toESM2(require_commonjs9()); + var import_operations = require_operations(); + var StorageClient2 = class extends coreHttpCompat.ExtendedServiceClient { + url; + version; + /** + * Initializes a new instance of the StorageClient class. + * @param url The URL of the service account, container, or blob that is the target of the desired + * operation. + * @param options The parameter options + */ + constructor(url2, options) { + if (url2 === void 0) { + throw new Error("'url' cannot be null"); + } + if (!options) { + options = {}; } + const defaults3 = { + requestContentType: "application/json; charset=utf-8" + }; + const packageDetails = `azsdk-js-azure-storage-blob/12.34.0`; + const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`; + const optionsWithDefaults = { + ...defaults3, + ...options, + userAgentOptions: { + userAgentPrefix + }, + endpoint: options.endpoint ?? options.baseUri ?? "{url}" + }; + super(optionsWithDefaults); + this.url = url2; + this.version = options.version || "2026-10-06"; + this.service = new import_operations.ServiceImpl(this); + this.container = new import_operations.ContainerImpl(this); + this.blob = new import_operations.BlobImpl(this); + this.pageBlob = new import_operations.PageBlobImpl(this); + this.appendBlob = new import_operations.AppendBlobImpl(this); + this.blockBlob = new import_operations.BlockBlobImpl(this); } + service; + container; + blob; + pageBlob; + appendBlob; + blockBlob; }; - exports2.BlobDeleteImmutabilityPolicyExceptionHeaders = { - serializedName: "Blob_deleteImmutabilityPolicyExceptionHeaders", - type: { - name: "Composite", - className: "BlobDeleteImmutabilityPolicyExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/service.js +var require_service2 = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/service.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobSetLegalHoldHeaders = { - serializedName: "Blob_setLegalHoldHeaders", - type: { - name: "Composite", - className: "BlobSetLegalHoldHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - legalHold: { - serializedName: "x-ms-legal-hold", - xmlName: "x-ms-legal-hold", - type: { - name: "Boolean" - } - } - } + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var service_exports = {}; + module2.exports = __toCommonJS2(service_exports); + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/container.js +var require_container2 = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/container.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobSetLegalHoldExceptionHeaders = { - serializedName: "Blob_setLegalHoldExceptionHeaders", - type: { - name: "Composite", - className: "BlobSetLegalHoldExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var container_exports = {}; + module2.exports = __toCommonJS2(container_exports); + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/blob.js +var require_blob2 = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/blob.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobSetMetadataHeaders = { - serializedName: "Blob_setMetadataHeaders", - type: { - name: "Composite", - className: "BlobSetMetadataHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - versionId: { - serializedName: "x-ms-version-id", - xmlName: "x-ms-version-id", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - xmlName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var blob_exports = {}; + module2.exports = __toCommonJS2(blob_exports); + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/pageBlob.js +var require_pageBlob2 = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/pageBlob.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobSetMetadataExceptionHeaders = { - serializedName: "Blob_setMetadataExceptionHeaders", - type: { - name: "Composite", - className: "BlobSetMetadataExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var pageBlob_exports = {}; + module2.exports = __toCommonJS2(pageBlob_exports); + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/appendBlob.js +var require_appendBlob2 = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/appendBlob.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobAcquireLeaseHeaders = { - serializedName: "Blob_acquireLeaseHeaders", - type: { - name: "Composite", - className: "BlobAcquireLeaseHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - leaseId: { - serializedName: "x-ms-lease-id", - xmlName: "x-ms-lease-id", - type: { - name: "String" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var appendBlob_exports = {}; + module2.exports = __toCommonJS2(appendBlob_exports); + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/blockBlob.js +var require_blockBlob2 = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/blockBlob.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobAcquireLeaseExceptionHeaders = { - serializedName: "Blob_acquireLeaseExceptionHeaders", - type: { - name: "Composite", - className: "BlobAcquireLeaseExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var blockBlob_exports = {}; + module2.exports = __toCommonJS2(blockBlob_exports); + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/index.js +var require_operationsInterfaces = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/index.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobReleaseLeaseHeaders = { - serializedName: "Blob_releaseLeaseHeaders", - type: { - name: "Composite", - className: "BlobReleaseLeaseHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var operationsInterfaces_exports = {}; + module2.exports = __toCommonJS2(operationsInterfaces_exports); + __reExport(operationsInterfaces_exports, require_service2(), module2.exports); + __reExport(operationsInterfaces_exports, require_container2(), module2.exports); + __reExport(operationsInterfaces_exports, require_blob2(), module2.exports); + __reExport(operationsInterfaces_exports, require_pageBlob2(), module2.exports); + __reExport(operationsInterfaces_exports, require_appendBlob2(), module2.exports); + __reExport(operationsInterfaces_exports, require_blockBlob2(), module2.exports); + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/generated/src/index.js +var require_src2 = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/generated/src/index.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobReleaseLeaseExceptionHeaders = { - serializedName: "Blob_releaseLeaseExceptionHeaders", - type: { - name: "Composite", - className: "BlobReleaseLeaseExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var src_exports = {}; + __export2(src_exports, { + StorageClient: () => import_storageClient.StorageClient + }); + module2.exports = __toCommonJS2(src_exports); + __reExport(src_exports, require_models(), module2.exports); + var import_storageClient = require_storageClient(); + __reExport(src_exports, require_operationsInterfaces(), module2.exports); + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/StorageContextClient.js +var require_StorageContextClient = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/StorageContextClient.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobRenewLeaseHeaders = { - serializedName: "Blob_renewLeaseHeaders", - type: { - name: "Composite", - className: "BlobRenewLeaseHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - leaseId: { - serializedName: "x-ms-lease-id", - xmlName: "x-ms-lease-id", - type: { - name: "String" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageContextClient_exports = {}; + __export2(StorageContextClient_exports, { + StorageContextClient: () => StorageContextClient + }); + module2.exports = __toCommonJS2(StorageContextClient_exports); + var import_src = require_src2(); + var StorageContextClient = class extends import_src.StorageClient { + async sendOperationRequest(operationArguments, operationSpec) { + const operationSpecToSend = { ...operationSpec }; + if (operationSpecToSend.path === "/{containerName}" || operationSpecToSend.path === "/{containerName}/{blob}") { + operationSpecToSend.path = ""; } + return super.sendOperationRequest(operationArguments, operationSpecToSend); } }; - exports2.BlobRenewLeaseExceptionHeaders = { - serializedName: "Blob_renewLeaseExceptionHeaders", - type: { - name: "Composite", - className: "BlobRenewLeaseExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/utils/utils.common.js +var require_utils_common2 = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/utils/utils.common.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobChangeLeaseHeaders = { - serializedName: "Blob_changeLeaseHeaders", - type: { - name: "Composite", - className: "BlobChangeLeaseHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - leaseId: { - serializedName: "x-ms-lease-id", - xmlName: "x-ms-lease-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var utils_common_exports = {}; + __export2(utils_common_exports, { + BlobNameToString: () => BlobNameToString, + ConvertInternalResponseOfListBlobFlat: () => ConvertInternalResponseOfListBlobFlat, + ConvertInternalResponseOfListBlobHierarchy: () => ConvertInternalResponseOfListBlobHierarchy, + EscapePath: () => EscapePath, + ExtractPageRangeInfoItems: () => ExtractPageRangeInfoItems, + appendToURLPath: () => appendToURLPath, + appendToURLQuery: () => appendToURLQuery, + assertResponse: () => assertResponse, + attachCredential: () => attachCredential, + base64decode: () => base64decode, + base64encode: () => base64encode, + delay: () => delay2, + escapeURLPath: () => escapeURLPath, + extractConnectionStringParts: () => extractConnectionStringParts, + generateBlockID: () => generateBlockID, + getAccountNameFromUrl: () => getAccountNameFromUrl, + getURLParameter: () => getURLParameter, + getURLPath: () => getURLPath, + getURLPathAndQuery: () => getURLPathAndQuery, + getURLQueries: () => getURLQueries, + getURLScheme: () => getURLScheme, + getValueInConnString: () => getValueInConnString, + httpAuthorizationToString: () => httpAuthorizationToString, + iEqual: () => iEqual, + isIpEndpointStyle: () => isIpEndpointStyle, + padStart: () => padStart2, + parseObjectReplicationRecord: () => parseObjectReplicationRecord, + readResponseBodyToBytes: () => readResponseBodyToBytes, + resolveResponseFormat: () => resolveResponseFormat, + sanitizeHeaders: () => sanitizeHeaders, + sanitizeURL: () => sanitizeURL, + setURLHost: () => setURLHost, + setURLParameter: () => setURLParameter, + setUploadChecksumParameters: () => setUploadChecksumParameters, + toBlobTags: () => toBlobTags, + toBlobTagsString: () => toBlobTagsString, + toQuerySerialization: () => toQuerySerialization, + toTags: () => toTags, + truncatedISO8061Date: () => truncatedISO8061Date + }); + module2.exports = __toCommonJS2(utils_common_exports); + var import_core_rest_pipeline = require_commonjs6(); + var import_core_util = require_commonjs4(); + var import_storage_common = require_commonjs12(); + var import_constants5 = require_constants11(); + var import_storage_common2 = require_commonjs12(); + var accountNameSuffixes = [ + "-secondary-ipv6", + "-secondary-dualstack", + "-ipv6", + "-dualstack", + "-secondary" + ]; + function escapeURLPath(url2) { + const urlParsed = new URL(url2); + let path30 = urlParsed.pathname; + path30 = path30 || "/"; + path30 = escape3(path30); + urlParsed.pathname = path30; + return urlParsed.toString(); + } + function getProxyUriFromDevConnString(connectionString) { + let proxyUri = ""; + if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { + const matchCredentials = connectionString.split(";"); + for (const element of matchCredentials) { + if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { + proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; } } } - }; - exports2.BlobChangeLeaseExceptionHeaders = { - serializedName: "Blob_changeLeaseExceptionHeaders", - type: { - name: "Composite", - className: "BlobChangeLeaseExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + return proxyUri; + } + function getValueInConnString(connectionString, argument) { + const elements = connectionString.split(";"); + for (const element of elements) { + if (element.trim().startsWith(argument)) { + return element.trim().match(argument + "=(.*)")[1]; } } - }; - exports2.BlobBreakLeaseHeaders = { - serializedName: "Blob_breakLeaseHeaders", - type: { - name: "Composite", - className: "BlobBreakLeaseHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - leaseTime: { - serializedName: "x-ms-lease-time", - xmlName: "x-ms-lease-time", - type: { - name: "Number" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } + return ""; + } + function extractConnectionStringParts(connectionString) { + let proxyUri = ""; + if (connectionString.startsWith("UseDevelopmentStorage=true")) { + proxyUri = getProxyUriFromDevConnString(connectionString); + connectionString = import_constants5.DevelopmentConnectionString; + } + let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); + blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; + if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && connectionString.search("AccountKey=") !== -1) { + let defaultEndpointsProtocol = ""; + let accountName = ""; + let accountKey = Buffer.from("accountKey", "base64"); + let endpointSuffix = ""; + accountName = getValueInConnString(connectionString, "AccountName"); + accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); + if (!blobEndpoint) { + defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); + const protocol = defaultEndpointsProtocol.toLowerCase(); + if (protocol !== "https" && protocol !== "http") { + throw new Error( + "Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'" + ); + } + endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix"); + if (!endpointSuffix) { + throw new Error("Invalid EndpointSuffix in the provided Connection String"); } + blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; + } + if (!accountName) { + throw new Error("Invalid AccountName in the provided Connection String"); + } else if (accountKey.length === 0) { + throw new Error("Invalid AccountKey in the provided Connection String"); + } + return { + kind: "AccountConnString", + url: blobEndpoint, + accountName, + accountKey, + proxyUri + }; + } else { + let accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); + let accountName = getValueInConnString(connectionString, "AccountName"); + if (!accountName) { + accountName = getAccountNameFromUrl(blobEndpoint); + } + if (!blobEndpoint) { + throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); + } else if (!accountSas) { + throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); + } + if (accountSas.startsWith("?")) { + accountSas = accountSas.substring(1); } + return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas }; } - }; - exports2.BlobBreakLeaseExceptionHeaders = { - serializedName: "Blob_breakLeaseExceptionHeaders", - type: { - name: "Composite", - className: "BlobBreakLeaseExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } + } + function escape3(text) { + return encodeURIComponent(text).replace(/%2F/g, "/").replace(/'/g, "%27").replace(/\+/g, "%20").replace(/%25/g, "%"); + } + function appendToURLPath(url2, name) { + const urlParsed = new URL(url2); + let path30 = urlParsed.pathname; + path30 = path30 ? path30.endsWith("/") ? `${path30}${name}` : `${path30}/${name}` : name; + urlParsed.pathname = path30; + return urlParsed.toString(); + } + function setURLParameter(url2, name, value) { + const urlParsed = new URL(url2); + const encodedName = encodeURIComponent(name); + const encodedValue = value ? encodeURIComponent(value) : void 0; + const searchString = urlParsed.search === "" ? "?" : urlParsed.search; + const searchPieces = []; + for (const pair of searchString.slice(1).split("&")) { + if (pair) { + const [key] = pair.split("=", 2); + if (key !== encodedName) { + searchPieces.push(pair); } } } - }; - exports2.BlobCreateSnapshotHeaders = { - serializedName: "Blob_createSnapshotHeaders", - type: { - name: "Composite", - className: "BlobCreateSnapshotHeaders", - modelProperties: { - snapshot: { - serializedName: "x-ms-snapshot", - xmlName: "x-ms-snapshot", - type: { - name: "String" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - versionId: { - serializedName: "x-ms-version-id", - xmlName: "x-ms-version-id", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - xmlName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } + if (encodedValue) { + searchPieces.push(`${encodedName}=${encodedValue}`); + } + urlParsed.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; + return urlParsed.toString(); + } + function getURLParameter(url2, name) { + const urlParsed = new URL(url2); + return urlParsed.searchParams.get(name) ?? void 0; + } + function setURLHost(url2, host) { + const urlParsed = new URL(url2); + urlParsed.hostname = host; + return urlParsed.toString(); + } + function getURLPath(url2) { + try { + const urlParsed = new URL(url2); + return urlParsed.pathname; + } catch (e) { + return void 0; + } + } + function getURLScheme(url2) { + try { + const urlParsed = new URL(url2); + return urlParsed.protocol.endsWith(":") ? urlParsed.protocol.slice(0, -1) : urlParsed.protocol; + } catch (e) { + return void 0; + } + } + function getURLPathAndQuery(url2) { + const urlParsed = new URL(url2); + const pathString = urlParsed.pathname; + if (!pathString) { + throw new RangeError("Invalid url without valid path."); + } + let queryString = urlParsed.search || ""; + queryString = queryString.trim(); + if (queryString !== "") { + queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; + } + return `${pathString}${queryString}`; + } + function getURLQueries(url2) { + let queryString = new URL(url2).search; + if (!queryString) { + return {}; + } + queryString = queryString.trim(); + queryString = queryString.startsWith("?") ? queryString.substring(1) : queryString; + let querySubStrings = queryString.split("&"); + querySubStrings = querySubStrings.filter((value) => { + const indexOfEqual = value.indexOf("="); + const lastIndexOfEqual = value.lastIndexOf("="); + return indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1; + }); + const queries = {}; + for (const querySubString of querySubStrings) { + const splitResults = querySubString.split("="); + const key = splitResults[0]; + const value = splitResults[1]; + queries[key] = value; + } + return queries; + } + function appendToURLQuery(url2, queryParts) { + const urlParsed = new URL(url2); + let query = urlParsed.search; + if (query) { + query += "&" + queryParts; + } else { + query = queryParts; + } + urlParsed.search = query; + return urlParsed.toString(); + } + function truncatedISO8061Date(date, withMilliseconds = true) { + const dateString = date.toISOString(); + return withMilliseconds ? dateString.substring(0, dateString.length - 1) + "0000Z" : dateString.substring(0, dateString.length - 5) + "Z"; + } + function base64encode(content) { + return !import_core_util.isNodeLike ? btoa(content) : Buffer.from(content).toString("base64"); + } + function base64decode(encodedString) { + return !import_core_util.isNodeLike ? atob(encodedString) : Buffer.from(encodedString, "base64").toString(); + } + function generateBlockID(blockIDPrefix, blockIndex) { + const maxSourceStringLength = 48; + const maxBlockIndexLength = 6; + const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; + if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { + blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); + } + const res = blockIDPrefix + padStart2(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); + return base64encode(res); + } + async function delay2(timeInMs, aborter, abortError) { + return new Promise((resolve15, reject) => { + let timeout; + const abortHandler = () => { + if (timeout !== void 0) { + clearTimeout(timeout); } + reject(abortError); + }; + const resolveHandler = () => { + if (aborter !== void 0) { + aborter.removeEventListener("abort", abortHandler); + } + resolve15(); + }; + timeout = setTimeout(resolveHandler, timeInMs); + if (aborter !== void 0) { + aborter.addEventListener("abort", abortHandler); } + }); + } + function padStart2(currentString, targetLength, padString = " ") { + if (String.prototype.padStart) { + return currentString.padStart(targetLength, padString); } - }; - exports2.BlobCreateSnapshotExceptionHeaders = { - serializedName: "Blob_createSnapshotExceptionHeaders", - type: { - name: "Composite", - className: "BlobCreateSnapshotExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + padString = padString || " "; + if (currentString.length > targetLength) { + return currentString; + } else { + targetLength = targetLength - currentString.length; + if (targetLength > padString.length) { + padString += padString.repeat(targetLength / padString.length); } + return padString.slice(0, targetLength) + currentString; } - }; - exports2.BlobStartCopyFromURLHeaders = { - serializedName: "Blob_startCopyFromURLHeaders", - type: { - name: "Composite", - className: "BlobStartCopyFromURLHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - versionId: { - serializedName: "x-ms-version-id", - xmlName: "x-ms-version-id", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - copyId: { - serializedName: "x-ms-copy-id", - xmlName: "x-ms-copy-id", - type: { - name: "String" - } - }, - copyStatus: { - serializedName: "x-ms-copy-status", - xmlName: "x-ms-copy-status", - type: { - name: "Enum", - allowedValues: ["pending", "success", "aborted", "failed"] - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + } + function sanitizeURL(url2) { + let safeURL = url2; + if (getURLParameter(safeURL, import_constants5.URLConstants.Parameters.SIGNATURE)) { + safeURL = setURLParameter(safeURL, import_constants5.URLConstants.Parameters.SIGNATURE, "*****"); + } + return safeURL; + } + function sanitizeHeaders(originalHeader) { + const headers = (0, import_core_rest_pipeline.createHttpHeaders)(); + for (const [name, value] of originalHeader) { + if (name.toLowerCase() === import_constants5.HeaderConstants.AUTHORIZATION.toLowerCase()) { + headers.set(name, "*****"); + } else if (name.toLowerCase() === import_constants5.HeaderConstants.X_MS_COPY_SOURCE) { + headers.set(name, sanitizeURL(value)); + } else { + headers.set(name, value); } } - }; - exports2.BlobStartCopyFromURLExceptionHeaders = { - serializedName: "Blob_startCopyFromURLExceptionHeaders", - type: { - name: "Composite", - className: "BlobStartCopyFromURLExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - }, - copySourceErrorCode: { - serializedName: "x-ms-copy-source-error-code", - xmlName: "x-ms-copy-source-error-code", - type: { - name: "String" - } - }, - copySourceStatusCode: { - serializedName: "x-ms-copy-source-status-code", - xmlName: "x-ms-copy-source-status-code", - type: { - name: "Number" + return headers; + } + function iEqual(str1, str2) { + return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); + } + function getAccountNameFromUrl(url2) { + const parsedUrl = new URL(url2); + let accountName; + try { + if (parsedUrl.hostname.split(".")[1] === "blob") { + accountName = parsedUrl.hostname.split(".")[0]; + for (let i = 0; i < accountNameSuffixes.length; ++i) { + const suffix = accountNameSuffixes[i]; + if (accountName.endsWith(suffix)) { + accountName = accountName.substring(0, accountName.length - suffix.length); + break; } } + } else if (isIpEndpointStyle(parsedUrl)) { + accountName = parsedUrl.pathname.split("/")[1]; + } else { + accountName = ""; } + return accountName; + } catch (error3) { + throw new Error("Unable to extract accountName with provided information."); } - }; - exports2.BlobCopyFromURLHeaders = { - serializedName: "Blob_copyFromURLHeaders", - type: { - name: "Composite", - className: "BlobCopyFromURLHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - versionId: { - serializedName: "x-ms-version-id", - xmlName: "x-ms-version-id", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - copyId: { - serializedName: "x-ms-copy-id", - xmlName: "x-ms-copy-id", - type: { - name: "String" - } - }, - copyStatus: { - defaultValue: "success", - isConstant: true, - serializedName: "x-ms-copy-status", - type: { - name: "String" - } - }, - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" + } + function isIpEndpointStyle(parsedUrl) { + const host = parsedUrl.host; + return /^.*:.*:.*$|^(localhost|host.docker.internal)(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test( + host + ) || Boolean(parsedUrl.port) && import_constants5.PathStylePorts.includes(parsedUrl.port); + } + function toBlobTagsString(tags) { + if (tags === void 0) { + return void 0; + } + const tagPairs = []; + for (const key in tags) { + if (Object.prototype.hasOwnProperty.call(tags, key)) { + const value = tags[key]; + tagPairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); + } + } + return tagPairs.join("&"); + } + function toBlobTags(tags) { + if (tags === void 0) { + return void 0; + } + const res = { + blobTagSet: [] + }; + for (const key in tags) { + if (Object.prototype.hasOwnProperty.call(tags, key)) { + const value = tags[key]; + res.blobTagSet.push({ + key, + value + }); + } + } + return res; + } + function toTags(tags) { + if (tags === void 0) { + return void 0; + } + const res = {}; + for (const blobTag of tags.blobTagSet) { + res[blobTag.key] = blobTag.value; + } + return res; + } + function toQuerySerialization(textConfiguration) { + if (textConfiguration === void 0) { + return void 0; + } + switch (textConfiguration.kind) { + case "csv": + return { + format: { + type: "delimited", + delimitedTextConfiguration: { + columnSeparator: textConfiguration.columnSeparator || ",", + fieldQuote: textConfiguration.fieldQuote || "", + recordSeparator: textConfiguration.recordSeparator, + escapeChar: textConfiguration.escapeCharacter || "", + headersPresent: textConfiguration.hasHeaders || false + } } - }, - xMsContentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", - type: { - name: "ByteArray" + }; + case "json": + return { + format: { + type: "json", + jsonTextConfiguration: { + recordSeparator: textConfiguration.recordSeparator + } } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" + }; + case "arrow": + return { + format: { + type: "arrow", + arrowConfiguration: { + schema: textConfiguration.schema + } } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" + }; + case "parquet": + return { + format: { + type: "parquet" } - } + }; + default: + throw Error("Invalid BlobQueryTextConfiguration."); + } + } + function parseObjectReplicationRecord(objectReplicationRecord) { + if (!objectReplicationRecord) { + return void 0; + } + if ("policy-id" in objectReplicationRecord) { + return void 0; + } + const orProperties = []; + for (const key in objectReplicationRecord) { + const ids = key.split("_"); + const policyPrefix = "or-"; + if (ids[0].startsWith(policyPrefix)) { + ids[0] = ids[0].substring(policyPrefix.length); + } + const rule = { + ruleId: ids[1], + replicationStatus: objectReplicationRecord[key] + }; + const policyIndex = orProperties.findIndex((policy) => policy.policyId === ids[0]); + if (policyIndex > -1) { + orProperties[policyIndex].rules.push(rule); + } else { + orProperties.push({ + policyId: ids[0], + rules: [rule] + }); } } - }; - exports2.BlobCopyFromURLExceptionHeaders = { - serializedName: "Blob_copyFromURLExceptionHeaders", - type: { - name: "Composite", - className: "BlobCopyFromURLExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - }, - copySourceErrorCode: { - serializedName: "x-ms-copy-source-error-code", - xmlName: "x-ms-copy-source-error-code", - type: { - name: "String" - } - }, - copySourceStatusCode: { - serializedName: "x-ms-copy-source-status-code", - xmlName: "x-ms-copy-source-status-code", - type: { - name: "Number" - } - } + return orProperties; + } + function resolveResponseFormat(responseFormat) { + if (responseFormat === void 0 || responseFormat === import_storage_common.StorageResponseFormat.Auto) { + return import_storage_common.StorageResponseFormat.Xml; + } + return responseFormat; + } + function attachCredential(thing, credential) { + thing.credential = credential; + return thing; + } + function httpAuthorizationToString(httpAuthorization) { + return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : void 0; + } + function BlobNameToString(name) { + if (name.encoded) { + return decodeURIComponent(name.content); + } else { + return name.content; + } + } + function ConvertInternalResponseOfListBlobFlat(internalResponse) { + return { + ...internalResponse, + segment: { + blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { + const blobItem = { + ...blobItemInteral, + name: BlobNameToString(blobItemInteral.name) + }; + return blobItem; + }) + } + }; + } + function ConvertInternalResponseOfListBlobHierarchy(internalResponse) { + return { + ...internalResponse, + segment: { + blobPrefixes: internalResponse.segment.blobPrefixes?.map((blobPrefixInternal) => { + const blobPrefix = { + ...blobPrefixInternal, + name: BlobNameToString(blobPrefixInternal.name) + }; + return blobPrefix; + }), + blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { + const blobItem = { + ...blobItemInteral, + name: BlobNameToString(blobItemInteral.name) + }; + return blobItem; + }) + } + }; + } + function* ExtractPageRangeInfoItems(getPageRangesSegment) { + let pageRange = []; + let clearRange = []; + if (getPageRangesSegment.pageRange) pageRange = getPageRangesSegment.pageRange; + if (getPageRangesSegment.clearRange) clearRange = getPageRangesSegment.clearRange; + let pageRangeIndex = 0; + let clearRangeIndex = 0; + while (pageRangeIndex < pageRange.length && clearRangeIndex < clearRange.length) { + if (pageRange[pageRangeIndex].start < clearRange[clearRangeIndex].start) { + yield { + start: pageRange[pageRangeIndex].start, + end: pageRange[pageRangeIndex].end, + isClear: false + }; + ++pageRangeIndex; + } else { + yield { + start: clearRange[clearRangeIndex].start, + end: clearRange[clearRangeIndex].end, + isClear: true + }; + ++clearRangeIndex; } } - }; - exports2.BlobAbortCopyFromURLHeaders = { - serializedName: "Blob_abortCopyFromURLHeaders", - type: { - name: "Composite", - className: "BlobAbortCopyFromURLHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } + for (; pageRangeIndex < pageRange.length; ++pageRangeIndex) { + yield { + start: pageRange[pageRangeIndex].start, + end: pageRange[pageRangeIndex].end, + isClear: false + }; + } + for (; clearRangeIndex < clearRange.length; ++clearRangeIndex) { + yield { + start: clearRange[clearRangeIndex].start, + end: clearRange[clearRangeIndex].end, + isClear: true + }; + } + } + function EscapePath(blobName) { + const split = blobName.split("/"); + for (let i = 0; i < split.length; i++) { + split[i] = encodeURIComponent(split[i]); + } + return split.join("/"); + } + async function readResponseBodyToBytes(response) { + if (response.blobBody) { + const blob = await response.blobBody; + return new Uint8Array(await blob.arrayBuffer()); + } + if (response.readableStreamBody) { + return readNodeStreamToBytes(response.readableStreamBody); + } + throw new RangeError("List Blobs response body is empty or unavailable."); + } + function readNodeStreamToBytes(stream2) { + return new Promise((resolve15, reject) => { + const chunks = []; + let totalLength = 0; + stream2.on("data", (chunk) => { + const bytes = typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk; + chunks.push(bytes); + totalLength += bytes.byteLength; + }); + stream2.on("end", () => { + const result = new Uint8Array(totalLength); + let offset = 0; + for (const chunk of chunks) { + result.set(chunk, offset); + offset += chunk.byteLength; } - } + resolve15(result); + }); + stream2.on("error", reject); + }); + } + function assertResponse(response) { + if (`_response` in response) { + return response; + } + throw new TypeError(`Unexpected response object ${response}`); + } + async function setUploadChecksumParameters(body, contentLength, parameters, uploadOptions, configContentChecksumAlgorithm) { + let contentChecksumAlgorithm = uploadOptions.contentChecksumAlgorithm ?? configContentChecksumAlgorithm; + if (contentChecksumAlgorithm === void 0) { + contentChecksumAlgorithm = "Customized"; + } + if (contentChecksumAlgorithm === "Auto") { + contentChecksumAlgorithm = "StorageCrc64"; + } + let bodyInfo = void 0; + if (contentChecksumAlgorithm === "Customized") { + parameters.transactionalContentMD5 = uploadOptions.transactionalContentMD5; + parameters.transactionalContentCrc64 = uploadOptions.transactionalContentCrc64; + } else if (contentChecksumAlgorithm === "StorageCrc64") { + await import_storage_common2.StorageCRC64Calculator.init(); + bodyInfo = await (0, import_storage_common2.structuredMessageEncoding)(body, contentLength); + parameters.structuredBodyType = "XSM/1.0; properties=crc64"; + parameters.structuredContentLength = contentLength; } + return { + body: contentChecksumAlgorithm === "StorageCrc64" ? bodyInfo.body : body, + contentLength: contentChecksumAlgorithm === "StorageCrc64" ? bodyInfo.encodedContentLength : contentLength, + contentChecksumAlgorithm + }; + } + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/StorageClient.js +var require_StorageClient = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/StorageClient.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); }; - exports2.BlobAbortCopyFromURLExceptionHeaders = { - serializedName: "Blob_abortCopyFromURLExceptionHeaders", - type: { - name: "Composite", - className: "BlobAbortCopyFromURLExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobSetTierHeaders = { - serializedName: "Blob_setTierHeaders", - type: { - name: "Composite", - className: "BlobSetTierHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var StorageClient_exports = {}; + __export2(StorageClient_exports, { + StorageClient: () => StorageClient2 + }); + module2.exports = __toCommonJS2(StorageClient_exports); + var import_StorageContextClient = require_StorageContextClient(); + var import_Pipeline = require_Pipeline(); + var import_utils_common = require_utils_common2(); + var StorageClient2 = class { + /** + * Encoded URL string value. + */ + url; + accountName; + /** + * Request policy pipeline. + * + * @internal + */ + pipeline; + /** + * Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. + */ + credential; + /** + * StorageClient is a reference to protocol layer operations entry, which is + * generated by AutoRest generator. + */ + storageClientContext; + /** + */ + isHttps; + /** + * Creates an instance of StorageClient. + * @param url - url to resource + * @param pipeline - request policy pipeline. + */ + constructor(url2, pipeline2) { + this.url = (0, import_utils_common.escapeURLPath)(url2); + this.accountName = (0, import_utils_common.getAccountNameFromUrl)(url2); + this.pipeline = pipeline2; + this.storageClientContext = new import_StorageContextClient.StorageContextClient(this.url, (0, import_Pipeline.getCoreClientOptions)(pipeline2)); + this.isHttps = (0, import_utils_common.iEqual)((0, import_utils_common.getURLScheme)(this.url) || "", "https"); + this.credential = (0, import_Pipeline.getCredentialFromPipeline)(pipeline2); + const storageClientContext = this.storageClientContext; + storageClientContext.requestContentType = void 0; } }; - exports2.BlobSetTierExceptionHeaders = { - serializedName: "Blob_setTierExceptionHeaders", - type: { - name: "Composite", - className: "BlobSetTierExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/utils/tracing.js +var require_tracing = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/utils/tracing.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.BlobGetAccountInfoHeaders = { - serializedName: "Blob_getAccountInfoHeaders", - type: { - name: "Composite", - className: "BlobGetAccountInfoHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - skuName: { - serializedName: "x-ms-sku-name", - xmlName: "x-ms-sku-name", - type: { - name: "Enum", - allowedValues: [ - "Standard_LRS", - "Standard_GRS", - "Standard_RAGRS", - "Standard_ZRS", - "Premium_LRS" - ] - } - }, - accountKind: { - serializedName: "x-ms-account-kind", - xmlName: "x-ms-account-kind", - type: { - name: "Enum", - allowedValues: [ - "Storage", - "BlobStorage", - "StorageV2", - "FileStorage", - "BlockBlobStorage" - ] - } - }, - isHierarchicalNamespaceEnabled: { - serializedName: "x-ms-is-hns-enabled", - xmlName: "x-ms-is-hns-enabled", - type: { - name: "Boolean" - } - } - } + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var tracing_exports = {}; + __export2(tracing_exports, { + tracingClient: () => tracingClient + }); + module2.exports = __toCommonJS2(tracing_exports); + var import_core_tracing = require_commonjs5(); + var import_constants5 = require_constants11(); + var tracingClient = (0, import_core_tracing.createTracingClient)({ + packageName: "@azure/storage-blob", + packageVersion: import_constants5.SDK_VERSION, + namespace: "Microsoft.Storage" + }); + } +}); + +// node_modules/apache-arrow/util/utf8.mjs +var decoder, decodeUtf8, encoder, encodeUtf8; +var init_utf8 = __esm({ + "node_modules/apache-arrow/util/utf8.mjs"() { + decoder = new TextDecoder("utf-8"); + decodeUtf8 = decoder.decode.bind(decoder); + encoder = new TextEncoder(); + encodeUtf8 = (value) => encoder.encode(value); + } +}); + +// node_modules/apache-arrow/util/compat.mjs +var isNumber2, isBoolean2, isFunction, isObject3, isPromise, isIterable, isAsyncIterable, isArrowJSON, isIteratorResult, isFileHandle, isFetchResponse, isReadableInterop, isWritableDOMStream, isReadableDOMStream, isWritableNodeStream, isReadableNodeStream, isFlatbuffersByteBuffer; +var init_compat = __esm({ + "node_modules/apache-arrow/util/compat.mjs"() { + isNumber2 = (x) => typeof x === "number"; + isBoolean2 = (x) => typeof x === "boolean"; + isFunction = (x) => typeof x === "function"; + isObject3 = (x) => x != null && Object(x) === x; + isPromise = (x) => { + return isObject3(x) && isFunction(x.then); + }; + isIterable = (x) => { + return isObject3(x) && isFunction(x[Symbol.iterator]); + }; + isAsyncIterable = (x) => { + return isObject3(x) && isFunction(x[Symbol.asyncIterator]); + }; + isArrowJSON = (x) => { + return isObject3(x) && isObject3(x["schema"]); + }; + isIteratorResult = (x) => { + return isObject3(x) && "done" in x && "value" in x; + }; + isFileHandle = (x) => { + return isObject3(x) && isFunction(x["stat"]) && isNumber2(x["fd"]); + }; + isFetchResponse = (x) => { + return isObject3(x) && isReadableDOMStream(x["body"]); + }; + isReadableInterop = (x) => "_getDOMStream" in x && "_getNodeStream" in x; + isWritableDOMStream = (x) => { + return isObject3(x) && isFunction(x["abort"]) && isFunction(x["getWriter"]) && !isReadableInterop(x); + }; + isReadableDOMStream = (x) => { + return isObject3(x) && isFunction(x["cancel"]) && isFunction(x["getReader"]) && !isReadableInterop(x); + }; + isWritableNodeStream = (x) => { + return isObject3(x) && isFunction(x["end"]) && isFunction(x["write"]) && isBoolean2(x["writable"]) && !isReadableInterop(x); + }; + isReadableNodeStream = (x) => { + return isObject3(x) && isFunction(x["read"]) && isFunction(x["pipe"]) && isBoolean2(x["readable"]) && !isReadableInterop(x); + }; + isFlatbuffersByteBuffer = (x) => { + return isObject3(x) && isFunction(x["clear"]) && isFunction(x["bytes"]) && isFunction(x["position"]) && isFunction(x["setPosition"]) && isFunction(x["capacity"]) && isFunction(x["getBufferIdentifier"]) && isFunction(x["createLong"]); + }; + } +}); + +// node_modules/apache-arrow/util/buffer.mjs +var buffer_exports = {}; +__export(buffer_exports, { + compareArrayLike: () => compareArrayLike, + joinUint8Arrays: () => joinUint8Arrays, + memcpy: () => memcpy, + rebaseValueOffsets: () => rebaseValueOffsets, + toArrayBufferView: () => toArrayBufferView, + toArrayBufferViewAsyncIterator: () => toArrayBufferViewAsyncIterator, + toArrayBufferViewIterator: () => toArrayBufferViewIterator, + toBigInt64Array: () => toBigInt64Array, + toBigUint64Array: () => toBigUint64Array, + toFloat32Array: () => toFloat32Array, + toFloat32ArrayAsyncIterator: () => toFloat32ArrayAsyncIterator, + toFloat32ArrayIterator: () => toFloat32ArrayIterator, + toFloat64Array: () => toFloat64Array, + toFloat64ArrayAsyncIterator: () => toFloat64ArrayAsyncIterator, + toFloat64ArrayIterator: () => toFloat64ArrayIterator, + toInt16Array: () => toInt16Array, + toInt16ArrayAsyncIterator: () => toInt16ArrayAsyncIterator, + toInt16ArrayIterator: () => toInt16ArrayIterator, + toInt32Array: () => toInt32Array, + toInt32ArrayAsyncIterator: () => toInt32ArrayAsyncIterator, + toInt32ArrayIterator: () => toInt32ArrayIterator, + toInt8Array: () => toInt8Array, + toInt8ArrayAsyncIterator: () => toInt8ArrayAsyncIterator, + toInt8ArrayIterator: () => toInt8ArrayIterator, + toUint16Array: () => toUint16Array, + toUint16ArrayAsyncIterator: () => toUint16ArrayAsyncIterator, + toUint16ArrayIterator: () => toUint16ArrayIterator, + toUint32Array: () => toUint32Array, + toUint32ArrayAsyncIterator: () => toUint32ArrayAsyncIterator, + toUint32ArrayIterator: () => toUint32ArrayIterator, + toUint8Array: () => toUint8Array, + toUint8ArrayAsyncIterator: () => toUint8ArrayAsyncIterator, + toUint8ArrayIterator: () => toUint8ArrayIterator, + toUint8ClampedArray: () => toUint8ClampedArray, + toUint8ClampedArrayAsyncIterator: () => toUint8ClampedArrayAsyncIterator, + toUint8ClampedArrayIterator: () => toUint8ClampedArrayIterator +}); +function collapseContiguousByteRanges(chunks) { + const result = chunks[0] ? [chunks[0]] : []; + let xOffset, yOffset, xLen, yLen; + for (let x, y, i = 0, j = 0, n = chunks.length; ++i < n; ) { + x = result[j]; + y = chunks[i]; + if (!x || !y || x.buffer !== y.buffer || y.byteOffset < x.byteOffset) { + y && (result[++j] = y); + continue; + } + ({ byteOffset: xOffset, byteLength: xLen } = x); + ({ byteOffset: yOffset, byteLength: yLen } = y); + if (xOffset + xLen < yOffset || yOffset + yLen < xOffset) { + y && (result[++j] = y); + continue; + } + result[j] = new Uint8Array(x.buffer, xOffset, yOffset - xOffset + yLen); + } + return result; +} +function memcpy(target, source, targetByteOffset = 0, sourceByteLength = source.byteLength) { + const targetByteLength = target.byteLength; + const dst = new Uint8Array(target.buffer, target.byteOffset, targetByteLength); + const src = new Uint8Array(source.buffer, source.byteOffset, Math.min(sourceByteLength, targetByteLength)); + dst.set(src, targetByteOffset); + return target; +} +function joinUint8Arrays(chunks, size) { + const result = collapseContiguousByteRanges(chunks); + const byteLength = result.reduce((x, b) => x + b.byteLength, 0); + let source, sliced, buffer; + let offset = 0, index2 = -1; + const length = Math.min(size || Number.POSITIVE_INFINITY, byteLength); + for (const n = result.length; ++index2 < n; ) { + source = result[index2]; + sliced = source.subarray(0, Math.min(source.length, length - offset)); + if (length <= offset + sliced.length) { + if (sliced.length < source.length) { + result[index2] = source.subarray(sliced.length); + } else if (sliced.length === source.length) { + index2++; } + buffer ? memcpy(buffer, sliced, offset) : buffer = sliced; + break; + } + memcpy(buffer || (buffer = new Uint8Array(length)), sliced, offset); + offset += sliced.length; + } + return [buffer || new Uint8Array(0), result.slice(index2), byteLength - (buffer ? buffer.byteLength : 0)]; +} +function toArrayBufferView(ArrayBufferViewCtor, input) { + let value = isIteratorResult(input) ? input.value : input; + if (value instanceof ArrayBufferViewCtor) { + if (ArrayBufferViewCtor === Uint8Array) { + return new ArrayBufferViewCtor(value.buffer, value.byteOffset, value.byteLength); + } + return value; + } + if (!value) { + return new ArrayBufferViewCtor(0); + } + if (typeof value === "string") { + value = encodeUtf8(value); + } + if (value instanceof ArrayBuffer) { + return new ArrayBufferViewCtor(value); + } + if (value instanceof SharedArrayBuf) { + return new ArrayBufferViewCtor(value); + } + if (isFlatbuffersByteBuffer(value)) { + return toArrayBufferView(ArrayBufferViewCtor, value.bytes()); + } + return !ArrayBuffer.isView(value) ? ArrayBufferViewCtor.from(value) : value.byteLength <= 0 ? new ArrayBufferViewCtor(0) : new ArrayBufferViewCtor(value.buffer, value.byteOffset, value.byteLength / ArrayBufferViewCtor.BYTES_PER_ELEMENT); +} +function* toArrayBufferViewIterator(ArrayCtor, source) { + const wrap = function* (x) { + yield x; + }; + const buffers = typeof source === "string" ? wrap(source) : ArrayBuffer.isView(source) ? wrap(source) : source instanceof ArrayBuffer ? wrap(source) : source instanceof SharedArrayBuf ? wrap(source) : !isIterable(source) ? wrap(source) : source; + yield* pump((function* (it) { + let r = null; + do { + r = it.next(yield toArrayBufferView(ArrayCtor, r)); + } while (!r.done); + })(buffers[Symbol.iterator]())); + return new ArrayCtor(); +} +function toArrayBufferViewAsyncIterator(ArrayCtor, source) { + return __asyncGenerator(this, arguments, function* toArrayBufferViewAsyncIterator_1() { + if (isPromise(source)) { + return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(toArrayBufferViewAsyncIterator(ArrayCtor, yield __await(source)))))); + } + const wrap = function(x) { + return __asyncGenerator(this, arguments, function* () { + yield yield __await(yield __await(x)); + }); }; - exports2.BlobGetAccountInfoExceptionHeaders = { - serializedName: "Blob_getAccountInfoExceptionHeaders", - type: { - name: "Composite", - className: "BlobGetAccountInfoExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + const emit = function(source2) { + return __asyncGenerator(this, arguments, function* () { + yield __await(yield* __asyncDelegator(__asyncValues(pump((function* (it) { + let r = null; + do { + r = it.next(yield r === null || r === void 0 ? void 0 : r.value); + } while (!r.done); + })(source2[Symbol.iterator]()))))); + }); + }; + const buffers = typeof source === "string" ? wrap(source) : ArrayBuffer.isView(source) ? wrap(source) : source instanceof ArrayBuffer ? wrap(source) : source instanceof SharedArrayBuf ? wrap(source) : isIterable(source) ? emit(source) : !isAsyncIterable(source) ? wrap(source) : source; + yield __await( + // otherwise if AsyncIterable, use it + yield* __asyncDelegator(__asyncValues(pump((function(it) { + return __asyncGenerator(this, arguments, function* () { + let r = null; + do { + r = yield __await(it.next(yield yield __await(toArrayBufferView(ArrayCtor, r)))); + } while (!r.done); + }); + })(buffers[Symbol.asyncIterator]())))) + ); + return yield __await(new ArrayCtor()); + }); +} +function rebaseValueOffsets(offset, length, valueOffsets) { + if (offset !== 0) { + valueOffsets = valueOffsets.slice(0, length); + const delta = typeof valueOffsets[0] === "bigint" ? BigInt(offset) : offset; + for (let i = -1, n = valueOffsets.length; ++i < n; ) { + valueOffsets[i] += delta; + } + } + return valueOffsets.subarray(0, length); +} +function compareArrayLike(a, b) { + let i = 0; + const n = a.length; + if (n !== b.length) { + return false; + } + if (n > 0) { + do { + if (a[i] !== b[i]) { + return false; + } + } while (++i < n); + } + return true; +} +var SharedArrayBuf, toInt8Array, toInt16Array, toInt32Array, toBigInt64Array, toUint8Array, toUint16Array, toUint32Array, toBigUint64Array, toFloat32Array, toFloat64Array, toUint8ClampedArray, pump, toInt8ArrayIterator, toInt16ArrayIterator, toInt32ArrayIterator, toUint8ArrayIterator, toUint16ArrayIterator, toUint32ArrayIterator, toFloat32ArrayIterator, toFloat64ArrayIterator, toUint8ClampedArrayIterator, toInt8ArrayAsyncIterator, toInt16ArrayAsyncIterator, toInt32ArrayAsyncIterator, toUint8ArrayAsyncIterator, toUint16ArrayAsyncIterator, toUint32ArrayAsyncIterator, toFloat32ArrayAsyncIterator, toFloat64ArrayAsyncIterator, toUint8ClampedArrayAsyncIterator; +var init_buffer = __esm({ + "node_modules/apache-arrow/util/buffer.mjs"() { + init_tslib_es6(); + init_utf8(); + init_compat(); + SharedArrayBuf = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : ArrayBuffer; + toInt8Array = (input) => toArrayBufferView(Int8Array, input); + toInt16Array = (input) => toArrayBufferView(Int16Array, input); + toInt32Array = (input) => toArrayBufferView(Int32Array, input); + toBigInt64Array = (input) => toArrayBufferView(BigInt64Array, input); + toUint8Array = (input) => toArrayBufferView(Uint8Array, input); + toUint16Array = (input) => toArrayBufferView(Uint16Array, input); + toUint32Array = (input) => toArrayBufferView(Uint32Array, input); + toBigUint64Array = (input) => toArrayBufferView(BigUint64Array, input); + toFloat32Array = (input) => toArrayBufferView(Float32Array, input); + toFloat64Array = (input) => toArrayBufferView(Float64Array, input); + toUint8ClampedArray = (input) => toArrayBufferView(Uint8ClampedArray, input); + pump = (iterator2) => { + iterator2.next(); + return iterator2; + }; + toInt8ArrayIterator = (input) => toArrayBufferViewIterator(Int8Array, input); + toInt16ArrayIterator = (input) => toArrayBufferViewIterator(Int16Array, input); + toInt32ArrayIterator = (input) => toArrayBufferViewIterator(Int32Array, input); + toUint8ArrayIterator = (input) => toArrayBufferViewIterator(Uint8Array, input); + toUint16ArrayIterator = (input) => toArrayBufferViewIterator(Uint16Array, input); + toUint32ArrayIterator = (input) => toArrayBufferViewIterator(Uint32Array, input); + toFloat32ArrayIterator = (input) => toArrayBufferViewIterator(Float32Array, input); + toFloat64ArrayIterator = (input) => toArrayBufferViewIterator(Float64Array, input); + toUint8ClampedArrayIterator = (input) => toArrayBufferViewIterator(Uint8ClampedArray, input); + toInt8ArrayAsyncIterator = (input) => toArrayBufferViewAsyncIterator(Int8Array, input); + toInt16ArrayAsyncIterator = (input) => toArrayBufferViewAsyncIterator(Int16Array, input); + toInt32ArrayAsyncIterator = (input) => toArrayBufferViewAsyncIterator(Int32Array, input); + toUint8ArrayAsyncIterator = (input) => toArrayBufferViewAsyncIterator(Uint8Array, input); + toUint16ArrayAsyncIterator = (input) => toArrayBufferViewAsyncIterator(Uint16Array, input); + toUint32ArrayAsyncIterator = (input) => toArrayBufferViewAsyncIterator(Uint32Array, input); + toFloat32ArrayAsyncIterator = (input) => toArrayBufferViewAsyncIterator(Float32Array, input); + toFloat64ArrayAsyncIterator = (input) => toArrayBufferViewAsyncIterator(Float64Array, input); + toUint8ClampedArrayAsyncIterator = (input) => toArrayBufferViewAsyncIterator(Uint8ClampedArray, input); + } +}); + +// node_modules/apache-arrow/io/adapters.mjs +function* fromIterable(source) { + let done, threw = false; + let buffers = [], buffer; + let cmd, size, bufferLength = 0; + function byteRange() { + if (cmd === "peek") { + return joinUint8Arrays(buffers, size)[0]; + } + [buffer, buffers, bufferLength] = joinUint8Arrays(buffers, size); + return buffer; + } + ({ cmd, size } = (yield /* @__PURE__ */ (() => null)()) || { cmd: "read", size: 0 }); + const it = toUint8ArrayIterator(source)[Symbol.iterator](); + try { + do { + ({ done, value: buffer } = Number.isNaN(size - bufferLength) ? it.next() : it.next(size - bufferLength)); + if (!done && buffer.byteLength > 0) { + buffers.push(buffer); + bufferLength += buffer.byteLength; + } + if (done || size <= bufferLength) { + do { + ({ cmd, size } = yield byteRange()); + } while (size < bufferLength); + } + } while (!done); + } catch (e) { + threw = true; + typeof it.throw === "function" && it.throw(e); + } finally { + threw === false && typeof it.return === "function" && it.return(null); + } + return null; +} +function fromAsyncIterable(source) { + return __asyncGenerator(this, arguments, function* fromAsyncIterable_1() { + let done, threw = false; + let buffers = [], buffer; + let cmd, size, bufferLength = 0; + function byteRange() { + if (cmd === "peek") { + return joinUint8Arrays(buffers, size)[0]; + } + [buffer, buffers, bufferLength] = joinUint8Arrays(buffers, size); + return buffer; + } + ({ cmd, size } = (yield yield __await(/* @__PURE__ */ (() => null)())) || { cmd: "read", size: 0 }); + const it = toUint8ArrayAsyncIterator(source)[Symbol.asyncIterator](); + try { + do { + ({ done, value: buffer } = Number.isNaN(size - bufferLength) ? yield __await(it.next()) : yield __await(it.next(size - bufferLength))); + if (!done && buffer.byteLength > 0) { + buffers.push(buffer); + bufferLength += buffer.byteLength; + } + if (done || size <= bufferLength) { + do { + ({ cmd, size } = yield yield __await(byteRange())); + } while (size < bufferLength); } + } while (!done); + } catch (e) { + threw = true; + typeof it.throw === "function" && (yield __await(it.throw(e))); + } finally { + threw === false && typeof it.return === "function" && (yield __await(it.return(new Uint8Array(0)))); + } + return yield __await(null); + }); +} +function fromDOMStream(source) { + return __asyncGenerator(this, arguments, function* fromDOMStream_1() { + let done = false, threw = false; + let buffers = [], buffer; + let cmd, size, bufferLength = 0; + function byteRange() { + if (cmd === "peek") { + return joinUint8Arrays(buffers, size)[0]; } - }; - exports2.BlobQueryHeaders = { - serializedName: "Blob_queryHeaders", - type: { - name: "Composite", - className: "BlobQueryHeaders", - modelProperties: { - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - metadata: { - serializedName: "x-ms-meta", - headerCollectionPrefix: "x-ms-meta-", - xmlName: "x-ms-meta", - type: { - name: "Dictionary", - value: { type: { name: "String" } } - } - }, - contentLength: { - serializedName: "content-length", - xmlName: "content-length", - type: { - name: "Number" - } - }, - contentType: { - serializedName: "content-type", - xmlName: "content-type", - type: { - name: "String" - } - }, - contentRange: { - serializedName: "content-range", - xmlName: "content-range", - type: { - name: "String" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" - } - }, - contentEncoding: { - serializedName: "content-encoding", - xmlName: "content-encoding", - type: { - name: "String" - } - }, - cacheControl: { - serializedName: "cache-control", - xmlName: "cache-control", - type: { - name: "String" - } - }, - contentDisposition: { - serializedName: "content-disposition", - xmlName: "content-disposition", - type: { - name: "String" - } - }, - contentLanguage: { - serializedName: "content-language", - xmlName: "content-language", - type: { - name: "String" - } - }, - blobSequenceNumber: { - serializedName: "x-ms-blob-sequence-number", - xmlName: "x-ms-blob-sequence-number", - type: { - name: "Number" - } - }, - blobType: { - serializedName: "x-ms-blob-type", - xmlName: "x-ms-blob-type", - type: { - name: "Enum", - allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"] - } - }, - copyCompletionTime: { - serializedName: "x-ms-copy-completion-time", - xmlName: "x-ms-copy-completion-time", - type: { - name: "DateTimeRfc1123" - } - }, - copyStatusDescription: { - serializedName: "x-ms-copy-status-description", - xmlName: "x-ms-copy-status-description", - type: { - name: "String" - } - }, - copyId: { - serializedName: "x-ms-copy-id", - xmlName: "x-ms-copy-id", - type: { - name: "String" - } - }, - copyProgress: { - serializedName: "x-ms-copy-progress", - xmlName: "x-ms-copy-progress", - type: { - name: "String" - } - }, - copySource: { - serializedName: "x-ms-copy-source", - xmlName: "x-ms-copy-source", - type: { - name: "String" - } - }, - copyStatus: { - serializedName: "x-ms-copy-status", - xmlName: "x-ms-copy-status", - type: { - name: "Enum", - allowedValues: ["pending", "success", "aborted", "failed"] - } - }, - leaseDuration: { - serializedName: "x-ms-lease-duration", - xmlName: "x-ms-lease-duration", - type: { - name: "Enum", - allowedValues: ["infinite", "fixed"] - } - }, - leaseState: { - serializedName: "x-ms-lease-state", - xmlName: "x-ms-lease-state", - type: { - name: "Enum", - allowedValues: [ - "available", - "leased", - "expired", - "breaking", - "broken" - ] - } - }, - leaseStatus: { - serializedName: "x-ms-lease-status", - xmlName: "x-ms-lease-status", - type: { - name: "Enum", - allowedValues: ["locked", "unlocked"] - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - acceptRanges: { - serializedName: "accept-ranges", - xmlName: "accept-ranges", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - blobCommittedBlockCount: { - serializedName: "x-ms-blob-committed-block-count", - xmlName: "x-ms-blob-committed-block-count", - type: { - name: "Number" - } - }, - isServerEncrypted: { - serializedName: "x-ms-server-encrypted", - xmlName: "x-ms-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, - blobContentMD5: { - serializedName: "x-ms-blob-content-md5", - xmlName: "x-ms-blob-content-md5", - type: { - name: "ByteArray" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - }, - contentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", - type: { - name: "ByteArray" + [buffer, buffers, bufferLength] = joinUint8Arrays(buffers, size); + return buffer; + } + ({ cmd, size } = (yield yield __await(/* @__PURE__ */ (() => null)())) || { cmd: "read", size: 0 }); + const it = new AdaptiveByteReader(source); + try { + do { + ({ done, value: buffer } = Number.isNaN(size - bufferLength) ? yield __await(it["read"]()) : yield __await(it["read"](size - bufferLength))); + if (!done && buffer.byteLength > 0) { + buffers.push(toUint8Array(buffer)); + bufferLength += buffer.byteLength; + } + if (done || size <= bufferLength) { + do { + ({ cmd, size } = yield yield __await(byteRange())); + } while (size < bufferLength); + } + } while (!done); + } catch (e) { + threw = true; + yield __await(it["cancel"](e)); + } finally { + threw === false ? yield __await(it["cancel"]()) : source["locked"] && it.releaseLock(); + } + return yield __await(null); + }); +} +function fromNodeStream(stream2) { + return __asyncGenerator(this, arguments, function* fromNodeStream_1() { + const events = []; + let event = "error"; + let done = false, err = null; + let cmd, size, bufferLength = 0; + let buffers = [], buffer; + function byteRange() { + if (cmd === "peek") { + return joinUint8Arrays(buffers, size)[0]; + } + [buffer, buffers, bufferLength] = joinUint8Arrays(buffers, size); + return buffer; + } + ({ cmd, size } = (yield yield __await(/* @__PURE__ */ (() => null)())) || { cmd: "read", size: 0 }); + if (stream2["isTTY"]) { + yield yield __await(new Uint8Array(0)); + return yield __await(null); + } + try { + events[0] = onEvent(stream2, "end"); + events[1] = onEvent(stream2, "error"); + do { + events[2] = onEvent(stream2, "readable"); + [event, err] = yield __await(Promise.race(events.map((x) => x[2]))); + if (event === "error") { + break; + } + if (!(done = event === "end")) { + if (!Number.isFinite(size - bufferLength)) { + buffer = toUint8Array(stream2["read"]()); + } else { + buffer = toUint8Array(stream2["read"](size - bufferLength)); + if (buffer.byteLength < size - bufferLength) { + buffer = toUint8Array(stream2["read"]()); } } + if (buffer.byteLength > 0) { + buffers.push(buffer); + bufferLength += buffer.byteLength; + } + } + if (done || size <= bufferLength) { + do { + ({ cmd, size } = yield yield __await(byteRange())); + } while (size < bufferLength); + } + } while (!done); + } finally { + yield __await(cleanup(events, event === "error" ? err : null)); + } + return yield __await(null); + function cleanup(events2, err2) { + buffer = buffers = null; + return new Promise((resolve15, reject) => { + for (const [evt, fn] of events2) { + stream2["off"](evt, fn); + } + try { + const destroy = stream2["destroy"]; + destroy && destroy.call(stream2, err2); + err2 = void 0; + } catch (e) { + err2 = e || err2; + } finally { + err2 != null ? reject(err2) : resolve15(); } + }); + } + }); +} +var adapters_default, pump2, AdaptiveByteReader, onEvent; +var init_adapters = __esm({ + "node_modules/apache-arrow/io/adapters.mjs"() { + init_tslib_es6(); + init_buffer(); + adapters_default = { + fromIterable(source) { + return pump2(fromIterable(source)); + }, + fromAsyncIterable(source) { + return pump2(fromAsyncIterable(source)); + }, + fromDOMStream(source) { + return pump2(fromDOMStream(source)); + }, + fromNodeStream(stream2) { + return pump2(fromNodeStream(stream2)); + }, + // @ts-ignore + toDOMStream(source, options) { + throw new Error(`"toDOMStream" not available in this environment`); + }, + // @ts-ignore + toNodeStream(source, options) { + throw new Error(`"toNodeStream" not available in this environment`); } }; - exports2.BlobQueryExceptionHeaders = { - serializedName: "Blob_queryExceptionHeaders", - type: { - name: "Composite", - className: "BlobQueryExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + pump2 = (iterator2) => { + iterator2.next(); + return iterator2; + }; + AdaptiveByteReader = class { + constructor(source) { + this.source = source; + this.reader = null; + this.reader = this.source["getReader"](); + this.reader["closed"].catch(() => { + }); + } + get closed() { + return this.reader ? this.reader["closed"].catch(() => { + }) : Promise.resolve(); + } + releaseLock() { + if (this.reader) { + this.reader.releaseLock(); } + this.reader = null; } - }; - exports2.BlobGetTagsHeaders = { - serializedName: "Blob_getTagsHeaders", - type: { - name: "Composite", - className: "BlobGetTagsHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } + cancel(reason) { + return __awaiter(this, void 0, void 0, function* () { + const { reader, source } = this; + reader && (yield reader["cancel"](reason).catch(() => { + })); + source && (source["locked"] && this.releaseLock()); + }); + } + read(size) { + return __awaiter(this, void 0, void 0, function* () { + if (size === 0) { + return { done: this.reader == null, value: new Uint8Array(0) }; } + const result = yield this.reader.read(); + !result.done && (result.value = toUint8Array(result)); + return result; + }); + } + }; + onEvent = (stream2, event) => { + const handler2 = (_2) => resolve15([event, _2]); + let resolve15; + return [event, handler2, new Promise((r) => (resolve15 = r) && stream2["once"](event, handler2))]; + }; + } +}); + +// node_modules/apache-arrow/fb/metadata-version.mjs +var MetadataVersion; +var init_metadata_version = __esm({ + "node_modules/apache-arrow/fb/metadata-version.mjs"() { + (function(MetadataVersion2) { + MetadataVersion2[MetadataVersion2["V1"] = 0] = "V1"; + MetadataVersion2[MetadataVersion2["V2"] = 1] = "V2"; + MetadataVersion2[MetadataVersion2["V3"] = 2] = "V3"; + MetadataVersion2[MetadataVersion2["V4"] = 3] = "V4"; + MetadataVersion2[MetadataVersion2["V5"] = 4] = "V5"; + })(MetadataVersion || (MetadataVersion = {})); + } +}); + +// node_modules/apache-arrow/fb/union-mode.mjs +var UnionMode; +var init_union_mode = __esm({ + "node_modules/apache-arrow/fb/union-mode.mjs"() { + (function(UnionMode2) { + UnionMode2[UnionMode2["Sparse"] = 0] = "Sparse"; + UnionMode2[UnionMode2["Dense"] = 1] = "Dense"; + })(UnionMode || (UnionMode = {})); + } +}); + +// node_modules/apache-arrow/fb/precision.mjs +var Precision; +var init_precision = __esm({ + "node_modules/apache-arrow/fb/precision.mjs"() { + (function(Precision2) { + Precision2[Precision2["HALF"] = 0] = "HALF"; + Precision2[Precision2["SINGLE"] = 1] = "SINGLE"; + Precision2[Precision2["DOUBLE"] = 2] = "DOUBLE"; + })(Precision || (Precision = {})); + } +}); + +// node_modules/apache-arrow/fb/date-unit.mjs +var DateUnit; +var init_date_unit = __esm({ + "node_modules/apache-arrow/fb/date-unit.mjs"() { + (function(DateUnit2) { + DateUnit2[DateUnit2["DAY"] = 0] = "DAY"; + DateUnit2[DateUnit2["MILLISECOND"] = 1] = "MILLISECOND"; + })(DateUnit || (DateUnit = {})); + } +}); + +// node_modules/apache-arrow/fb/time-unit.mjs +var TimeUnit; +var init_time_unit = __esm({ + "node_modules/apache-arrow/fb/time-unit.mjs"() { + (function(TimeUnit2) { + TimeUnit2[TimeUnit2["SECOND"] = 0] = "SECOND"; + TimeUnit2[TimeUnit2["MILLISECOND"] = 1] = "MILLISECOND"; + TimeUnit2[TimeUnit2["MICROSECOND"] = 2] = "MICROSECOND"; + TimeUnit2[TimeUnit2["NANOSECOND"] = 3] = "NANOSECOND"; + })(TimeUnit || (TimeUnit = {})); + } +}); + +// node_modules/apache-arrow/fb/interval-unit.mjs +var IntervalUnit; +var init_interval_unit = __esm({ + "node_modules/apache-arrow/fb/interval-unit.mjs"() { + (function(IntervalUnit2) { + IntervalUnit2[IntervalUnit2["YEAR_MONTH"] = 0] = "YEAR_MONTH"; + IntervalUnit2[IntervalUnit2["DAY_TIME"] = 1] = "DAY_TIME"; + IntervalUnit2[IntervalUnit2["MONTH_DAY_NANO"] = 2] = "MONTH_DAY_NANO"; + })(IntervalUnit || (IntervalUnit = {})); + } +}); + +// node_modules/flatbuffers/js/constants.js +var require_constants12 = __commonJS({ + "node_modules/flatbuffers/js/constants.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SIZE_PREFIX_LENGTH = exports2.FILE_IDENTIFIER_LENGTH = exports2.SIZEOF_INT = exports2.SIZEOF_SHORT = void 0; + exports2.SIZEOF_SHORT = 2; + exports2.SIZEOF_INT = 4; + exports2.FILE_IDENTIFIER_LENGTH = 4; + exports2.SIZE_PREFIX_LENGTH = 4; + } +}); + +// node_modules/flatbuffers/js/utils.js +var require_utils6 = __commonJS({ + "node_modules/flatbuffers/js/utils.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isLittleEndian = exports2.float64 = exports2.float32 = exports2.int32 = void 0; + exports2.int32 = new Int32Array(2); + exports2.float32 = new Float32Array(exports2.int32.buffer); + exports2.float64 = new Float64Array(exports2.int32.buffer); + exports2.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1; + } +}); + +// node_modules/flatbuffers/js/encoding.js +var require_encoding2 = __commonJS({ + "node_modules/flatbuffers/js/encoding.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Encoding = void 0; + var Encoding; + (function(Encoding2) { + Encoding2[Encoding2["UTF8_BYTES"] = 1] = "UTF8_BYTES"; + Encoding2[Encoding2["UTF16_STRING"] = 2] = "UTF16_STRING"; + })(Encoding || (exports2.Encoding = Encoding = {})); + } +}); + +// node_modules/flatbuffers/js/byte-buffer.js +var require_byte_buffer = __commonJS({ + "node_modules/flatbuffers/js/byte-buffer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ByteBuffer = void 0; + var constants_js_1 = require_constants12(); + var encoding_js_1 = require_encoding2(); + var utils_js_1 = require_utils6(); + var ByteBuffer8 = class _ByteBuffer { + /** + * Create a new ByteBuffer with a given array of bytes (`Uint8Array`) + */ + constructor(bytes_) { + this.bytes_ = bytes_; + this.position_ = 0; + this.text_decoder_ = new TextDecoder(); + } + /** + * Create and allocate a new ByteBuffer with a given size. + */ + static allocate(byte_size) { + return new _ByteBuffer(new Uint8Array(byte_size)); + } + clear() { + this.position_ = 0; + } + /** + * Get the underlying `Uint8Array`. + */ + bytes() { + return this.bytes_; + } + /** + * Get the buffer's position. + */ + position() { + return this.position_; + } + /** + * Set the buffer's position. + */ + setPosition(position) { + this.position_ = position; + } + /** + * Get the buffer's capacity. + */ + capacity() { + return this.bytes_.length; + } + readInt8(offset) { + return this.readUint8(offset) << 24 >> 24; + } + readUint8(offset) { + return this.bytes_[offset]; + } + readInt16(offset) { + return this.readUint16(offset) << 16 >> 16; + } + readUint16(offset) { + return this.bytes_[offset] | this.bytes_[offset + 1] << 8; + } + readInt32(offset) { + return this.bytes_[offset] | this.bytes_[offset + 1] << 8 | this.bytes_[offset + 2] << 16 | this.bytes_[offset + 3] << 24; + } + readUint32(offset) { + return this.readInt32(offset) >>> 0; + } + readInt64(offset) { + return BigInt.asIntN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32))); + } + readUint64(offset) { + return BigInt.asUintN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32))); + } + readFloat32(offset) { + utils_js_1.int32[0] = this.readInt32(offset); + return utils_js_1.float32[0]; + } + readFloat64(offset) { + utils_js_1.int32[utils_js_1.isLittleEndian ? 0 : 1] = this.readInt32(offset); + utils_js_1.int32[utils_js_1.isLittleEndian ? 1 : 0] = this.readInt32(offset + 4); + return utils_js_1.float64[0]; + } + writeInt8(offset, value) { + this.bytes_[offset] = value; + } + writeUint8(offset, value) { + this.bytes_[offset] = value; + } + writeInt16(offset, value) { + this.bytes_[offset] = value; + this.bytes_[offset + 1] = value >> 8; + } + writeUint16(offset, value) { + this.bytes_[offset] = value; + this.bytes_[offset + 1] = value >> 8; + } + writeInt32(offset, value) { + this.bytes_[offset] = value; + this.bytes_[offset + 1] = value >> 8; + this.bytes_[offset + 2] = value >> 16; + this.bytes_[offset + 3] = value >> 24; + } + writeUint32(offset, value) { + this.bytes_[offset] = value; + this.bytes_[offset + 1] = value >> 8; + this.bytes_[offset + 2] = value >> 16; + this.bytes_[offset + 3] = value >> 24; + } + writeInt64(offset, value) { + this.writeInt32(offset, Number(BigInt.asIntN(32, value))); + this.writeInt32(offset + 4, Number(BigInt.asIntN(32, value >> BigInt(32)))); + } + writeUint64(offset, value) { + this.writeUint32(offset, Number(BigInt.asUintN(32, value))); + this.writeUint32(offset + 4, Number(BigInt.asUintN(32, value >> BigInt(32)))); + } + writeFloat32(offset, value) { + utils_js_1.float32[0] = value; + this.writeInt32(offset, utils_js_1.int32[0]); + } + writeFloat64(offset, value) { + utils_js_1.float64[0] = value; + this.writeInt32(offset, utils_js_1.int32[utils_js_1.isLittleEndian ? 0 : 1]); + this.writeInt32(offset + 4, utils_js_1.int32[utils_js_1.isLittleEndian ? 1 : 0]); + } + /** + * Return the file identifier. Behavior is undefined for FlatBuffers whose + * schema does not include a file_identifier (likely points at padding or the + * start of a the root vtable). + */ + getBufferIdentifier() { + if (this.bytes_.length < this.position_ + constants_js_1.SIZEOF_INT + constants_js_1.FILE_IDENTIFIER_LENGTH) { + throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier."); + } + let result = ""; + for (let i = 0; i < constants_js_1.FILE_IDENTIFIER_LENGTH; i++) { + result += String.fromCharCode(this.readInt8(this.position_ + constants_js_1.SIZEOF_INT + i)); + } + return result; + } + /** + * Look up a field in the vtable, return an offset into the object, or 0 if the + * field is not present. + */ + __offset(bb_pos, vtable_offset) { + const vtable = bb_pos - this.readInt32(bb_pos); + return vtable_offset < this.readInt16(vtable) ? this.readInt16(vtable + vtable_offset) : 0; + } + /** + * Initialize any Table-derived type to point to the union at the given offset. + */ + __union(t, offset) { + t.bb_pos = offset + this.readInt32(offset); + t.bb = this; + return t; + } + /** + * Create a JavaScript string from UTF-8 data stored inside the FlatBuffer. + * This allocates a new string and converts to wide chars upon each access. + * + * To avoid the conversion to string, pass Encoding.UTF8_BYTES as the + * "optionalEncoding" argument. This is useful for avoiding conversion when + * the data will just be packaged back up in another FlatBuffer later on. + * + * @param offset + * @param opt_encoding Defaults to UTF16_STRING + */ + __string(offset, opt_encoding) { + offset += this.readInt32(offset); + const length = this.readInt32(offset); + offset += constants_js_1.SIZEOF_INT; + const utf8bytes = this.bytes_.subarray(offset, offset + length); + if (opt_encoding === encoding_js_1.Encoding.UTF8_BYTES) + return utf8bytes; + else + return this.text_decoder_.decode(utf8bytes); + } + /** + * Handle unions that can contain string as its member, if a Table-derived type then initialize it, + * if a string then return a new one + * + * WARNING: strings are immutable in JS so we can't change the string that the user gave us, this + * makes the behaviour of __union_with_string different compared to __union + */ + __union_with_string(o, offset) { + if (typeof o === "string") { + return this.__string(offset); } + return this.__union(o, offset); } - }; - exports2.BlobGetTagsExceptionHeaders = { - serializedName: "Blob_getTagsExceptionHeaders", - type: { - name: "Composite", - className: "BlobGetTagsExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } + /** + * Retrieve the relative offset stored at "offset" + */ + __indirect(offset) { + return offset + this.readInt32(offset); + } + /** + * Get the start of data of a vector whose offset is stored at "offset" in this object. + */ + __vector(offset) { + return offset + this.readInt32(offset) + constants_js_1.SIZEOF_INT; + } + /** + * Get the length of a vector whose offset is stored at "offset" in this object. + */ + __vector_len(offset) { + return this.readInt32(offset + this.readInt32(offset)); + } + __has_identifier(ident) { + if (ident.length != constants_js_1.FILE_IDENTIFIER_LENGTH) { + throw new Error("FlatBuffers: file identifier must be length " + constants_js_1.FILE_IDENTIFIER_LENGTH); + } + for (let i = 0; i < constants_js_1.FILE_IDENTIFIER_LENGTH; i++) { + if (ident.charCodeAt(i) != this.readInt8(this.position() + constants_js_1.SIZEOF_INT + i)) { + return false; } } + return true; } - }; - exports2.BlobSetTagsHeaders = { - serializedName: "Blob_setTagsHeaders", - type: { - name: "Composite", - className: "BlobSetTagsHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } + /** + * A helper function for generating list for obj api + */ + createScalarList(listAccessor, listLength) { + const ret = []; + for (let i = 0; i < listLength; ++i) { + const val = listAccessor(i); + if (val !== null) { + ret.push(val); } } + return ret; } - }; - exports2.BlobSetTagsExceptionHeaders = { - serializedName: "Blob_setTagsExceptionHeaders", - type: { - name: "Composite", - className: "BlobSetTagsExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } + /** + * A helper function for generating list for obj api + * @param listAccessor function that accepts an index and return data at that index + * @param listLength listLength + * @param res result list + */ + createObjList(listAccessor, listLength) { + const ret = []; + for (let i = 0; i < listLength; ++i) { + const val = listAccessor(i); + if (val !== null) { + ret.push(val.unpack()); } } + return ret; } }; - exports2.PageBlobCreateHeaders = { - serializedName: "PageBlob_createHeaders", - type: { - name: "Composite", - className: "PageBlobCreateHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - versionId: { - serializedName: "x-ms-version-id", - xmlName: "x-ms-version-id", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - xmlName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + exports2.ByteBuffer = ByteBuffer8; + } +}); + +// node_modules/flatbuffers/js/builder.js +var require_builder = __commonJS({ + "node_modules/flatbuffers/js/builder.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Builder = void 0; + var byte_buffer_js_1 = require_byte_buffer(); + var constants_js_1 = require_constants12(); + var Builder6 = class _Builder { + /** + * Create a FlatBufferBuilder. + */ + constructor(opt_initial_size) { + this.minalign = 1; + this.vtable = null; + this.vtable_in_use = 0; + this.isNested = false; + this.object_start = 0; + this.vtables = []; + this.vector_num_elems = 0; + this.force_defaults = false; + this.string_maps = null; + this.text_encoder = new TextEncoder(); + let initial_size; + if (!opt_initial_size) { + initial_size = 1024; + } else { + initial_size = opt_initial_size; } + this.bb = byte_buffer_js_1.ByteBuffer.allocate(initial_size); + this.space = initial_size; } - }; - exports2.PageBlobCreateExceptionHeaders = { - serializedName: "PageBlob_createExceptionHeaders", - type: { - name: "Composite", - className: "PageBlobCreateExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + clear() { + this.bb.clear(); + this.space = this.bb.capacity(); + this.minalign = 1; + this.vtable = null; + this.vtable_in_use = 0; + this.isNested = false; + this.object_start = 0; + this.vtables = []; + this.vector_num_elems = 0; + this.force_defaults = false; + this.string_maps = null; + } + /** + * In order to save space, fields that are set to their default value + * don't get serialized into the buffer. Forcing defaults provides a + * way to manually disable this optimization. + * + * @param forceDefaults true always serializes default values + */ + forceDefaults(forceDefaults) { + this.force_defaults = forceDefaults; + } + /** + * Get the ByteBuffer representing the FlatBuffer. Only call this after you've + * called finish(). The actual data starts at the ByteBuffer's current position, + * not necessarily at 0. + */ + dataBuffer() { + return this.bb; + } + /** + * Get the bytes representing the FlatBuffer. Only call this after you've + * called finish(). + */ + asUint8Array() { + return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset()); + } + /** + * Prepare to write an element of `size` after `additional_bytes` have been + * written, e.g. if you write a string, you need to align such the int length + * field is aligned to 4 bytes, and the string data follows it directly. If all + * you need to do is alignment, `additional_bytes` will be 0. + * + * @param size This is the of the new element to write + * @param additional_bytes The padding size + */ + prep(size, additional_bytes) { + if (size > this.minalign) { + this.minalign = size; } + const align_size = ~(this.bb.capacity() - this.space + additional_bytes) + 1 & size - 1; + while (this.space < align_size + size + additional_bytes) { + const old_buf_size = this.bb.capacity(); + this.bb = _Builder.growByteBuffer(this.bb); + this.space += this.bb.capacity() - old_buf_size; + } + this.pad(align_size); } - }; - exports2.PageBlobUploadPagesHeaders = { - serializedName: "PageBlob_uploadPagesHeaders", - type: { - name: "Composite", - className: "PageBlobUploadPagesHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" - } - }, - xMsContentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", - type: { - name: "ByteArray" - } - }, - blobSequenceNumber: { - serializedName: "x-ms-blob-sequence-number", - xmlName: "x-ms-blob-sequence-number", - type: { - name: "Number" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - xmlName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + pad(byte_size) { + for (let i = 0; i < byte_size; i++) { + this.bb.writeInt8(--this.space, 0); } } - }; - exports2.PageBlobUploadPagesExceptionHeaders = { - serializedName: "PageBlob_uploadPagesExceptionHeaders", - type: { - name: "Composite", - className: "PageBlobUploadPagesExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" + writeInt8(value) { + this.bb.writeInt8(this.space -= 1, value); + } + writeInt16(value) { + this.bb.writeInt16(this.space -= 2, value); + } + writeInt32(value) { + this.bb.writeInt32(this.space -= 4, value); + } + writeInt64(value) { + this.bb.writeInt64(this.space -= 8, value); + } + writeFloat32(value) { + this.bb.writeFloat32(this.space -= 4, value); + } + writeFloat64(value) { + this.bb.writeFloat64(this.space -= 8, value); + } + /** + * Add an `int8` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param value The `int8` to add the buffer. + */ + addInt8(value) { + this.prep(1, 0); + this.writeInt8(value); + } + /** + * Add an `int16` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param value The `int16` to add the buffer. + */ + addInt16(value) { + this.prep(2, 0); + this.writeInt16(value); + } + /** + * Add an `int32` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param value The `int32` to add the buffer. + */ + addInt32(value) { + this.prep(4, 0); + this.writeInt32(value); + } + /** + * Add an `int64` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param value The `int64` to add the buffer. + */ + addInt64(value) { + this.prep(8, 0); + this.writeInt64(value); + } + /** + * Add a `float32` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param value The `float32` to add the buffer. + */ + addFloat32(value) { + this.prep(4, 0); + this.writeFloat32(value); + } + /** + * Add a `float64` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param value The `float64` to add the buffer. + */ + addFloat64(value) { + this.prep(8, 0); + this.writeFloat64(value); + } + addFieldInt8(voffset, value, defaultValue) { + if (this.force_defaults || value != defaultValue) { + this.addInt8(value); + this.slot(voffset); + } + } + addFieldInt16(voffset, value, defaultValue) { + if (this.force_defaults || value != defaultValue) { + this.addInt16(value); + this.slot(voffset); + } + } + addFieldInt32(voffset, value, defaultValue) { + if (this.force_defaults || value != defaultValue) { + this.addInt32(value); + this.slot(voffset); + } + } + addFieldInt64(voffset, value, defaultValue) { + if (this.force_defaults || value !== defaultValue) { + this.addInt64(value); + this.slot(voffset); + } + } + addFieldFloat32(voffset, value, defaultValue) { + if (this.force_defaults || value != defaultValue) { + this.addFloat32(value); + this.slot(voffset); + } + } + addFieldFloat64(voffset, value, defaultValue) { + if (this.force_defaults || value != defaultValue) { + this.addFloat64(value); + this.slot(voffset); + } + } + addFieldOffset(voffset, value, defaultValue) { + if (this.force_defaults || value != defaultValue) { + this.addOffset(value); + this.slot(voffset); + } + } + /** + * Structs are stored inline, so nothing additional is being added. `d` is always 0. + */ + addFieldStruct(voffset, value, defaultValue) { + if (value != defaultValue) { + this.nested(value); + this.slot(voffset); + } + } + /** + * Structures are always stored inline, they need to be created right + * where they're used. You'll get this assertion failure if you + * created it elsewhere. + */ + nested(obj) { + if (obj != this.offset()) { + throw new TypeError("FlatBuffers: struct must be serialized inline."); + } + } + /** + * Should not be creating any other object, string or vector + * while an object is being constructed + */ + notNested() { + if (this.isNested) { + throw new TypeError("FlatBuffers: object serialization must not be nested."); + } + } + /** + * Set the current vtable at `voffset` to the current location in the buffer. + */ + slot(voffset) { + if (this.vtable !== null) + this.vtable[voffset] = this.offset(); + } + /** + * @returns Offset relative to the end of the buffer. + */ + offset() { + return this.bb.capacity() - this.space; + } + /** + * Doubles the size of the backing ByteBuffer and copies the old data towards + * the end of the new buffer (since we build the buffer backwards). + * + * @param bb The current buffer with the existing data + * @returns A new byte buffer with the old data copied + * to it. The data is located at the end of the buffer. + * + * uint8Array.set() formally takes {Array|ArrayBufferView}, so to pass + * it a uint8Array we need to suppress the type check: + * @suppress {checkTypes} + */ + static growByteBuffer(bb) { + const old_buf_size = bb.capacity(); + if (old_buf_size & 3221225472) { + throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes."); + } + const new_buf_size = old_buf_size << 1; + const nbb = byte_buffer_js_1.ByteBuffer.allocate(new_buf_size); + nbb.setPosition(new_buf_size - old_buf_size); + nbb.bytes().set(bb.bytes(), new_buf_size - old_buf_size); + return nbb; + } + /** + * Adds on offset, relative to where it will be written. + * + * @param offset The offset to add. + */ + addOffset(offset) { + this.prep(constants_js_1.SIZEOF_INT, 0); + this.writeInt32(this.offset() - offset + constants_js_1.SIZEOF_INT); + } + /** + * Start encoding a new object in the buffer. Users will not usually need to + * call this directly. The FlatBuffers compiler will generate helper methods + * that call this method internally. + */ + startObject(numfields) { + this.notNested(); + if (this.vtable == null) { + this.vtable = []; + } + this.vtable_in_use = numfields; + for (let i = 0; i < numfields; i++) { + this.vtable[i] = 0; + } + this.isNested = true; + this.object_start = this.offset(); + } + /** + * Finish off writing the object that is under construction. + * + * @returns The offset to the object inside `dataBuffer` + */ + endObject() { + if (this.vtable == null || !this.isNested) { + throw new Error("FlatBuffers: endObject called without startObject"); + } + this.addInt32(0); + const vtableloc = this.offset(); + let i = this.vtable_in_use - 1; + for (; i >= 0 && this.vtable[i] == 0; i--) { + } + const trimmed_size = i + 1; + for (; i >= 0; i--) { + this.addInt16(this.vtable[i] != 0 ? vtableloc - this.vtable[i] : 0); + } + const standard_fields = 2; + this.addInt16(vtableloc - this.object_start); + const len = (trimmed_size + standard_fields) * constants_js_1.SIZEOF_SHORT; + this.addInt16(len); + let existing_vtable = 0; + const vt1 = this.space; + outer_loop: for (i = 0; i < this.vtables.length; i++) { + const vt2 = this.bb.capacity() - this.vtables[i]; + if (len == this.bb.readInt16(vt2)) { + for (let j = constants_js_1.SIZEOF_SHORT; j < len; j += constants_js_1.SIZEOF_SHORT) { + if (this.bb.readInt16(vt1 + j) != this.bb.readInt16(vt2 + j)) { + continue outer_loop; + } } + existing_vtable = this.vtables[i]; + break; } } + if (existing_vtable) { + this.space = this.bb.capacity() - vtableloc; + this.bb.writeInt32(this.space, existing_vtable - vtableloc); + } else { + this.vtables.push(this.offset()); + this.bb.writeInt32(this.bb.capacity() - vtableloc, this.offset() - vtableloc); + } + this.isNested = false; + return vtableloc; } - }; - exports2.PageBlobClearPagesHeaders = { - serializedName: "PageBlob_clearPagesHeaders", - type: { - name: "Composite", - className: "PageBlobClearPagesHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" - } - }, - xMsContentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", - type: { - name: "ByteArray" - } - }, - blobSequenceNumber: { - serializedName: "x-ms-blob-sequence-number", - xmlName: "x-ms-blob-sequence-number", - type: { - name: "Number" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } + /** + * Finalize a buffer, poiting to the given `root_table`. + */ + finish(root_table, opt_file_identifier, opt_size_prefix) { + const size_prefix = opt_size_prefix ? constants_js_1.SIZE_PREFIX_LENGTH : 0; + if (opt_file_identifier) { + const file_identifier = opt_file_identifier; + this.prep(this.minalign, constants_js_1.SIZEOF_INT + constants_js_1.FILE_IDENTIFIER_LENGTH + size_prefix); + if (file_identifier.length != constants_js_1.FILE_IDENTIFIER_LENGTH) { + throw new TypeError("FlatBuffers: file identifier must be length " + constants_js_1.FILE_IDENTIFIER_LENGTH); + } + for (let i = constants_js_1.FILE_IDENTIFIER_LENGTH - 1; i >= 0; i--) { + this.writeInt8(file_identifier.charCodeAt(i)); } } + this.prep(this.minalign, constants_js_1.SIZEOF_INT + size_prefix); + this.addOffset(root_table); + if (size_prefix) { + this.addInt32(this.bb.capacity() - this.space); + } + this.bb.setPosition(this.space); } - }; - exports2.PageBlobClearPagesExceptionHeaders = { - serializedName: "PageBlob_clearPagesExceptionHeaders", - type: { - name: "Composite", - className: "PageBlobClearPagesExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } + /** + * Finalize a size prefixed buffer, pointing to the given `root_table`. + */ + finishSizePrefixed(root_table, opt_file_identifier) { + this.finish(root_table, opt_file_identifier, true); + } + /** + * This checks a required field has been set in a given table that has + * just been constructed. + */ + requiredField(table, field) { + const table_start = this.bb.capacity() - table; + const vtable_start = table_start - this.bb.readInt32(table_start); + const ok = field < this.bb.readInt16(vtable_start) && this.bb.readInt16(vtable_start + field) != 0; + if (!ok) { + throw new TypeError("FlatBuffers: field " + field + " must be set"); + } + } + /** + * Start a new array/vector of objects. Users usually will not call + * this directly. The FlatBuffers compiler will create a start/end + * method for vector types in generated code. + * + * @param elem_size The size of each element in the array + * @param num_elems The number of elements in the array + * @param alignment The alignment of the array + */ + startVector(elem_size, num_elems, alignment) { + this.notNested(); + this.vector_num_elems = num_elems; + this.prep(constants_js_1.SIZEOF_INT, elem_size * num_elems); + this.prep(alignment, elem_size * num_elems); + } + /** + * Finish off the creation of an array and all its elements. The array must be + * created with `startVector`. + * + * @returns The offset at which the newly created array + * starts. + */ + endVector() { + this.writeInt32(this.vector_num_elems); + return this.offset(); + } + /** + * Encode the string `s` in the buffer using UTF-8. If the string passed has + * already been seen, we return the offset of the already written string + * + * @param s The string to encode + * @return The offset in the buffer where the encoded string starts + */ + createSharedString(s) { + if (!s) { + return 0; + } + if (!this.string_maps) { + this.string_maps = /* @__PURE__ */ new Map(); + } + if (this.string_maps.has(s)) { + return this.string_maps.get(s); + } + const offset = this.createString(s); + this.string_maps.set(s, offset); + return offset; + } + /** + * Encode the string `s` in the buffer using UTF-8. If a Uint8Array is passed + * instead of a string, it is assumed to contain valid UTF-8 encoded data. + * + * @param s The string to encode + * @return The offset in the buffer where the encoded string starts + */ + createString(s) { + if (s === null || s === void 0) { + return 0; + } + let utf8; + if (s instanceof Uint8Array) { + utf8 = s; + } else { + utf8 = this.text_encoder.encode(s); + } + this.addInt8(0); + this.startVector(1, utf8.length, 1); + this.bb.setPosition(this.space -= utf8.length); + this.bb.bytes().set(utf8, this.space); + return this.endVector(); + } + /** + * Create a byte vector. + * + * @param v The bytes to add + * @returns The offset in the buffer where the byte vector starts + */ + createByteVector(v) { + if (v === null || v === void 0) { + return 0; + } + this.startVector(1, v.length, 1); + this.bb.setPosition(this.space -= v.length); + this.bb.bytes().set(v, this.space); + return this.endVector(); + } + /** + * A helper function to pack an object + * + * @returns offset of obj + */ + createObjectOffset(obj) { + if (obj === null) { + return 0; + } + if (typeof obj === "string") { + return this.createString(obj); + } else { + return obj.pack(this); + } + } + /** + * A helper function to pack a list of object + * + * @returns list of offsets of each non null object + */ + createObjectOffsetList(list) { + const ret = []; + for (let i = 0; i < list.length; ++i) { + const val = list[i]; + if (val !== null) { + ret.push(this.createObjectOffset(val)); + } else { + throw new TypeError("FlatBuffers: Argument for createObjectOffsetList cannot contain null."); } } + return ret; + } + createStructOffsetList(list, startFunc) { + startFunc(this, list.length); + this.createObjectOffsetList(list.slice().reverse()); + return this.endVector(); } }; - exports2.PageBlobUploadPagesFromURLHeaders = { - serializedName: "PageBlob_uploadPagesFromURLHeaders", - type: { - name: "Composite", - className: "PageBlobUploadPagesFromURLHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" - } - }, - xMsContentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", - type: { - name: "ByteArray" - } - }, - blobSequenceNumber: { - serializedName: "x-ms-blob-sequence-number", - xmlName: "x-ms-blob-sequence-number", - type: { - name: "Number" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - xmlName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + exports2.Builder = Builder6; + } +}); + +// node_modules/flatbuffers/js/flatbuffers.js +var require_flatbuffers = __commonJS({ + "node_modules/flatbuffers/js/flatbuffers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Encoding = exports2.ByteBuffer = exports2.Builder = exports2.isLittleEndian = exports2.int32 = exports2.float64 = exports2.float32 = exports2.SIZE_PREFIX_LENGTH = exports2.SIZEOF_SHORT = exports2.SIZEOF_INT = exports2.FILE_IDENTIFIER_LENGTH = void 0; + var constants_js_1 = require_constants12(); + Object.defineProperty(exports2, "FILE_IDENTIFIER_LENGTH", { enumerable: true, get: function() { + return constants_js_1.FILE_IDENTIFIER_LENGTH; + } }); + Object.defineProperty(exports2, "SIZEOF_INT", { enumerable: true, get: function() { + return constants_js_1.SIZEOF_INT; + } }); + Object.defineProperty(exports2, "SIZEOF_SHORT", { enumerable: true, get: function() { + return constants_js_1.SIZEOF_SHORT; + } }); + Object.defineProperty(exports2, "SIZE_PREFIX_LENGTH", { enumerable: true, get: function() { + return constants_js_1.SIZE_PREFIX_LENGTH; + } }); + var utils_js_1 = require_utils6(); + Object.defineProperty(exports2, "float32", { enumerable: true, get: function() { + return utils_js_1.float32; + } }); + Object.defineProperty(exports2, "float64", { enumerable: true, get: function() { + return utils_js_1.float64; + } }); + Object.defineProperty(exports2, "int32", { enumerable: true, get: function() { + return utils_js_1.int32; + } }); + Object.defineProperty(exports2, "isLittleEndian", { enumerable: true, get: function() { + return utils_js_1.isLittleEndian; + } }); + var builder_js_1 = require_builder(); + Object.defineProperty(exports2, "Builder", { enumerable: true, get: function() { + return builder_js_1.Builder; + } }); + var byte_buffer_js_1 = require_byte_buffer(); + Object.defineProperty(exports2, "ByteBuffer", { enumerable: true, get: function() { + return byte_buffer_js_1.ByteBuffer; + } }); + var encoding_js_1 = require_encoding2(); + Object.defineProperty(exports2, "Encoding", { enumerable: true, get: function() { + return encoding_js_1.Encoding; + } }); + } +}); + +// node_modules/apache-arrow/fb/body-compression-method.mjs +var BodyCompressionMethod; +var init_body_compression_method = __esm({ + "node_modules/apache-arrow/fb/body-compression-method.mjs"() { + (function(BodyCompressionMethod2) { + BodyCompressionMethod2[BodyCompressionMethod2["BUFFER"] = 0] = "BUFFER"; + })(BodyCompressionMethod || (BodyCompressionMethod = {})); + } +}); + +// node_modules/apache-arrow/fb/compression-type.mjs +var CompressionType; +var init_compression_type = __esm({ + "node_modules/apache-arrow/fb/compression-type.mjs"() { + (function(CompressionType2) { + CompressionType2[CompressionType2["LZ4_FRAME"] = 0] = "LZ4_FRAME"; + CompressionType2[CompressionType2["ZSTD"] = 1] = "ZSTD"; + })(CompressionType || (CompressionType = {})); + } +}); + +// node_modules/apache-arrow/fb/body-compression.mjs +var flatbuffers, BodyCompression; +var init_body_compression = __esm({ + "node_modules/apache-arrow/fb/body-compression.mjs"() { + flatbuffers = __toESM(require_flatbuffers(), 1); + init_body_compression_method(); + init_compression_type(); + BodyCompression = class _BodyCompression { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsBodyCompression(bb, obj) { + return (obj || new _BodyCompression()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsBodyCompression(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new _BodyCompression()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + /** + * Compressor library. + * For LZ4_FRAME, each compressed buffer must consist of a single frame. + */ + codec() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt8(this.bb_pos + offset) : CompressionType.LZ4_FRAME; + } + /** + * Indicates the way the record batch body was compressed + */ + method() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt8(this.bb_pos + offset) : BodyCompressionMethod.BUFFER; + } + static startBodyCompression(builder) { + builder.startObject(2); + } + static addCodec(builder, codec) { + builder.addFieldInt8(0, codec, CompressionType.LZ4_FRAME); + } + static addMethod(builder, method) { + builder.addFieldInt8(1, method, BodyCompressionMethod.BUFFER); + } + static endBodyCompression(builder) { + const offset = builder.endObject(); + return offset; + } + static createBodyCompression(builder, codec, method) { + _BodyCompression.startBodyCompression(builder); + _BodyCompression.addCodec(builder, codec); + _BodyCompression.addMethod(builder, method); + return _BodyCompression.endBodyCompression(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/buffer.mjs +var Buffer2; +var init_buffer2 = __esm({ + "node_modules/apache-arrow/fb/buffer.mjs"() { + Buffer2 = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + /** + * The relative offset into the shared memory page where the bytes for this + * buffer starts + */ + offset() { + return this.bb.readInt64(this.bb_pos); + } + /** + * The absolute length (in bytes) of the memory buffer. The memory is found + * from offset (inclusive) to offset + length (non-inclusive). When building + * messages using the encapsulated IPC message, padding bytes may be written + * after a buffer, but such padding bytes do not need to be accounted for in + * the size here. + */ + length() { + return this.bb.readInt64(this.bb_pos + 8); + } + static sizeOf() { + return 16; + } + static createBuffer(builder, offset, length) { + builder.prep(8, 16); + builder.writeInt64(BigInt(length !== null && length !== void 0 ? length : 0)); + builder.writeInt64(BigInt(offset !== null && offset !== void 0 ? offset : 0)); + return builder.offset(); + } + }; + } +}); + +// node_modules/apache-arrow/fb/field-node.mjs +var FieldNode; +var init_field_node = __esm({ + "node_modules/apache-arrow/fb/field-node.mjs"() { + FieldNode = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + /** + * The number of value slots in the Arrow array at this level of a nested + * tree + */ + length() { + return this.bb.readInt64(this.bb_pos); + } + /** + * The number of observed nulls. Fields with null_count == 0 may choose not + * to write their physical validity bitmap out as a materialized buffer, + * instead setting the length of the bitmap buffer to 0. + */ + nullCount() { + return this.bb.readInt64(this.bb_pos + 8); + } + static sizeOf() { + return 16; + } + static createFieldNode(builder, length, null_count) { + builder.prep(8, 16); + builder.writeInt64(BigInt(null_count !== null && null_count !== void 0 ? null_count : 0)); + builder.writeInt64(BigInt(length !== null && length !== void 0 ? length : 0)); + return builder.offset(); + } + }; + } +}); + +// node_modules/apache-arrow/fb/record-batch.mjs +var flatbuffers2, RecordBatch; +var init_record_batch = __esm({ + "node_modules/apache-arrow/fb/record-batch.mjs"() { + flatbuffers2 = __toESM(require_flatbuffers(), 1); + init_body_compression(); + init_buffer2(); + init_field_node(); + RecordBatch = class _RecordBatch { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsRecordBatch(bb, obj) { + return (obj || new _RecordBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsRecordBatch(bb, obj) { + bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH); + return (obj || new _RecordBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + /** + * number of records / rows. The arrays in the batch should all have this + * length + */ + length() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0"); + } + /** + * Nodes correspond to the pre-ordered flattened logical schema + */ + nodes(index2, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new FieldNode()).__init(this.bb.__vector(this.bb_pos + offset) + index2 * 16, this.bb) : null; + } + nodesLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + /** + * Buffers correspond to the pre-ordered flattened buffer tree + * + * The number of buffers appended to this list depends on the schema. For + * example, most primitive arrays will have 2 buffers, 1 for the validity + * bitmap and 1 for the values. For struct arrays, there will only be a + * single buffer for the validity (nulls) bitmap + */ + buffers(index2, obj) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? (obj || new Buffer2()).__init(this.bb.__vector(this.bb_pos + offset) + index2 * 16, this.bb) : null; + } + buffersLength() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + /** + * Optional compression of the message body + */ + compression(obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? (obj || new BodyCompression()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + /** + * Some types such as Utf8View are represented using a variable number of buffers. + * For each such Field in the pre-ordered flattened logical schema, there will be + * an entry in variadicBufferCounts to indicate the number of number of variadic + * buffers which belong to that Field in the current RecordBatch. + * + * For example, the schema + * col1: Struct + * col2: Utf8View + * contains two Fields with variadic buffers so variadicBufferCounts will have + * two entries, the first counting the variadic buffers of `col1.beta` and the + * second counting `col2`'s. + * + * This field may be omitted if and only if the schema contains no Fields with + * a variable number of buffers, such as BinaryView and Utf8View. + */ + variadicBufferCounts(index2) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index2 * 8) : BigInt(0); + } + variadicBufferCountsLength() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static startRecordBatch(builder) { + builder.startObject(5); + } + static addLength(builder, length) { + builder.addFieldInt64(0, length, BigInt("0")); + } + static addNodes(builder, nodesOffset) { + builder.addFieldOffset(1, nodesOffset, 0); + } + static startNodesVector(builder, numElems) { + builder.startVector(16, numElems, 8); + } + static addBuffers(builder, buffersOffset) { + builder.addFieldOffset(2, buffersOffset, 0); + } + static startBuffersVector(builder, numElems) { + builder.startVector(16, numElems, 8); + } + static addCompression(builder, compressionOffset) { + builder.addFieldOffset(3, compressionOffset, 0); + } + static addVariadicBufferCounts(builder, variadicBufferCountsOffset) { + builder.addFieldOffset(4, variadicBufferCountsOffset, 0); + } + static createVariadicBufferCountsVector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]); } + return builder.endVector(); + } + static startVariadicBufferCountsVector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static endRecordBatch(builder) { + const offset = builder.endObject(); + return offset; + } + }; + } +}); + +// node_modules/apache-arrow/fb/dictionary-batch.mjs +var flatbuffers3, DictionaryBatch; +var init_dictionary_batch = __esm({ + "node_modules/apache-arrow/fb/dictionary-batch.mjs"() { + flatbuffers3 = __toESM(require_flatbuffers(), 1); + init_record_batch(); + DictionaryBatch = class _DictionaryBatch { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsDictionaryBatch(bb, obj) { + return (obj || new _DictionaryBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsDictionaryBatch(bb, obj) { + bb.setPosition(bb.position() + flatbuffers3.SIZE_PREFIX_LENGTH); + return (obj || new _DictionaryBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + id() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0"); + } + data(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new RecordBatch()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + /** + * If isDelta is true the values in the dictionary are to be appended to a + * dictionary with the indicated id. If isDelta is false this dictionary + * should replace the existing dictionary. + */ + isDelta() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + static startDictionaryBatch(builder) { + builder.startObject(3); + } + static addId(builder, id) { + builder.addFieldInt64(0, id, BigInt("0")); + } + static addData(builder, dataOffset) { + builder.addFieldOffset(1, dataOffset, 0); + } + static addIsDelta(builder, isDelta) { + builder.addFieldInt8(2, +isDelta, 0); + } + static endDictionaryBatch(builder) { + const offset = builder.endObject(); + return offset; + } + }; + } +}); + +// node_modules/apache-arrow/fb/endianness.mjs +var Endianness; +var init_endianness = __esm({ + "node_modules/apache-arrow/fb/endianness.mjs"() { + (function(Endianness2) { + Endianness2[Endianness2["Little"] = 0] = "Little"; + Endianness2[Endianness2["Big"] = 1] = "Big"; + })(Endianness || (Endianness = {})); + } +}); + +// node_modules/apache-arrow/fb/dictionary-kind.mjs +var DictionaryKind; +var init_dictionary_kind = __esm({ + "node_modules/apache-arrow/fb/dictionary-kind.mjs"() { + (function(DictionaryKind2) { + DictionaryKind2[DictionaryKind2["DenseArray"] = 0] = "DenseArray"; + })(DictionaryKind || (DictionaryKind = {})); + } +}); + +// node_modules/apache-arrow/fb/int.mjs +var flatbuffers4, Int; +var init_int = __esm({ + "node_modules/apache-arrow/fb/int.mjs"() { + flatbuffers4 = __toESM(require_flatbuffers(), 1); + Int = class _Int { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsInt(bb, obj) { + return (obj || new _Int()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsInt(bb, obj) { + bb.setPosition(bb.position() + flatbuffers4.SIZE_PREFIX_LENGTH); + return (obj || new _Int()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + bitWidth() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + isSigned() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + static startInt(builder) { + builder.startObject(2); + } + static addBitWidth(builder, bitWidth) { + builder.addFieldInt32(0, bitWidth, 0); + } + static addIsSigned(builder, isSigned) { + builder.addFieldInt8(1, +isSigned, 0); + } + static endInt(builder) { + const offset = builder.endObject(); + return offset; + } + static createInt(builder, bitWidth, isSigned) { + _Int.startInt(builder); + _Int.addBitWidth(builder, bitWidth); + _Int.addIsSigned(builder, isSigned); + return _Int.endInt(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/dictionary-encoding.mjs +var flatbuffers5, DictionaryEncoding; +var init_dictionary_encoding = __esm({ + "node_modules/apache-arrow/fb/dictionary-encoding.mjs"() { + flatbuffers5 = __toESM(require_flatbuffers(), 1); + init_dictionary_kind(); + init_int(); + DictionaryEncoding = class _DictionaryEncoding { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsDictionaryEncoding(bb, obj) { + return (obj || new _DictionaryEncoding()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsDictionaryEncoding(bb, obj) { + bb.setPosition(bb.position() + flatbuffers5.SIZE_PREFIX_LENGTH); + return (obj || new _DictionaryEncoding()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + /** + * The known dictionary id in the application where this data is used. In + * the file or streaming formats, the dictionary ids are found in the + * DictionaryBatch messages + */ + id() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0"); + } + /** + * The dictionary indices are constrained to be non-negative integers. If + * this field is null, the indices must be signed int32. To maximize + * cross-language compatibility and performance, implementations are + * recommended to prefer signed integer types over unsigned integer types + * and to avoid uint64 indices unless they are required by an application. + */ + indexType(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Int()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + /** + * By default, dictionaries are not ordered, or the order does not have + * semantic meaning. In some statistical, applications, dictionary-encoding + * is used to represent ordered categorical data, and we provide a way to + * preserve that metadata here + */ + isOrdered() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + dictionaryKind() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readInt16(this.bb_pos + offset) : DictionaryKind.DenseArray; + } + static startDictionaryEncoding(builder) { + builder.startObject(4); + } + static addId(builder, id) { + builder.addFieldInt64(0, id, BigInt("0")); + } + static addIndexType(builder, indexTypeOffset) { + builder.addFieldOffset(1, indexTypeOffset, 0); + } + static addIsOrdered(builder, isOrdered) { + builder.addFieldInt8(2, +isOrdered, 0); + } + static addDictionaryKind(builder, dictionaryKind) { + builder.addFieldInt16(3, dictionaryKind, DictionaryKind.DenseArray); + } + static endDictionaryEncoding(builder) { + const offset = builder.endObject(); + return offset; + } + }; + } +}); + +// node_modules/apache-arrow/fb/key-value.mjs +var flatbuffers6, KeyValue; +var init_key_value = __esm({ + "node_modules/apache-arrow/fb/key-value.mjs"() { + flatbuffers6 = __toESM(require_flatbuffers(), 1); + KeyValue = class _KeyValue { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsKeyValue(bb, obj) { + return (obj || new _KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsKeyValue(bb, obj) { + bb.setPosition(bb.position() + flatbuffers6.SIZE_PREFIX_LENGTH); + return (obj || new _KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + key(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + value(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static startKeyValue(builder) { + builder.startObject(2); + } + static addKey(builder, keyOffset) { + builder.addFieldOffset(0, keyOffset, 0); + } + static addValue(builder, valueOffset) { + builder.addFieldOffset(1, valueOffset, 0); + } + static endKeyValue(builder) { + const offset = builder.endObject(); + return offset; + } + static createKeyValue(builder, keyOffset, valueOffset) { + _KeyValue.startKeyValue(builder); + _KeyValue.addKey(builder, keyOffset); + _KeyValue.addValue(builder, valueOffset); + return _KeyValue.endKeyValue(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/binary.mjs +var flatbuffers7, Binary; +var init_binary = __esm({ + "node_modules/apache-arrow/fb/binary.mjs"() { + flatbuffers7 = __toESM(require_flatbuffers(), 1); + Binary = class _Binary { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsBinary(bb, obj) { + return (obj || new _Binary()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsBinary(bb, obj) { + bb.setPosition(bb.position() + flatbuffers7.SIZE_PREFIX_LENGTH); + return (obj || new _Binary()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static startBinary(builder) { + builder.startObject(0); + } + static endBinary(builder) { + const offset = builder.endObject(); + return offset; + } + static createBinary(builder) { + _Binary.startBinary(builder); + return _Binary.endBinary(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/binary-view.mjs +var flatbuffers8, BinaryView; +var init_binary_view = __esm({ + "node_modules/apache-arrow/fb/binary-view.mjs"() { + flatbuffers8 = __toESM(require_flatbuffers(), 1); + BinaryView = class _BinaryView { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsBinaryView(bb, obj) { + return (obj || new _BinaryView()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsBinaryView(bb, obj) { + bb.setPosition(bb.position() + flatbuffers8.SIZE_PREFIX_LENGTH); + return (obj || new _BinaryView()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static startBinaryView(builder) { + builder.startObject(0); + } + static endBinaryView(builder) { + const offset = builder.endObject(); + return offset; + } + static createBinaryView(builder) { + _BinaryView.startBinaryView(builder); + return _BinaryView.endBinaryView(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/bool.mjs +var flatbuffers9, Bool; +var init_bool = __esm({ + "node_modules/apache-arrow/fb/bool.mjs"() { + flatbuffers9 = __toESM(require_flatbuffers(), 1); + Bool = class _Bool { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsBool(bb, obj) { + return (obj || new _Bool()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsBool(bb, obj) { + bb.setPosition(bb.position() + flatbuffers9.SIZE_PREFIX_LENGTH); + return (obj || new _Bool()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static startBool(builder) { + builder.startObject(0); + } + static endBool(builder) { + const offset = builder.endObject(); + return offset; + } + static createBool(builder) { + _Bool.startBool(builder); + return _Bool.endBool(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/date.mjs +var flatbuffers10, Date2; +var init_date = __esm({ + "node_modules/apache-arrow/fb/date.mjs"() { + flatbuffers10 = __toESM(require_flatbuffers(), 1); + init_date_unit(); + Date2 = class _Date { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsDate(bb, obj) { + return (obj || new _Date()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsDate(bb, obj) { + bb.setPosition(bb.position() + flatbuffers10.SIZE_PREFIX_LENGTH); + return (obj || new _Date()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + unit() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt16(this.bb_pos + offset) : DateUnit.MILLISECOND; + } + static startDate(builder) { + builder.startObject(1); + } + static addUnit(builder, unit) { + builder.addFieldInt16(0, unit, DateUnit.MILLISECOND); + } + static endDate(builder) { + const offset = builder.endObject(); + return offset; + } + static createDate(builder, unit) { + _Date.startDate(builder); + _Date.addUnit(builder, unit); + return _Date.endDate(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/decimal.mjs +var flatbuffers11, Decimal; +var init_decimal = __esm({ + "node_modules/apache-arrow/fb/decimal.mjs"() { + flatbuffers11 = __toESM(require_flatbuffers(), 1); + Decimal = class _Decimal { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsDecimal(bb, obj) { + return (obj || new _Decimal()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsDecimal(bb, obj) { + bb.setPosition(bb.position() + flatbuffers11.SIZE_PREFIX_LENGTH); + return (obj || new _Decimal()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + /** + * Total number of decimal digits + */ + precision() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + /** + * Number of digits after the decimal point "." + */ + scale() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + /** + * Number of bits per value. The only accepted widths are 128 and 256. + * We use bitWidth for consistency with Int::bitWidth. + */ + bitWidth() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 128; + } + static startDecimal(builder) { + builder.startObject(3); + } + static addPrecision(builder, precision) { + builder.addFieldInt32(0, precision, 0); + } + static addScale(builder, scale) { + builder.addFieldInt32(1, scale, 0); + } + static addBitWidth(builder, bitWidth) { + builder.addFieldInt32(2, bitWidth, 128); + } + static endDecimal(builder) { + const offset = builder.endObject(); + return offset; + } + static createDecimal(builder, precision, scale, bitWidth) { + _Decimal.startDecimal(builder); + _Decimal.addPrecision(builder, precision); + _Decimal.addScale(builder, scale); + _Decimal.addBitWidth(builder, bitWidth); + return _Decimal.endDecimal(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/duration.mjs +var flatbuffers12, Duration; +var init_duration = __esm({ + "node_modules/apache-arrow/fb/duration.mjs"() { + flatbuffers12 = __toESM(require_flatbuffers(), 1); + init_time_unit(); + Duration = class _Duration { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsDuration(bb, obj) { + return (obj || new _Duration()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsDuration(bb, obj) { + bb.setPosition(bb.position() + flatbuffers12.SIZE_PREFIX_LENGTH); + return (obj || new _Duration()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + unit() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt16(this.bb_pos + offset) : TimeUnit.MILLISECOND; + } + static startDuration(builder) { + builder.startObject(1); + } + static addUnit(builder, unit) { + builder.addFieldInt16(0, unit, TimeUnit.MILLISECOND); + } + static endDuration(builder) { + const offset = builder.endObject(); + return offset; + } + static createDuration(builder, unit) { + _Duration.startDuration(builder); + _Duration.addUnit(builder, unit); + return _Duration.endDuration(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/fixed-size-binary.mjs +var flatbuffers13, FixedSizeBinary; +var init_fixed_size_binary = __esm({ + "node_modules/apache-arrow/fb/fixed-size-binary.mjs"() { + flatbuffers13 = __toESM(require_flatbuffers(), 1); + FixedSizeBinary = class _FixedSizeBinary { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsFixedSizeBinary(bb, obj) { + return (obj || new _FixedSizeBinary()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsFixedSizeBinary(bb, obj) { + bb.setPosition(bb.position() + flatbuffers13.SIZE_PREFIX_LENGTH); + return (obj || new _FixedSizeBinary()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + /** + * Number of bytes per value + */ + byteWidth() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + static startFixedSizeBinary(builder) { + builder.startObject(1); + } + static addByteWidth(builder, byteWidth) { + builder.addFieldInt32(0, byteWidth, 0); + } + static endFixedSizeBinary(builder) { + const offset = builder.endObject(); + return offset; + } + static createFixedSizeBinary(builder, byteWidth) { + _FixedSizeBinary.startFixedSizeBinary(builder); + _FixedSizeBinary.addByteWidth(builder, byteWidth); + return _FixedSizeBinary.endFixedSizeBinary(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/fixed-size-list.mjs +var flatbuffers14, FixedSizeList; +var init_fixed_size_list = __esm({ + "node_modules/apache-arrow/fb/fixed-size-list.mjs"() { + flatbuffers14 = __toESM(require_flatbuffers(), 1); + FixedSizeList = class _FixedSizeList { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsFixedSizeList(bb, obj) { + return (obj || new _FixedSizeList()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsFixedSizeList(bb, obj) { + bb.setPosition(bb.position() + flatbuffers14.SIZE_PREFIX_LENGTH); + return (obj || new _FixedSizeList()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + /** + * Number of list items per value + */ + listSize() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + static startFixedSizeList(builder) { + builder.startObject(1); + } + static addListSize(builder, listSize) { + builder.addFieldInt32(0, listSize, 0); + } + static endFixedSizeList(builder) { + const offset = builder.endObject(); + return offset; + } + static createFixedSizeList(builder, listSize) { + _FixedSizeList.startFixedSizeList(builder); + _FixedSizeList.addListSize(builder, listSize); + return _FixedSizeList.endFixedSizeList(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/floating-point.mjs +var flatbuffers15, FloatingPoint; +var init_floating_point = __esm({ + "node_modules/apache-arrow/fb/floating-point.mjs"() { + flatbuffers15 = __toESM(require_flatbuffers(), 1); + init_precision(); + FloatingPoint = class _FloatingPoint { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsFloatingPoint(bb, obj) { + return (obj || new _FloatingPoint()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsFloatingPoint(bb, obj) { + bb.setPosition(bb.position() + flatbuffers15.SIZE_PREFIX_LENGTH); + return (obj || new _FloatingPoint()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + precision() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt16(this.bb_pos + offset) : Precision.HALF; + } + static startFloatingPoint(builder) { + builder.startObject(1); + } + static addPrecision(builder, precision) { + builder.addFieldInt16(0, precision, Precision.HALF); + } + static endFloatingPoint(builder) { + const offset = builder.endObject(); + return offset; + } + static createFloatingPoint(builder, precision) { + _FloatingPoint.startFloatingPoint(builder); + _FloatingPoint.addPrecision(builder, precision); + return _FloatingPoint.endFloatingPoint(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/interval.mjs +var flatbuffers16, Interval; +var init_interval = __esm({ + "node_modules/apache-arrow/fb/interval.mjs"() { + flatbuffers16 = __toESM(require_flatbuffers(), 1); + init_interval_unit(); + Interval = class _Interval { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsInterval(bb, obj) { + return (obj || new _Interval()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsInterval(bb, obj) { + bb.setPosition(bb.position() + flatbuffers16.SIZE_PREFIX_LENGTH); + return (obj || new _Interval()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + unit() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt16(this.bb_pos + offset) : IntervalUnit.YEAR_MONTH; + } + static startInterval(builder) { + builder.startObject(1); + } + static addUnit(builder, unit) { + builder.addFieldInt16(0, unit, IntervalUnit.YEAR_MONTH); + } + static endInterval(builder) { + const offset = builder.endObject(); + return offset; + } + static createInterval(builder, unit) { + _Interval.startInterval(builder); + _Interval.addUnit(builder, unit); + return _Interval.endInterval(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/large-binary.mjs +var flatbuffers17, LargeBinary; +var init_large_binary = __esm({ + "node_modules/apache-arrow/fb/large-binary.mjs"() { + flatbuffers17 = __toESM(require_flatbuffers(), 1); + LargeBinary = class _LargeBinary { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsLargeBinary(bb, obj) { + return (obj || new _LargeBinary()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsLargeBinary(bb, obj) { + bb.setPosition(bb.position() + flatbuffers17.SIZE_PREFIX_LENGTH); + return (obj || new _LargeBinary()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static startLargeBinary(builder) { + builder.startObject(0); + } + static endLargeBinary(builder) { + const offset = builder.endObject(); + return offset; + } + static createLargeBinary(builder) { + _LargeBinary.startLargeBinary(builder); + return _LargeBinary.endLargeBinary(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/large-list.mjs +var flatbuffers18, LargeList; +var init_large_list = __esm({ + "node_modules/apache-arrow/fb/large-list.mjs"() { + flatbuffers18 = __toESM(require_flatbuffers(), 1); + LargeList = class _LargeList { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsLargeList(bb, obj) { + return (obj || new _LargeList()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsLargeList(bb, obj) { + bb.setPosition(bb.position() + flatbuffers18.SIZE_PREFIX_LENGTH); + return (obj || new _LargeList()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static startLargeList(builder) { + builder.startObject(0); + } + static endLargeList(builder) { + const offset = builder.endObject(); + return offset; + } + static createLargeList(builder) { + _LargeList.startLargeList(builder); + return _LargeList.endLargeList(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/large-utf8.mjs +var flatbuffers19, LargeUtf8; +var init_large_utf8 = __esm({ + "node_modules/apache-arrow/fb/large-utf8.mjs"() { + flatbuffers19 = __toESM(require_flatbuffers(), 1); + LargeUtf8 = class _LargeUtf8 { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsLargeUtf8(bb, obj) { + return (obj || new _LargeUtf8()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsLargeUtf8(bb, obj) { + bb.setPosition(bb.position() + flatbuffers19.SIZE_PREFIX_LENGTH); + return (obj || new _LargeUtf8()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static startLargeUtf8(builder) { + builder.startObject(0); + } + static endLargeUtf8(builder) { + const offset = builder.endObject(); + return offset; + } + static createLargeUtf8(builder) { + _LargeUtf8.startLargeUtf8(builder); + return _LargeUtf8.endLargeUtf8(builder); } }; - exports2.PageBlobUploadPagesFromURLExceptionHeaders = { - serializedName: "PageBlob_uploadPagesFromURLExceptionHeaders", - type: { - name: "Composite", - className: "PageBlobUploadPagesFromURLExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - }, - copySourceErrorCode: { - serializedName: "x-ms-copy-source-error-code", - xmlName: "x-ms-copy-source-error-code", - type: { - name: "String" - } - }, - copySourceStatusCode: { - serializedName: "x-ms-copy-source-status-code", - xmlName: "x-ms-copy-source-status-code", - type: { - name: "Number" - } - } - } + } +}); + +// node_modules/apache-arrow/fb/list.mjs +var flatbuffers20, List; +var init_list = __esm({ + "node_modules/apache-arrow/fb/list.mjs"() { + flatbuffers20 = __toESM(require_flatbuffers(), 1); + List = class _List { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsList(bb, obj) { + return (obj || new _List()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsList(bb, obj) { + bb.setPosition(bb.position() + flatbuffers20.SIZE_PREFIX_LENGTH); + return (obj || new _List()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static startList(builder) { + builder.startObject(0); + } + static endList(builder) { + const offset = builder.endObject(); + return offset; + } + static createList(builder) { + _List.startList(builder); + return _List.endList(builder); } }; - exports2.PageBlobGetPageRangesHeaders = { - serializedName: "PageBlob_getPageRangesHeaders", - type: { - name: "Composite", - className: "PageBlobGetPageRangesHeaders", - modelProperties: { - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - blobContentLength: { - serializedName: "x-ms-blob-content-length", - xmlName: "x-ms-blob-content-length", - type: { - name: "Number" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + } +}); + +// node_modules/apache-arrow/fb/map.mjs +var flatbuffers21, Map2; +var init_map = __esm({ + "node_modules/apache-arrow/fb/map.mjs"() { + flatbuffers21 = __toESM(require_flatbuffers(), 1); + Map2 = class _Map { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsMap(bb, obj) { + return (obj || new _Map()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsMap(bb, obj) { + bb.setPosition(bb.position() + flatbuffers21.SIZE_PREFIX_LENGTH); + return (obj || new _Map()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + /** + * Set to true if the keys within each value are sorted + */ + keysSorted() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + static startMap(builder) { + builder.startObject(1); + } + static addKeysSorted(builder, keysSorted) { + builder.addFieldInt8(0, +keysSorted, 0); + } + static endMap(builder) { + const offset = builder.endObject(); + return offset; + } + static createMap(builder, keysSorted) { + _Map.startMap(builder); + _Map.addKeysSorted(builder, keysSorted); + return _Map.endMap(builder); } }; - exports2.PageBlobGetPageRangesExceptionHeaders = { - serializedName: "PageBlob_getPageRangesExceptionHeaders", - type: { - name: "Composite", - className: "PageBlobGetPageRangesExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + } +}); + +// node_modules/apache-arrow/fb/null.mjs +var flatbuffers22, Null; +var init_null = __esm({ + "node_modules/apache-arrow/fb/null.mjs"() { + flatbuffers22 = __toESM(require_flatbuffers(), 1); + Null = class _Null { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsNull(bb, obj) { + return (obj || new _Null()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsNull(bb, obj) { + bb.setPosition(bb.position() + flatbuffers22.SIZE_PREFIX_LENGTH); + return (obj || new _Null()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static startNull(builder) { + builder.startObject(0); + } + static endNull(builder) { + const offset = builder.endObject(); + return offset; + } + static createNull(builder) { + _Null.startNull(builder); + return _Null.endNull(builder); } }; - exports2.PageBlobGetPageRangesDiffHeaders = { - serializedName: "PageBlob_getPageRangesDiffHeaders", - type: { - name: "Composite", - className: "PageBlobGetPageRangesDiffHeaders", - modelProperties: { - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - blobContentLength: { - serializedName: "x-ms-blob-content-length", - xmlName: "x-ms-blob-content-length", - type: { - name: "Number" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + } +}); + +// node_modules/apache-arrow/fb/struct-.mjs +var flatbuffers23, Struct_; +var init_struct = __esm({ + "node_modules/apache-arrow/fb/struct-.mjs"() { + flatbuffers23 = __toESM(require_flatbuffers(), 1); + Struct_ = class _Struct_ { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsStruct_(bb, obj) { + return (obj || new _Struct_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsStruct_(bb, obj) { + bb.setPosition(bb.position() + flatbuffers23.SIZE_PREFIX_LENGTH); + return (obj || new _Struct_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static startStruct_(builder) { + builder.startObject(0); + } + static endStruct_(builder) { + const offset = builder.endObject(); + return offset; + } + static createStruct_(builder) { + _Struct_.startStruct_(builder); + return _Struct_.endStruct_(builder); } }; - exports2.PageBlobGetPageRangesDiffExceptionHeaders = { - serializedName: "PageBlob_getPageRangesDiffExceptionHeaders", - type: { - name: "Composite", - className: "PageBlobGetPageRangesDiffExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + } +}); + +// node_modules/apache-arrow/fb/time.mjs +var flatbuffers24, Time; +var init_time = __esm({ + "node_modules/apache-arrow/fb/time.mjs"() { + flatbuffers24 = __toESM(require_flatbuffers(), 1); + init_time_unit(); + Time = class _Time { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsTime(bb, obj) { + return (obj || new _Time()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsTime(bb, obj) { + bb.setPosition(bb.position() + flatbuffers24.SIZE_PREFIX_LENGTH); + return (obj || new _Time()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + unit() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt16(this.bb_pos + offset) : TimeUnit.MILLISECOND; + } + bitWidth() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 32; + } + static startTime(builder) { + builder.startObject(2); + } + static addUnit(builder, unit) { + builder.addFieldInt16(0, unit, TimeUnit.MILLISECOND); + } + static addBitWidth(builder, bitWidth) { + builder.addFieldInt32(1, bitWidth, 32); + } + static endTime(builder) { + const offset = builder.endObject(); + return offset; + } + static createTime(builder, unit, bitWidth) { + _Time.startTime(builder); + _Time.addUnit(builder, unit); + _Time.addBitWidth(builder, bitWidth); + return _Time.endTime(builder); } }; - exports2.PageBlobResizeHeaders = { - serializedName: "PageBlob_resizeHeaders", - type: { - name: "Composite", - className: "PageBlobResizeHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - blobSequenceNumber: { - serializedName: "x-ms-blob-sequence-number", - xmlName: "x-ms-blob-sequence-number", - type: { - name: "Number" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + } +}); + +// node_modules/apache-arrow/fb/timestamp.mjs +var flatbuffers25, Timestamp; +var init_timestamp = __esm({ + "node_modules/apache-arrow/fb/timestamp.mjs"() { + flatbuffers25 = __toESM(require_flatbuffers(), 1); + init_time_unit(); + Timestamp = class _Timestamp { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsTimestamp(bb, obj) { + return (obj || new _Timestamp()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsTimestamp(bb, obj) { + bb.setPosition(bb.position() + flatbuffers25.SIZE_PREFIX_LENGTH); + return (obj || new _Timestamp()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + unit() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt16(this.bb_pos + offset) : TimeUnit.SECOND; + } + timezone(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static startTimestamp(builder) { + builder.startObject(2); + } + static addUnit(builder, unit) { + builder.addFieldInt16(0, unit, TimeUnit.SECOND); + } + static addTimezone(builder, timezoneOffset) { + builder.addFieldOffset(1, timezoneOffset, 0); + } + static endTimestamp(builder) { + const offset = builder.endObject(); + return offset; + } + static createTimestamp(builder, unit, timezoneOffset) { + _Timestamp.startTimestamp(builder); + _Timestamp.addUnit(builder, unit); + _Timestamp.addTimezone(builder, timezoneOffset); + return _Timestamp.endTimestamp(builder); } }; - exports2.PageBlobResizeExceptionHeaders = { - serializedName: "PageBlob_resizeExceptionHeaders", - type: { - name: "Composite", - className: "PageBlobResizeExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + } +}); + +// node_modules/apache-arrow/fb/union.mjs +var flatbuffers26, Union; +var init_union = __esm({ + "node_modules/apache-arrow/fb/union.mjs"() { + flatbuffers26 = __toESM(require_flatbuffers(), 1); + init_union_mode(); + Union = class _Union { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsUnion(bb, obj) { + return (obj || new _Union()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsUnion(bb, obj) { + bb.setPosition(bb.position() + flatbuffers26.SIZE_PREFIX_LENGTH); + return (obj || new _Union()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + mode() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt16(this.bb_pos + offset) : UnionMode.Sparse; + } + typeIds(index2) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt32(this.bb.__vector(this.bb_pos + offset) + index2 * 4) : 0; + } + typeIdsLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + typeIdsArray() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? new Int32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + static startUnion(builder) { + builder.startObject(2); + } + static addMode(builder, mode) { + builder.addFieldInt16(0, mode, UnionMode.Sparse); + } + static addTypeIds(builder, typeIdsOffset) { + builder.addFieldOffset(1, typeIdsOffset, 0); + } + static createTypeIdsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt32(data[i]); } + return builder.endVector(); + } + static startTypeIdsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endUnion(builder) { + const offset = builder.endObject(); + return offset; + } + static createUnion(builder, mode, typeIdsOffset) { + _Union.startUnion(builder); + _Union.addMode(builder, mode); + _Union.addTypeIds(builder, typeIdsOffset); + return _Union.endUnion(builder); } }; - exports2.PageBlobUpdateSequenceNumberHeaders = { - serializedName: "PageBlob_updateSequenceNumberHeaders", - type: { - name: "Composite", - className: "PageBlobUpdateSequenceNumberHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - blobSequenceNumber: { - serializedName: "x-ms-blob-sequence-number", - xmlName: "x-ms-blob-sequence-number", - type: { - name: "Number" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + } +}); + +// node_modules/apache-arrow/fb/utf8.mjs +var flatbuffers27, Utf8; +var init_utf82 = __esm({ + "node_modules/apache-arrow/fb/utf8.mjs"() { + flatbuffers27 = __toESM(require_flatbuffers(), 1); + Utf8 = class _Utf8 { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsUtf8(bb, obj) { + return (obj || new _Utf8()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsUtf8(bb, obj) { + bb.setPosition(bb.position() + flatbuffers27.SIZE_PREFIX_LENGTH); + return (obj || new _Utf8()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static startUtf8(builder) { + builder.startObject(0); + } + static endUtf8(builder) { + const offset = builder.endObject(); + return offset; + } + static createUtf8(builder) { + _Utf8.startUtf8(builder); + return _Utf8.endUtf8(builder); } }; - exports2.PageBlobUpdateSequenceNumberExceptionHeaders = { - serializedName: "PageBlob_updateSequenceNumberExceptionHeaders", - type: { - name: "Composite", - className: "PageBlobUpdateSequenceNumberExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + } +}); + +// node_modules/apache-arrow/fb/utf8-view.mjs +var flatbuffers28, Utf8View; +var init_utf8_view = __esm({ + "node_modules/apache-arrow/fb/utf8-view.mjs"() { + flatbuffers28 = __toESM(require_flatbuffers(), 1); + Utf8View = class _Utf8View { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsUtf8View(bb, obj) { + return (obj || new _Utf8View()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsUtf8View(bb, obj) { + bb.setPosition(bb.position() + flatbuffers28.SIZE_PREFIX_LENGTH); + return (obj || new _Utf8View()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static startUtf8View(builder) { + builder.startObject(0); + } + static endUtf8View(builder) { + const offset = builder.endObject(); + return offset; + } + static createUtf8View(builder) { + _Utf8View.startUtf8View(builder); + return _Utf8View.endUtf8View(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/type.mjs +var Type; +var init_type = __esm({ + "node_modules/apache-arrow/fb/type.mjs"() { + (function(Type3) { + Type3[Type3["NONE"] = 0] = "NONE"; + Type3[Type3["Null"] = 1] = "Null"; + Type3[Type3["Int"] = 2] = "Int"; + Type3[Type3["FloatingPoint"] = 3] = "FloatingPoint"; + Type3[Type3["Binary"] = 4] = "Binary"; + Type3[Type3["Utf8"] = 5] = "Utf8"; + Type3[Type3["Bool"] = 6] = "Bool"; + Type3[Type3["Decimal"] = 7] = "Decimal"; + Type3[Type3["Date"] = 8] = "Date"; + Type3[Type3["Time"] = 9] = "Time"; + Type3[Type3["Timestamp"] = 10] = "Timestamp"; + Type3[Type3["Interval"] = 11] = "Interval"; + Type3[Type3["List"] = 12] = "List"; + Type3[Type3["Struct_"] = 13] = "Struct_"; + Type3[Type3["Union"] = 14] = "Union"; + Type3[Type3["FixedSizeBinary"] = 15] = "FixedSizeBinary"; + Type3[Type3["FixedSizeList"] = 16] = "FixedSizeList"; + Type3[Type3["Map"] = 17] = "Map"; + Type3[Type3["Duration"] = 18] = "Duration"; + Type3[Type3["LargeBinary"] = 19] = "LargeBinary"; + Type3[Type3["LargeUtf8"] = 20] = "LargeUtf8"; + Type3[Type3["LargeList"] = 21] = "LargeList"; + Type3[Type3["RunEndEncoded"] = 22] = "RunEndEncoded"; + Type3[Type3["BinaryView"] = 23] = "BinaryView"; + Type3[Type3["Utf8View"] = 24] = "Utf8View"; + Type3[Type3["ListView"] = 25] = "ListView"; + Type3[Type3["LargeListView"] = 26] = "LargeListView"; + })(Type || (Type = {})); + } +}); + +// node_modules/apache-arrow/fb/field.mjs +var flatbuffers29, Field; +var init_field = __esm({ + "node_modules/apache-arrow/fb/field.mjs"() { + flatbuffers29 = __toESM(require_flatbuffers(), 1); + init_dictionary_encoding(); + init_key_value(); + init_type(); + Field = class _Field { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsField(bb, obj) { + return (obj || new _Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsField(bb, obj) { + bb.setPosition(bb.position() + flatbuffers29.SIZE_PREFIX_LENGTH); + return (obj || new _Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + /** + * Whether or not this field can contain nulls. Should be true in general. + */ + nullable() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + typeType() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readUint8(this.bb_pos + offset) : Type.NONE; + } + /** + * This is the type of the decoded value if the field is dictionary encoded. + */ + type(obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__union(obj, this.bb_pos + offset) : null; + } + /** + * Present only if the field is dictionary encoded. + */ + dictionary(obj) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? (obj || new DictionaryEncoding()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + /** + * children apply only to nested data types like Struct, List and Union. For + * primitive types children will have length 0. + */ + children(index2, obj) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? (obj || new _Field()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null; + } + childrenLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + /** + * User-defined metadata + */ + customMetadata(index2, obj) { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null; + } + customMetadataLength() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static startField(builder) { + builder.startObject(7); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addNullable(builder, nullable) { + builder.addFieldInt8(1, +nullable, 0); + } + static addTypeType(builder, typeType) { + builder.addFieldInt8(2, typeType, Type.NONE); + } + static addType(builder, typeOffset) { + builder.addFieldOffset(3, typeOffset, 0); + } + static addDictionary(builder, dictionaryOffset) { + builder.addFieldOffset(4, dictionaryOffset, 0); + } + static addChildren(builder, childrenOffset) { + builder.addFieldOffset(5, childrenOffset, 0); + } + static createChildrenVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); } + return builder.endVector(); } - }; - exports2.PageBlobCopyIncrementalHeaders = { - serializedName: "PageBlob_copyIncrementalHeaders", - type: { - name: "Composite", - className: "PageBlobCopyIncrementalHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - copyId: { - serializedName: "x-ms-copy-id", - xmlName: "x-ms-copy-id", - type: { - name: "String" - } - }, - copyStatus: { - serializedName: "x-ms-copy-status", - xmlName: "x-ms-copy-status", - type: { - name: "Enum", - allowedValues: ["pending", "success", "aborted", "failed"] - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } + static startChildrenVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addCustomMetadata(builder, customMetadataOffset) { + builder.addFieldOffset(6, customMetadataOffset, 0); + } + static createCustomMetadataVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); } + return builder.endVector(); + } + static startCustomMetadataVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endField(builder) { + const offset = builder.endObject(); + return offset; } }; - exports2.PageBlobCopyIncrementalExceptionHeaders = { - serializedName: "PageBlob_copyIncrementalExceptionHeaders", - type: { - name: "Composite", - className: "PageBlobCopyIncrementalExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + } +}); + +// node_modules/apache-arrow/fb/schema.mjs +var flatbuffers30, Schema3; +var init_schema = __esm({ + "node_modules/apache-arrow/fb/schema.mjs"() { + flatbuffers30 = __toESM(require_flatbuffers(), 1); + init_endianness(); + init_field(); + init_key_value(); + Schema3 = class _Schema { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsSchema(bb, obj) { + return (obj || new _Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsSchema(bb, obj) { + bb.setPosition(bb.position() + flatbuffers30.SIZE_PREFIX_LENGTH); + return (obj || new _Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + /** + * endianness of the buffer + * it is Little Endian by default + * if endianness doesn't match the underlying system then the vectors need to be converted + */ + endianness() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt16(this.bb_pos + offset) : Endianness.Little; + } + fields(index2, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Field()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null; + } + fieldsLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + customMetadata(index2, obj) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null; + } + customMetadataLength() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + /** + * Features used in the stream/file. + */ + features(index2) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index2 * 8) : BigInt(0); + } + featuresLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static startSchema(builder) { + builder.startObject(4); + } + static addEndianness(builder, endianness) { + builder.addFieldInt16(0, endianness, Endianness.Little); + } + static addFields(builder, fieldsOffset) { + builder.addFieldOffset(1, fieldsOffset, 0); + } + static createFieldsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startFieldsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addCustomMetadata(builder, customMetadataOffset) { + builder.addFieldOffset(2, customMetadataOffset, 0); + } + static createCustomMetadataVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startCustomMetadataVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addFeatures(builder, featuresOffset) { + builder.addFieldOffset(3, featuresOffset, 0); + } + static createFeaturesVector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]); + } + return builder.endVector(); + } + static startFeaturesVector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static endSchema(builder) { + const offset = builder.endObject(); + return offset; + } + static createSchema(builder, endianness, fieldsOffset, customMetadataOffset, featuresOffset) { + _Schema.startSchema(builder); + _Schema.addEndianness(builder, endianness); + _Schema.addFields(builder, fieldsOffset); + _Schema.addCustomMetadata(builder, customMetadataOffset); + _Schema.addFeatures(builder, featuresOffset); + return _Schema.endSchema(builder); + } + }; + } +}); + +// node_modules/apache-arrow/fb/message-header.mjs +var MessageHeader; +var init_message_header = __esm({ + "node_modules/apache-arrow/fb/message-header.mjs"() { + (function(MessageHeader2) { + MessageHeader2[MessageHeader2["NONE"] = 0] = "NONE"; + MessageHeader2[MessageHeader2["Schema"] = 1] = "Schema"; + MessageHeader2[MessageHeader2["DictionaryBatch"] = 2] = "DictionaryBatch"; + MessageHeader2[MessageHeader2["RecordBatch"] = 3] = "RecordBatch"; + MessageHeader2[MessageHeader2["Tensor"] = 4] = "Tensor"; + MessageHeader2[MessageHeader2["SparseTensor"] = 5] = "SparseTensor"; + })(MessageHeader || (MessageHeader = {})); + } +}); + +// node_modules/apache-arrow/enum.mjs +var Type2, BufferType; +var init_enum = __esm({ + "node_modules/apache-arrow/enum.mjs"() { + init_metadata_version(); + init_union_mode(); + init_precision(); + init_date_unit(); + init_time_unit(); + init_interval_unit(); + init_message_header(); + (function(Type3) { + Type3[Type3["NONE"] = 0] = "NONE"; + Type3[Type3["Null"] = 1] = "Null"; + Type3[Type3["Int"] = 2] = "Int"; + Type3[Type3["Float"] = 3] = "Float"; + Type3[Type3["Binary"] = 4] = "Binary"; + Type3[Type3["Utf8"] = 5] = "Utf8"; + Type3[Type3["Bool"] = 6] = "Bool"; + Type3[Type3["Decimal"] = 7] = "Decimal"; + Type3[Type3["Date"] = 8] = "Date"; + Type3[Type3["Time"] = 9] = "Time"; + Type3[Type3["Timestamp"] = 10] = "Timestamp"; + Type3[Type3["Interval"] = 11] = "Interval"; + Type3[Type3["List"] = 12] = "List"; + Type3[Type3["Struct"] = 13] = "Struct"; + Type3[Type3["Union"] = 14] = "Union"; + Type3[Type3["FixedSizeBinary"] = 15] = "FixedSizeBinary"; + Type3[Type3["FixedSizeList"] = 16] = "FixedSizeList"; + Type3[Type3["Map"] = 17] = "Map"; + Type3[Type3["Duration"] = 18] = "Duration"; + Type3[Type3["LargeBinary"] = 19] = "LargeBinary"; + Type3[Type3["LargeUtf8"] = 20] = "LargeUtf8"; + Type3[Type3["LargeList"] = 21] = "LargeList"; + Type3[Type3["BinaryView"] = 23] = "BinaryView"; + Type3[Type3["Utf8View"] = 24] = "Utf8View"; + Type3[Type3["Dictionary"] = -1] = "Dictionary"; + Type3[Type3["Int8"] = -2] = "Int8"; + Type3[Type3["Int16"] = -3] = "Int16"; + Type3[Type3["Int32"] = -4] = "Int32"; + Type3[Type3["Int64"] = -5] = "Int64"; + Type3[Type3["Uint8"] = -6] = "Uint8"; + Type3[Type3["Uint16"] = -7] = "Uint16"; + Type3[Type3["Uint32"] = -8] = "Uint32"; + Type3[Type3["Uint64"] = -9] = "Uint64"; + Type3[Type3["Float16"] = -10] = "Float16"; + Type3[Type3["Float32"] = -11] = "Float32"; + Type3[Type3["Float64"] = -12] = "Float64"; + Type3[Type3["DateDay"] = -13] = "DateDay"; + Type3[Type3["DateMillisecond"] = -14] = "DateMillisecond"; + Type3[Type3["TimestampSecond"] = -15] = "TimestampSecond"; + Type3[Type3["TimestampMillisecond"] = -16] = "TimestampMillisecond"; + Type3[Type3["TimestampMicrosecond"] = -17] = "TimestampMicrosecond"; + Type3[Type3["TimestampNanosecond"] = -18] = "TimestampNanosecond"; + Type3[Type3["TimeSecond"] = -19] = "TimeSecond"; + Type3[Type3["TimeMillisecond"] = -20] = "TimeMillisecond"; + Type3[Type3["TimeMicrosecond"] = -21] = "TimeMicrosecond"; + Type3[Type3["TimeNanosecond"] = -22] = "TimeNanosecond"; + Type3[Type3["DenseUnion"] = -23] = "DenseUnion"; + Type3[Type3["SparseUnion"] = -24] = "SparseUnion"; + Type3[Type3["IntervalDayTime"] = -25] = "IntervalDayTime"; + Type3[Type3["IntervalYearMonth"] = -26] = "IntervalYearMonth"; + Type3[Type3["DurationSecond"] = -27] = "DurationSecond"; + Type3[Type3["DurationMillisecond"] = -28] = "DurationMillisecond"; + Type3[Type3["DurationMicrosecond"] = -29] = "DurationMicrosecond"; + Type3[Type3["DurationNanosecond"] = -30] = "DurationNanosecond"; + Type3[Type3["IntervalMonthDayNano"] = -31] = "IntervalMonthDayNano"; + })(Type2 || (Type2 = {})); + (function(BufferType2) { + BufferType2[BufferType2["OFFSET"] = 0] = "OFFSET"; + BufferType2[BufferType2["DATA"] = 1] = "DATA"; + BufferType2[BufferType2["VALIDITY"] = 2] = "VALIDITY"; + BufferType2[BufferType2["TYPE"] = 3] = "TYPE"; + })(BufferType || (BufferType = {})); + } +}); + +// node_modules/apache-arrow/util/pretty.mjs +var pretty_exports = {}; +__export(pretty_exports, { + valueToString: () => valueToString +}); +function valueToString(x) { + if (x === null) { + return "null"; + } + if (x === undf) { + return "undefined"; + } + switch (typeof x) { + case "number": + return `${x}`; + case "bigint": + return `${x}`; + case "string": + return `"${x}"`; + } + if (typeof x[Symbol.toPrimitive] === "function") { + return x[Symbol.toPrimitive]("string"); + } + if (ArrayBuffer.isView(x)) { + if (x instanceof BigInt64Array || x instanceof BigUint64Array) { + return `[${[...x].map((x2) => valueToString(x2))}]`; + } + return `[${x}]`; + } + return ArrayBuffer.isView(x) ? `[${x}]` : JSON.stringify(x, (_2, y) => typeof y === "bigint" ? `${y}` : y); +} +var undf; +var init_pretty = __esm({ + "node_modules/apache-arrow/util/pretty.mjs"() { + undf = void 0; + } +}); + +// node_modules/apache-arrow/util/bigint.mjs +function bigIntToNumber(number2) { + if (typeof number2 === "bigint" && (number2 < Number.MIN_SAFE_INTEGER || number2 > Number.MAX_SAFE_INTEGER)) { + throw new TypeError(`${number2} is not safe to convert to a number.`); + } + return Number(number2); +} +function divideBigInts(number2, divisor) { + return bigIntToNumber(number2 / divisor) + bigIntToNumber(number2 % divisor) / bigIntToNumber(divisor); +} +var init_bigint = __esm({ + "node_modules/apache-arrow/util/bigint.mjs"() { + } +}); + +// node_modules/apache-arrow/util/bn.mjs +var bn_exports = {}; +__export(bn_exports, { + BN: () => BN, + bigNumToBigInt: () => bigNumToBigInt, + bigNumToNumber: () => bigNumToNumber, + bigNumToString: () => bigNumToString, + isArrowBigNumSymbol: () => isArrowBigNumSymbol +}); +function BigNum(x, ...xs) { + if (xs.length === 0) { + return Object.setPrototypeOf(toArrayBufferView(this["TypedArray"], x), this.constructor.prototype); + } + return Object.setPrototypeOf(new this["TypedArray"](x, ...xs), this.constructor.prototype); +} +function SignedBigNum(...args) { + return BigNum.apply(this, args); +} +function UnsignedBigNum(...args) { + return BigNum.apply(this, args); +} +function DecimalBigNum(...args) { + return BigNum.apply(this, args); +} +function bigNumToNumber(bn, scale) { + const { buffer, byteOffset, byteLength, "signed": signed } = bn; + const words = new BigUint64Array(buffer, byteOffset, byteLength / 8); + const negative = signed && words.at(-1) & BigInt(1) << BigInt(63); + let number2 = BigInt(0); + let i = 0; + if (negative) { + for (const word of words) { + number2 |= (word ^ TWO_TO_THE_64_MINUS_1) * (BigInt(1) << BigInt(64 * i++)); + } + number2 *= BigInt(-1); + number2 -= BigInt(1); + } else { + for (const word of words) { + number2 |= word * (BigInt(1) << BigInt(64 * i++)); + } + } + if (typeof scale === "number" && scale > 0) { + const denominator = BigInt("1".padEnd(scale + 1, "0")); + const quotient = number2 / denominator; + const remainder = negative ? -(number2 % denominator) : number2 % denominator; + const integerPart = bigIntToNumber(quotient); + const fractionPart = `${remainder}`.padStart(scale, "0"); + const sign = negative && integerPart === 0 ? "-" : ""; + return +`${sign}${integerPart}.${fractionPart}`; + } + return bigIntToNumber(number2); +} +function bigNumToString(a) { + if (a.byteLength === 8) { + const bigIntArray = new a["BigIntArray"](a.buffer, a.byteOffset, 1); + return `${bigIntArray[0]}`; + } + if (!a["signed"]) { + return unsignedBigNumToString(a); + } + let array2 = new Uint16Array(a.buffer, a.byteOffset, a.byteLength / 2); + const highOrderWord = new Int16Array([array2.at(-1)])[0]; + if (highOrderWord >= 0) { + return unsignedBigNumToString(a); + } + array2 = array2.slice(); + let carry = 1; + for (let i = 0; i < array2.length; i++) { + const elem = array2[i]; + const updated = ~elem + carry; + array2[i] = updated; + carry &= elem === 0 ? 1 : 0; + } + const negated = unsignedBigNumToString(array2); + return `-${negated}`; +} +function bigNumToBigInt(a) { + if (a.byteLength === 8) { + const bigIntArray = new a["BigIntArray"](a.buffer, a.byteOffset, 1); + return bigIntArray[0]; + } else { + return bigNumToString(a); + } +} +function unsignedBigNumToString(a) { + let digits = ""; + const base64 = new Uint32Array(2); + let base32 = new Uint16Array(a.buffer, a.byteOffset, a.byteLength / 2); + const checks = new Uint32Array((base32 = new Uint16Array(base32).reverse()).buffer); + let i = -1; + const n = base32.length - 1; + do { + for (base64[0] = base32[i = 0]; i < n; ) { + base32[i++] = base64[1] = base64[0] / 10; + base64[0] = (base64[0] - base64[1] * 10 << 16) + base32[i]; + } + base32[i] = base64[1] = base64[0] / 10; + base64[0] = base64[0] - base64[1] * 10; + digits = `${base64[0]}${digits}`; + } while (checks[0] || checks[1] || checks[2] || checks[3]); + return digits !== null && digits !== void 0 ? digits : `0`; +} +var isArrowBigNumSymbol, TWO_TO_THE_64, TWO_TO_THE_64_MINUS_1, BN; +var init_bn = __esm({ + "node_modules/apache-arrow/util/bn.mjs"() { + init_buffer(); + init_bigint(); + isArrowBigNumSymbol = /* @__PURE__ */ Symbol.for("isArrowBigNum"); + BigNum.prototype[isArrowBigNumSymbol] = true; + BigNum.prototype.toJSON = function() { + return `"${bigNumToString(this)}"`; + }; + BigNum.prototype.valueOf = function(scale) { + return bigNumToNumber(this, scale); + }; + BigNum.prototype.toString = function() { + return bigNumToString(this); + }; + BigNum.prototype[Symbol.toPrimitive] = function(hint = "default") { + switch (hint) { + case "number": + return bigNumToNumber(this); + case "string": + return bigNumToString(this); + case "default": + return bigNumToBigInt(this); + } + return bigNumToString(this); + }; + Object.setPrototypeOf(SignedBigNum.prototype, Object.create(Int32Array.prototype)); + Object.setPrototypeOf(UnsignedBigNum.prototype, Object.create(Uint32Array.prototype)); + Object.setPrototypeOf(DecimalBigNum.prototype, Object.create(Uint32Array.prototype)); + Object.assign(SignedBigNum.prototype, BigNum.prototype, { "constructor": SignedBigNum, "signed": true, "TypedArray": Int32Array, "BigIntArray": BigInt64Array }); + Object.assign(UnsignedBigNum.prototype, BigNum.prototype, { "constructor": UnsignedBigNum, "signed": false, "TypedArray": Uint32Array, "BigIntArray": BigUint64Array }); + Object.assign(DecimalBigNum.prototype, BigNum.prototype, { "constructor": DecimalBigNum, "signed": true, "TypedArray": Uint32Array, "BigIntArray": BigUint64Array }); + TWO_TO_THE_64 = BigInt(4294967296) * BigInt(4294967296); + TWO_TO_THE_64_MINUS_1 = TWO_TO_THE_64 - BigInt(1); + BN = class _BN { + /** @nocollapse */ + static new(num, isSigned) { + switch (isSigned) { + case true: + return new SignedBigNum(num); + case false: + return new UnsignedBigNum(num); + } + switch (num.constructor) { + case Int8Array: + case Int16Array: + case Int32Array: + case BigInt64Array: + return new SignedBigNum(num); + } + if (num.byteLength === 16) { + return new DecimalBigNum(num); + } + return new UnsignedBigNum(num); + } + /** @nocollapse */ + static signed(num) { + return new SignedBigNum(num); + } + /** @nocollapse */ + static unsigned(num) { + return new UnsignedBigNum(num); + } + /** @nocollapse */ + static decimal(num) { + return new DecimalBigNum(num); + } + constructor(num, isSigned) { + return _BN.new(num, isSigned); + } + }; + } +}); + +// node_modules/apache-arrow/type.mjs +function strideForType(type) { + const t = type; + switch (type.typeId) { + case Type2.Decimal: + return type.bitWidth / 32; + case Type2.Interval: { + if (t.unit === IntervalUnit.MONTH_DAY_NANO) { + return 4; + } + return 1 + t.unit; + } + // case Type.Int: return 1 + +((t as Int_).bitWidth > 32); + // case Type.Time: return 1 + +((t as Time_).bitWidth > 32); + case Type2.BinaryView: + case Type2.Utf8View: + return 16; + case Type2.FixedSizeList: + return t.listSize; + case Type2.FixedSizeBinary: + return t.byteWidth; + default: + return 1; + } +} +var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, kDataTypeSymbol, DataType, Null2, Int_, Int8, Int16, Int32, Int64, Uint8, Uint16, Uint32, Uint64, Float, Float16, Float32, Float64, Binary2, BinaryView2, LargeBinary2, Utf82, Utf8View2, LargeUtf82, Bool2, Decimal2, Date_, DateDay, DateMillisecond, Time_, TimeSecond, TimeMillisecond, TimeMicrosecond, TimeNanosecond, Timestamp_, TimestampSecond, TimestampMillisecond, TimestampMicrosecond, TimestampNanosecond, Interval_, IntervalDayTime, IntervalYearMonth, IntervalMonthDayNano, Duration2, DurationSecond, DurationMillisecond, DurationMicrosecond, DurationNanosecond, List2, LargeList2, Struct, Union_, DenseUnion, SparseUnion, FixedSizeBinary2, FixedSizeList2, Map_, getId, Dictionary; +var init_type2 = __esm({ + "node_modules/apache-arrow/type.mjs"() { + init_bigint(); + init_enum(); + kDataTypeSymbol = /* @__PURE__ */ Symbol.for("apache-arrow/DataType"); + DataType = class _DataType { + /** + * Check if an object is an instance of DataType. + * This works across different instances of the Arrow library. + * + * Note: We intentionally do NOT implement Symbol.hasInstance here because + * it would break instanceof checks for subclasses like Struct, Dictionary, etc. + * Use DataType.isDataType() for cross-library type checking instead. + * @nocollapse + */ + static isDataType(x) { + return (x === null || x === void 0 ? void 0 : x[kDataTypeSymbol]) === true; + } + /** @nocollapse */ + static isNull(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Null; + } + /** @nocollapse */ + static isInt(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Int; + } + /** @nocollapse */ + static isFloat(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Float; + } + /** @nocollapse */ + static isBinary(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Binary; + } + /** @nocollapse */ + static isBinaryView(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.BinaryView; + } + /** @nocollapse */ + static isLargeBinary(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.LargeBinary; + } + /** @nocollapse */ + static isUtf8(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Utf8; + } + /** @nocollapse */ + static isUtf8View(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Utf8View; + } + /** @nocollapse */ + static isLargeUtf8(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.LargeUtf8; + } + /** @nocollapse */ + static isBool(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Bool; + } + /** @nocollapse */ + static isDecimal(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Decimal; + } + /** @nocollapse */ + static isDate(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Date; + } + /** @nocollapse */ + static isTime(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Time; + } + /** @nocollapse */ + static isTimestamp(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Timestamp; + } + /** @nocollapse */ + static isInterval(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Interval; + } + /** @nocollapse */ + static isDuration(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Duration; + } + /** @nocollapse */ + static isList(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.List; + } + /** @nocollapse */ + static isLargeList(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.LargeList; + } + // TODO: Implement ListView type + // /** @nocollapse */ static isListView(x: any): x is ListView { return x?.typeId === Type.ListView; } + /** @nocollapse */ + static isStruct(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Struct; + } + /** @nocollapse */ + static isUnion(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Union; + } + /** @nocollapse */ + static isFixedSizeBinary(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.FixedSizeBinary; + } + /** @nocollapse */ + static isFixedSizeList(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.FixedSizeList; + } + /** @nocollapse */ + static isMap(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Map; + } + /** @nocollapse */ + static isDictionary(x) { + return (x === null || x === void 0 ? void 0 : x.typeId) === Type2.Dictionary; + } + /** @nocollapse */ + static isDenseUnion(x) { + return _DataType.isUnion(x) && x.mode === UnionMode.Dense; + } + /** @nocollapse */ + static isSparseUnion(x) { + return _DataType.isUnion(x) && x.mode === UnionMode.Sparse; + } + constructor(typeId) { + this.typeId = typeId; + } + }; + _a = Symbol.toStringTag; + DataType[_a] = ((proto) => { + proto.children = null; + proto.ArrayType = Array; + proto.OffsetArrayType = Int32Array; + proto[kDataTypeSymbol] = true; + return proto[Symbol.toStringTag] = "DataType"; + })(DataType.prototype); + Null2 = class extends DataType { + constructor() { + super(Type2.Null); + } + toString() { + return `Null`; + } + }; + _b = Symbol.toStringTag; + Null2[_b] = ((proto) => proto[Symbol.toStringTag] = "Null")(Null2.prototype); + Int_ = class extends DataType { + constructor(isSigned, bitWidth) { + super(Type2.Int); + this.isSigned = isSigned; + this.bitWidth = bitWidth; + } + get ArrayType() { + switch (this.bitWidth) { + case 8: + return this.isSigned ? Int8Array : Uint8Array; + case 16: + return this.isSigned ? Int16Array : Uint16Array; + case 32: + return this.isSigned ? Int32Array : Uint32Array; + case 64: + return this.isSigned ? BigInt64Array : BigUint64Array; + } + throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`); + } + toString() { + return `${this.isSigned ? `I` : `Ui`}nt${this.bitWidth}`; } }; - exports2.AppendBlobCreateHeaders = { - serializedName: "AppendBlob_createHeaders", - type: { - name: "Composite", - className: "AppendBlobCreateHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - versionId: { - serializedName: "x-ms-version-id", - xmlName: "x-ms-version-id", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - xmlName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + _c = Symbol.toStringTag; + Int_[_c] = ((proto) => { + proto.isSigned = null; + proto.bitWidth = null; + return proto[Symbol.toStringTag] = "Int"; + })(Int_.prototype); + Int8 = class extends Int_ { + constructor() { + super(true, 8); + } + get ArrayType() { + return Int8Array; } }; - exports2.AppendBlobCreateExceptionHeaders = { - serializedName: "AppendBlob_createExceptionHeaders", - type: { - name: "Composite", - className: "AppendBlobCreateExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + Int16 = class extends Int_ { + constructor() { + super(true, 16); + } + get ArrayType() { + return Int16Array; } }; - exports2.AppendBlobAppendBlockHeaders = { - serializedName: "AppendBlob_appendBlockHeaders", - type: { - name: "Composite", - className: "AppendBlobAppendBlockHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" - } - }, - xMsContentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", - type: { - name: "ByteArray" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - blobAppendOffset: { - serializedName: "x-ms-blob-append-offset", - xmlName: "x-ms-blob-append-offset", - type: { - name: "String" - } - }, - blobCommittedBlockCount: { - serializedName: "x-ms-blob-committed-block-count", - xmlName: "x-ms-blob-committed-block-count", - type: { - name: "Number" - } - }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - xmlName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + Int32 = class extends Int_ { + constructor() { + super(true, 32); + } + get ArrayType() { + return Int32Array; } }; - exports2.AppendBlobAppendBlockExceptionHeaders = { - serializedName: "AppendBlob_appendBlockExceptionHeaders", - type: { - name: "Composite", - className: "AppendBlobAppendBlockExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + Int64 = class extends Int_ { + constructor() { + super(true, 64); + } + get ArrayType() { + return BigInt64Array; } }; - exports2.AppendBlobAppendBlockFromUrlHeaders = { - serializedName: "AppendBlob_appendBlockFromUrlHeaders", - type: { - name: "Composite", - className: "AppendBlobAppendBlockFromUrlHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" - } - }, - xMsContentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", - type: { - name: "ByteArray" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - blobAppendOffset: { - serializedName: "x-ms-blob-append-offset", - xmlName: "x-ms-blob-append-offset", - type: { - name: "String" - } - }, - blobCommittedBlockCount: { - serializedName: "x-ms-blob-committed-block-count", - xmlName: "x-ms-blob-committed-block-count", - type: { - name: "Number" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - xmlName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + Uint8 = class extends Int_ { + constructor() { + super(false, 8); + } + get ArrayType() { + return Uint8Array; } }; - exports2.AppendBlobAppendBlockFromUrlExceptionHeaders = { - serializedName: "AppendBlob_appendBlockFromUrlExceptionHeaders", - type: { - name: "Composite", - className: "AppendBlobAppendBlockFromUrlExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - }, - copySourceErrorCode: { - serializedName: "x-ms-copy-source-error-code", - xmlName: "x-ms-copy-source-error-code", - type: { - name: "String" - } - }, - copySourceStatusCode: { - serializedName: "x-ms-copy-source-status-code", - xmlName: "x-ms-copy-source-status-code", - type: { - name: "Number" - } - } - } + Uint16 = class extends Int_ { + constructor() { + super(false, 16); + } + get ArrayType() { + return Uint16Array; } }; - exports2.AppendBlobSealHeaders = { - serializedName: "AppendBlob_sealHeaders", - type: { - name: "Composite", - className: "AppendBlobSealHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - isSealed: { - serializedName: "x-ms-blob-sealed", - xmlName: "x-ms-blob-sealed", - type: { - name: "Boolean" - } - } - } + Uint32 = class extends Int_ { + constructor() { + super(false, 32); + } + get ArrayType() { + return Uint32Array; } }; - exports2.AppendBlobSealExceptionHeaders = { - serializedName: "AppendBlob_sealExceptionHeaders", - type: { - name: "Composite", - className: "AppendBlobSealExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + Uint64 = class extends Int_ { + constructor() { + super(false, 64); + } + get ArrayType() { + return BigUint64Array; + } + }; + Object.defineProperty(Int8.prototype, "ArrayType", { value: Int8Array }); + Object.defineProperty(Int16.prototype, "ArrayType", { value: Int16Array }); + Object.defineProperty(Int32.prototype, "ArrayType", { value: Int32Array }); + Object.defineProperty(Int64.prototype, "ArrayType", { value: BigInt64Array }); + Object.defineProperty(Uint8.prototype, "ArrayType", { value: Uint8Array }); + Object.defineProperty(Uint16.prototype, "ArrayType", { value: Uint16Array }); + Object.defineProperty(Uint32.prototype, "ArrayType", { value: Uint32Array }); + Object.defineProperty(Uint64.prototype, "ArrayType", { value: BigUint64Array }); + Float = class extends DataType { + constructor(precision) { + super(Type2.Float); + this.precision = precision; + } + get ArrayType() { + switch (this.precision) { + case Precision.HALF: + return Uint16Array; + case Precision.SINGLE: + return Float32Array; + case Precision.DOUBLE: + return Float64Array; + } + throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`); + } + toString() { + return `Float${this.precision << 5 || 16}`; } }; - exports2.BlockBlobUploadHeaders = { - serializedName: "BlockBlob_uploadHeaders", - type: { - name: "Composite", - className: "BlockBlobUploadHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - versionId: { - serializedName: "x-ms-version-id", - xmlName: "x-ms-version-id", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - xmlName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + _d = Symbol.toStringTag; + Float[_d] = ((proto) => { + proto.precision = null; + return proto[Symbol.toStringTag] = "Float"; + })(Float.prototype); + Float16 = class extends Float { + constructor() { + super(Precision.HALF); } }; - exports2.BlockBlobUploadExceptionHeaders = { - serializedName: "BlockBlob_uploadExceptionHeaders", - type: { - name: "Composite", - className: "BlockBlobUploadExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + Float32 = class extends Float { + constructor() { + super(Precision.SINGLE); } }; - exports2.BlockBlobPutBlobFromUrlHeaders = { - serializedName: "BlockBlob_putBlobFromUrlHeaders", - type: { - name: "Composite", - className: "BlockBlobPutBlobFromUrlHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - versionId: { - serializedName: "x-ms-version-id", - xmlName: "x-ms-version-id", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - xmlName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + Float64 = class extends Float { + constructor() { + super(Precision.DOUBLE); } }; - exports2.BlockBlobPutBlobFromUrlExceptionHeaders = { - serializedName: "BlockBlob_putBlobFromUrlExceptionHeaders", - type: { - name: "Composite", - className: "BlockBlobPutBlobFromUrlExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - }, - copySourceErrorCode: { - serializedName: "x-ms-copy-source-error-code", - xmlName: "x-ms-copy-source-error-code", - type: { - name: "String" - } - }, - copySourceStatusCode: { - serializedName: "x-ms-copy-source-status-code", - xmlName: "x-ms-copy-source-status-code", - type: { - name: "Number" - } - } - } + Object.defineProperty(Float16.prototype, "ArrayType", { value: Uint16Array }); + Object.defineProperty(Float32.prototype, "ArrayType", { value: Float32Array }); + Object.defineProperty(Float64.prototype, "ArrayType", { value: Float64Array }); + Binary2 = class extends DataType { + constructor() { + super(Type2.Binary); + } + toString() { + return `Binary`; } }; - exports2.BlockBlobStageBlockHeaders = { - serializedName: "BlockBlob_stageBlockHeaders", - type: { - name: "Composite", - className: "BlockBlobStageBlockHeaders", - modelProperties: { - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - xMsContentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", - type: { - name: "ByteArray" - } - }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - xmlName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + _e = Symbol.toStringTag; + Binary2[_e] = ((proto) => { + proto.ArrayType = Uint8Array; + return proto[Symbol.toStringTag] = "Binary"; + })(Binary2.prototype); + BinaryView2 = class extends DataType { + constructor() { + super(Type2.BinaryView); + } + toString() { + return `BinaryView`; + } + }; + _f = Symbol.toStringTag; + BinaryView2.ELEMENT_WIDTH = 16; + BinaryView2.INLINE_CAPACITY = 12; + BinaryView2.LENGTH_OFFSET = 0; + BinaryView2.INLINE_OFFSET = 4; + BinaryView2.BUFFER_INDEX_OFFSET = 8; + BinaryView2.BUFFER_OFFSET_OFFSET = 12; + BinaryView2[_f] = ((proto) => { + proto.ArrayType = Uint8Array; + return proto[Symbol.toStringTag] = "BinaryView"; + })(BinaryView2.prototype); + LargeBinary2 = class extends DataType { + constructor() { + super(Type2.LargeBinary); + } + toString() { + return `LargeBinary`; } }; - exports2.BlockBlobStageBlockExceptionHeaders = { - serializedName: "BlockBlob_stageBlockExceptionHeaders", - type: { - name: "Composite", - className: "BlockBlobStageBlockExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + _g = Symbol.toStringTag; + LargeBinary2[_g] = ((proto) => { + proto.ArrayType = Uint8Array; + proto.OffsetArrayType = BigInt64Array; + return proto[Symbol.toStringTag] = "LargeBinary"; + })(LargeBinary2.prototype); + Utf82 = class extends DataType { + constructor() { + super(Type2.Utf8); + } + toString() { + return `Utf8`; } }; - exports2.BlockBlobStageBlockFromURLHeaders = { - serializedName: "BlockBlob_stageBlockFromURLHeaders", - type: { - name: "Composite", - className: "BlockBlobStageBlockFromURLHeaders", - modelProperties: { - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" - } - }, - xMsContentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", - type: { - name: "ByteArray" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - xmlName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + _h = Symbol.toStringTag; + Utf82[_h] = ((proto) => { + proto.ArrayType = Uint8Array; + return proto[Symbol.toStringTag] = "Utf8"; + })(Utf82.prototype); + Utf8View2 = class extends DataType { + constructor() { + super(Type2.Utf8View); + } + toString() { + return `Utf8View`; } }; - exports2.BlockBlobStageBlockFromURLExceptionHeaders = { - serializedName: "BlockBlob_stageBlockFromURLExceptionHeaders", - type: { - name: "Composite", - className: "BlockBlobStageBlockFromURLExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - }, - copySourceErrorCode: { - serializedName: "x-ms-copy-source-error-code", - xmlName: "x-ms-copy-source-error-code", - type: { - name: "String" - } - }, - copySourceStatusCode: { - serializedName: "x-ms-copy-source-status-code", - xmlName: "x-ms-copy-source-status-code", - type: { - name: "Number" - } - } - } + _j = Symbol.toStringTag; + Utf8View2.ELEMENT_WIDTH = BinaryView2.ELEMENT_WIDTH; + Utf8View2.INLINE_CAPACITY = BinaryView2.INLINE_CAPACITY; + Utf8View2[_j] = ((proto) => { + proto.ArrayType = Uint8Array; + return proto[Symbol.toStringTag] = "Utf8View"; + })(Utf8View2.prototype); + LargeUtf82 = class extends DataType { + constructor() { + super(Type2.LargeUtf8); + } + toString() { + return `LargeUtf8`; } }; - exports2.BlockBlobCommitBlockListHeaders = { - serializedName: "BlockBlob_commitBlockListHeaders", - type: { - name: "Composite", - className: "BlockBlobCommitBlockListHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - contentMD5: { - serializedName: "content-md5", - xmlName: "content-md5", - type: { - name: "ByteArray" - } - }, - xMsContentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", - type: { - name: "ByteArray" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - versionId: { - serializedName: "x-ms-version-id", - xmlName: "x-ms-version-id", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - xmlName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + _k = Symbol.toStringTag; + LargeUtf82[_k] = ((proto) => { + proto.ArrayType = Uint8Array; + proto.OffsetArrayType = BigInt64Array; + return proto[Symbol.toStringTag] = "LargeUtf8"; + })(LargeUtf82.prototype); + Bool2 = class extends DataType { + constructor() { + super(Type2.Bool); + } + toString() { + return `Bool`; } }; - exports2.BlockBlobCommitBlockListExceptionHeaders = { - serializedName: "BlockBlob_commitBlockListExceptionHeaders", - type: { - name: "Composite", - className: "BlockBlobCommitBlockListExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + _l = Symbol.toStringTag; + Bool2[_l] = ((proto) => { + proto.ArrayType = Uint8Array; + return proto[Symbol.toStringTag] = "Bool"; + })(Bool2.prototype); + Decimal2 = class extends DataType { + constructor(scale, precision, bitWidth = 128) { + super(Type2.Decimal); + this.scale = scale; + this.precision = precision; + this.bitWidth = bitWidth; + } + toString() { + return `Decimal[${this.precision}e${this.scale > 0 ? `+` : ``}${this.scale}]`; } }; - exports2.BlockBlobGetBlockListHeaders = { - serializedName: "BlockBlob_getBlockListHeaders", - type: { - name: "Composite", - className: "BlockBlobGetBlockListHeaders", - modelProperties: { - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - contentType: { - serializedName: "content-type", - xmlName: "content-type", - type: { - name: "String" - } - }, - blobContentLength: { - serializedName: "x-ms-blob-content-length", - xmlName: "x-ms-blob-content-length", - type: { - name: "Number" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + _m = Symbol.toStringTag; + Decimal2[_m] = ((proto) => { + proto.scale = null; + proto.precision = null; + proto.ArrayType = Uint32Array; + return proto[Symbol.toStringTag] = "Decimal"; + })(Decimal2.prototype); + Date_ = class extends DataType { + constructor(unit) { + super(Type2.Date); + this.unit = unit; + } + toString() { + return `Date${(this.unit + 1) * 32}<${DateUnit[this.unit]}>`; + } + get ArrayType() { + return this.unit === DateUnit.DAY ? Int32Array : BigInt64Array; } }; - exports2.BlockBlobGetBlockListExceptionHeaders = { - serializedName: "BlockBlob_getBlockListExceptionHeaders", - type: { - name: "Composite", - className: "BlockBlobGetBlockListExceptionHeaders", - modelProperties: { - errorCode: { - serializedName: "x-ms-error-code", - xmlName: "x-ms-error-code", - type: { - name: "String" - } - } - } + _o = Symbol.toStringTag; + Date_[_o] = ((proto) => { + proto.unit = null; + return proto[Symbol.toStringTag] = "Date"; + })(Date_.prototype); + DateDay = class extends Date_ { + constructor() { + super(DateUnit.DAY); } }; - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/models/parameters.js -var require_parameters = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/models/parameters.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.action3 = exports2.action2 = exports2.leaseId1 = exports2.action1 = exports2.proposedLeaseId = exports2.duration = exports2.action = exports2.comp10 = exports2.sourceLeaseId = exports2.sourceContainerName = exports2.comp9 = exports2.deletedContainerVersion = exports2.deletedContainerName = exports2.comp8 = exports2.containerAcl = exports2.comp7 = exports2.comp6 = exports2.ifUnmodifiedSince = exports2.ifModifiedSince = exports2.leaseId = exports2.preventEncryptionScopeOverride = exports2.defaultEncryptionScope = exports2.access = exports2.metadata = exports2.restype2 = exports2.where = exports2.comp5 = exports2.multipartContentType = exports2.contentLength = exports2.comp4 = exports2.body = exports2.restype1 = exports2.comp3 = exports2.keyInfo = exports2.include = exports2.maxPageSize = exports2.marker = exports2.prefix = exports2.comp2 = exports2.comp1 = exports2.accept1 = exports2.requestId = exports2.version = exports2.timeoutInSeconds = exports2.comp = exports2.restype = exports2.url = exports2.accept = exports2.blobServiceProperties = exports2.contentType = void 0; - exports2.fileRequestIntent = exports2.copySourceTags = exports2.copySourceAuthorization = exports2.sourceContentMD5 = exports2.xMsRequiresSync = exports2.legalHold1 = exports2.sealBlob = exports2.blobTagsString = exports2.copySource = exports2.sourceIfTags = exports2.sourceIfNoneMatch = exports2.sourceIfMatch = exports2.sourceIfUnmodifiedSince = exports2.sourceIfModifiedSince = exports2.rehydratePriority = exports2.tier = exports2.comp14 = exports2.encryptionScope = exports2.legalHold = exports2.comp13 = exports2.immutabilityPolicyMode = exports2.immutabilityPolicyExpiry = exports2.comp12 = exports2.blobContentDisposition = exports2.blobContentLanguage = exports2.blobContentEncoding = exports2.blobContentMD5 = exports2.blobContentType = exports2.blobCacheControl = exports2.expiresOn = exports2.expiryOptions = exports2.comp11 = exports2.blobDeleteType = exports2.deleteSnapshots = exports2.ifTags = exports2.ifNoneMatch = exports2.ifMatch = exports2.encryptionAlgorithm = exports2.encryptionKeySha256 = exports2.encryptionKey = exports2.rangeGetContentCRC64 = exports2.rangeGetContentMD5 = exports2.range = exports2.versionId = exports2.snapshot = exports2.delimiter = exports2.include1 = exports2.proposedLeaseId1 = exports2.action4 = exports2.breakPeriod = void 0; - exports2.listType = exports2.comp25 = exports2.blocks = exports2.blockId = exports2.comp24 = exports2.copySourceBlobProperties = exports2.blobType2 = exports2.comp23 = exports2.sourceRange1 = exports2.appendPosition = exports2.maxSize = exports2.comp22 = exports2.blobType1 = exports2.comp21 = exports2.sequenceNumberAction = exports2.prevSnapshotUrl = exports2.prevsnapshot = exports2.comp20 = exports2.range1 = exports2.sourceContentCrc64 = exports2.sourceRange = exports2.sourceUrl = exports2.pageWrite1 = exports2.ifSequenceNumberEqualTo = exports2.ifSequenceNumberLessThan = exports2.ifSequenceNumberLessThanOrEqualTo = exports2.pageWrite = exports2.comp19 = exports2.accept2 = exports2.body1 = exports2.contentType1 = exports2.blobSequenceNumber = exports2.blobContentLength = exports2.blobType = exports2.transactionalContentCrc64 = exports2.transactionalContentMD5 = exports2.tags = exports2.comp18 = exports2.comp17 = exports2.queryRequest = exports2.tier1 = exports2.comp16 = exports2.copyId = exports2.copyActionAbortConstant = exports2.comp15 = void 0; - var mappers_js_1 = require_mappers(); - exports2.contentType = { - parameterPath: ["options", "contentType"], - mapper: { - defaultValue: "application/xml", - isConstant: true, - serializedName: "Content-Type", - type: { - name: "String" + DateMillisecond = class extends Date_ { + constructor() { + super(DateUnit.MILLISECOND); + } + }; + Time_ = class extends DataType { + constructor(unit, bitWidth) { + super(Type2.Time); + this.unit = unit; + this.bitWidth = bitWidth; + } + toString() { + return `Time${this.bitWidth}<${TimeUnit[this.unit]}>`; + } + get ArrayType() { + switch (this.bitWidth) { + case 32: + return Int32Array; + case 64: + return BigInt64Array; } + throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`); } }; - exports2.blobServiceProperties = { - parameterPath: "blobServiceProperties", - mapper: mappers_js_1.BlobServiceProperties + _p = Symbol.toStringTag; + Time_[_p] = ((proto) => { + proto.unit = null; + proto.bitWidth = null; + return proto[Symbol.toStringTag] = "Time"; + })(Time_.prototype); + TimeSecond = class extends Time_ { + constructor() { + super(TimeUnit.SECOND, 32); + } }; - exports2.accept = { - parameterPath: "accept", - mapper: { - defaultValue: "application/xml", - isConstant: true, - serializedName: "Accept", - type: { - name: "String" - } + TimeMillisecond = class extends Time_ { + constructor() { + super(TimeUnit.MILLISECOND, 32); } }; - exports2.url = { - parameterPath: "url", - mapper: { - serializedName: "url", - required: true, - xmlName: "url", - type: { - name: "String" - } - }, - skipEncoding: true + TimeMicrosecond = class extends Time_ { + constructor() { + super(TimeUnit.MICROSECOND, 64); + } }; - exports2.restype = { - parameterPath: "restype", - mapper: { - defaultValue: "service", - isConstant: true, - serializedName: "restype", - type: { - name: "String" - } + TimeNanosecond = class extends Time_ { + constructor() { + super(TimeUnit.NANOSECOND, 64); } }; - exports2.comp = { - parameterPath: "comp", - mapper: { - defaultValue: "properties", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } + Timestamp_ = class extends DataType { + constructor(unit, timezone) { + super(Type2.Timestamp); + this.unit = unit; + this.timezone = timezone; + } + toString() { + return `Timestamp<${TimeUnit[this.unit]}${this.timezone ? `, ${this.timezone}` : ``}>`; } }; - exports2.timeoutInSeconds = { - parameterPath: ["options", "timeoutInSeconds"], - mapper: { - constraints: { - InclusiveMinimum: 0 - }, - serializedName: "timeout", - xmlName: "timeout", - type: { - name: "Number" - } + _q = Symbol.toStringTag; + Timestamp_[_q] = ((proto) => { + proto.unit = null; + proto.timezone = null; + proto.ArrayType = BigInt64Array; + return proto[Symbol.toStringTag] = "Timestamp"; + })(Timestamp_.prototype); + TimestampSecond = class extends Timestamp_ { + constructor(timezone) { + super(TimeUnit.SECOND, timezone); } }; - exports2.version = { - parameterPath: "version", - mapper: { - defaultValue: "2025-11-05", - isConstant: true, - serializedName: "x-ms-version", - type: { - name: "String" - } + TimestampMillisecond = class extends Timestamp_ { + constructor(timezone) { + super(TimeUnit.MILLISECOND, timezone); } }; - exports2.requestId = { - parameterPath: ["options", "requestId"], - mapper: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } + TimestampMicrosecond = class extends Timestamp_ { + constructor(timezone) { + super(TimeUnit.MICROSECOND, timezone); } }; - exports2.accept1 = { - parameterPath: "accept", - mapper: { - defaultValue: "application/xml", - isConstant: true, - serializedName: "Accept", - type: { - name: "String" - } + TimestampNanosecond = class extends Timestamp_ { + constructor(timezone) { + super(TimeUnit.NANOSECOND, timezone); } }; - exports2.comp1 = { - parameterPath: "comp", - mapper: { - defaultValue: "stats", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } + Interval_ = class extends DataType { + constructor(unit) { + super(Type2.Interval); + this.unit = unit; + } + toString() { + return `Interval<${IntervalUnit[this.unit]}>`; } }; - exports2.comp2 = { - parameterPath: "comp", - mapper: { - defaultValue: "list", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } + _r = Symbol.toStringTag; + Interval_[_r] = ((proto) => { + proto.unit = null; + proto.ArrayType = Int32Array; + return proto[Symbol.toStringTag] = "Interval"; + })(Interval_.prototype); + IntervalDayTime = class extends Interval_ { + constructor() { + super(IntervalUnit.DAY_TIME); } }; - exports2.prefix = { - parameterPath: ["options", "prefix"], - mapper: { - serializedName: "prefix", - xmlName: "prefix", - type: { - name: "String" - } + IntervalYearMonth = class extends Interval_ { + constructor() { + super(IntervalUnit.YEAR_MONTH); } }; - exports2.marker = { - parameterPath: ["options", "marker"], - mapper: { - serializedName: "marker", - xmlName: "marker", - type: { - name: "String" - } + IntervalMonthDayNano = class extends Interval_ { + constructor() { + super(IntervalUnit.MONTH_DAY_NANO); } }; - exports2.maxPageSize = { - parameterPath: ["options", "maxPageSize"], - mapper: { - constraints: { - InclusiveMinimum: 1 - }, - serializedName: "maxresults", - xmlName: "maxresults", - type: { - name: "Number" - } + Duration2 = class extends DataType { + constructor(unit) { + super(Type2.Duration); + this.unit = unit; + } + toString() { + return `Duration<${TimeUnit[this.unit]}>`; } }; - exports2.include = { - parameterPath: ["options", "include"], - mapper: { - serializedName: "include", - xmlName: "include", - xmlElementName: "ListContainersIncludeType", - type: { - name: "Sequence", - element: { - type: { - name: "Enum", - allowedValues: ["metadata", "deleted", "system"] - } - } - } - }, - collectionFormat: "CSV" + _s = Symbol.toStringTag; + Duration2[_s] = ((proto) => { + proto.unit = null; + proto.ArrayType = BigInt64Array; + return proto[Symbol.toStringTag] = "Duration"; + })(Duration2.prototype); + DurationSecond = class extends Duration2 { + constructor() { + super(TimeUnit.SECOND); + } }; - exports2.keyInfo = { - parameterPath: "keyInfo", - mapper: mappers_js_1.KeyInfo + DurationMillisecond = class extends Duration2 { + constructor() { + super(TimeUnit.MILLISECOND); + } }; - exports2.comp3 = { - parameterPath: "comp", - mapper: { - defaultValue: "userdelegationkey", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } + DurationMicrosecond = class extends Duration2 { + constructor() { + super(TimeUnit.MICROSECOND); } }; - exports2.restype1 = { - parameterPath: "restype", - mapper: { - defaultValue: "account", - isConstant: true, - serializedName: "restype", - type: { - name: "String" - } + DurationNanosecond = class extends Duration2 { + constructor() { + super(TimeUnit.NANOSECOND); } }; - exports2.body = { - parameterPath: "body", - mapper: { - serializedName: "body", - required: true, - xmlName: "body", - type: { - name: "Stream" - } + List2 = class extends DataType { + constructor(child) { + super(Type2.List); + this.children = [child]; + } + toString() { + return `List<${this.valueType}>`; + } + get valueType() { + return this.children[0].type; + } + get valueField() { + return this.children[0]; + } + get ArrayType() { + return this.valueType.ArrayType; } }; - exports2.comp4 = { - parameterPath: "comp", - mapper: { - defaultValue: "batch", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } + _t = Symbol.toStringTag; + List2[_t] = ((proto) => { + proto.children = null; + return proto[Symbol.toStringTag] = "List"; + })(List2.prototype); + LargeList2 = class extends DataType { + constructor(child) { + super(Type2.LargeList); + this.children = [child]; + } + toString() { + return `LargeList<${this.valueType}>`; + } + get valueType() { + return this.children[0].type; + } + get valueField() { + return this.children[0]; + } + get ArrayType() { + return this.valueType.ArrayType; } }; - exports2.contentLength = { - parameterPath: "contentLength", - mapper: { - serializedName: "Content-Length", - required: true, - xmlName: "Content-Length", - type: { - name: "Number" + _u = Symbol.toStringTag; + LargeList2[_u] = ((proto) => { + proto.children = null; + proto.OffsetArrayType = BigInt64Array; + return proto[Symbol.toStringTag] = "LargeList"; + })(LargeList2.prototype); + Struct = class extends DataType { + constructor(children) { + super(Type2.Struct); + this.children = children; + } + toString() { + return `Struct<{${this.children.map((f) => `${f.name}:${f.type}`).join(`, `)}}>`; + } + }; + _v = Symbol.toStringTag; + Struct[_v] = ((proto) => { + proto.children = null; + return proto[Symbol.toStringTag] = "Struct"; + })(Struct.prototype); + Union_ = class extends DataType { + constructor(mode, typeIds, children) { + super(Type2.Union); + this.mode = mode; + this.children = children; + this.typeIds = typeIds = Int32Array.from(typeIds); + this.typeIdToChildIndex = typeIds.reduce((typeIdToChildIndex, typeId, idx) => (typeIdToChildIndex[typeId] = idx) && typeIdToChildIndex || typeIdToChildIndex, /* @__PURE__ */ Object.create(null)); + } + toString() { + return `${this[Symbol.toStringTag]}<${this.children.map((x) => `${x.type}`).join(` | `)}>`; + } + }; + _w = Symbol.toStringTag; + Union_[_w] = ((proto) => { + proto.mode = null; + proto.typeIds = null; + proto.children = null; + proto.typeIdToChildIndex = null; + proto.ArrayType = Int8Array; + return proto[Symbol.toStringTag] = "Union"; + })(Union_.prototype); + DenseUnion = class extends Union_ { + constructor(typeIds, children) { + super(UnionMode.Dense, typeIds, children); + } + }; + SparseUnion = class extends Union_ { + constructor(typeIds, children) { + super(UnionMode.Sparse, typeIds, children); + } + }; + FixedSizeBinary2 = class extends DataType { + constructor(byteWidth) { + super(Type2.FixedSizeBinary); + this.byteWidth = byteWidth; + } + toString() { + return `FixedSizeBinary[${this.byteWidth}]`; + } + }; + _x = Symbol.toStringTag; + FixedSizeBinary2[_x] = ((proto) => { + proto.byteWidth = null; + proto.ArrayType = Uint8Array; + return proto[Symbol.toStringTag] = "FixedSizeBinary"; + })(FixedSizeBinary2.prototype); + FixedSizeList2 = class extends DataType { + constructor(listSize, child) { + super(Type2.FixedSizeList); + this.listSize = listSize; + this.children = [child]; + } + get valueType() { + return this.children[0].type; + } + get valueField() { + return this.children[0]; + } + get ArrayType() { + return this.valueType.ArrayType; + } + toString() { + return `FixedSizeList[${this.listSize}]<${this.valueType}>`; + } + }; + _y = Symbol.toStringTag; + FixedSizeList2[_y] = ((proto) => { + proto.children = null; + proto.listSize = null; + return proto[Symbol.toStringTag] = "FixedSizeList"; + })(FixedSizeList2.prototype); + Map_ = class extends DataType { + constructor(entries, keysSorted = false) { + var _1, _2, _3; + super(Type2.Map); + this.children = [entries]; + this.keysSorted = keysSorted; + if (entries) { + entries["name"] = "entries"; + if ((_1 = entries === null || entries === void 0 ? void 0 : entries.type) === null || _1 === void 0 ? void 0 : _1.children) { + const key = (_2 = entries === null || entries === void 0 ? void 0 : entries.type) === null || _2 === void 0 ? void 0 : _2.children[0]; + if (key) { + key["name"] = "key"; + } + const val = (_3 = entries === null || entries === void 0 ? void 0 : entries.type) === null || _3 === void 0 ? void 0 : _3.children[1]; + if (val) { + val["name"] = "value"; + } + } } } - }; - exports2.multipartContentType = { - parameterPath: "multipartContentType", - mapper: { - serializedName: "Content-Type", - required: true, - xmlName: "Content-Type", - type: { - name: "String" + get keyType() { + return this.children[0].type.children[0].type; + } + get valueType() { + return this.children[0].type.children[1].type; + } + get childType() { + return this.children[0].type; + } + toString() { + return `Map<{${this.children[0].type.children.map((f) => `${f.name}:${f.type}`).join(`, `)}}>`; + } + }; + _z = Symbol.toStringTag; + Map_[_z] = ((proto) => { + proto.children = null; + proto.keysSorted = null; + return proto[Symbol.toStringTag] = "Map_"; + })(Map_.prototype); + getId = /* @__PURE__ */ ((atomicDictionaryId) => () => ++atomicDictionaryId)(-1); + Dictionary = class extends DataType { + constructor(dictionary, indices, id, isOrdered) { + super(Type2.Dictionary); + this.indices = indices; + this.dictionary = dictionary; + this.isOrdered = isOrdered || false; + this.id = id == null ? getId() : bigIntToNumber(id); + } + get children() { + return this.dictionary.children; + } + get valueType() { + return this.dictionary; + } + get ArrayType() { + return this.dictionary.ArrayType; + } + toString() { + return `Dictionary<${this.indices}, ${this.dictionary}>`; + } + }; + _0 = Symbol.toStringTag; + Dictionary[_0] = ((proto) => { + proto.id = null; + proto.indices = null; + proto.isOrdered = null; + proto.dictionary = null; + return proto[Symbol.toStringTag] = "Dictionary"; + })(Dictionary.prototype); + } +}); + +// node_modules/apache-arrow/visitor.mjs +function getVisitFn(visitor, node, throwIfNotFound = true) { + if (typeof node === "number") { + return getVisitFnByTypeId(visitor, node, throwIfNotFound); + } + if (typeof node === "string" && node in Type2) { + return getVisitFnByTypeId(visitor, Type2[node], throwIfNotFound); + } + if (node && node instanceof DataType) { + return getVisitFnByTypeId(visitor, inferDType(node), throwIfNotFound); + } + if ((node === null || node === void 0 ? void 0 : node.type) && node.type instanceof DataType) { + return getVisitFnByTypeId(visitor, inferDType(node.type), throwIfNotFound); + } + return getVisitFnByTypeId(visitor, Type2.NONE, throwIfNotFound); +} +function getVisitFnByTypeId(visitor, dtype, throwIfNotFound = true) { + let fn = null; + switch (dtype) { + case Type2.Null: + fn = visitor.visitNull; + break; + case Type2.Bool: + fn = visitor.visitBool; + break; + case Type2.Int: + fn = visitor.visitInt; + break; + case Type2.Int8: + fn = visitor.visitInt8 || visitor.visitInt; + break; + case Type2.Int16: + fn = visitor.visitInt16 || visitor.visitInt; + break; + case Type2.Int32: + fn = visitor.visitInt32 || visitor.visitInt; + break; + case Type2.Int64: + fn = visitor.visitInt64 || visitor.visitInt; + break; + case Type2.Uint8: + fn = visitor.visitUint8 || visitor.visitInt; + break; + case Type2.Uint16: + fn = visitor.visitUint16 || visitor.visitInt; + break; + case Type2.Uint32: + fn = visitor.visitUint32 || visitor.visitInt; + break; + case Type2.Uint64: + fn = visitor.visitUint64 || visitor.visitInt; + break; + case Type2.Float: + fn = visitor.visitFloat; + break; + case Type2.Float16: + fn = visitor.visitFloat16 || visitor.visitFloat; + break; + case Type2.Float32: + fn = visitor.visitFloat32 || visitor.visitFloat; + break; + case Type2.Float64: + fn = visitor.visitFloat64 || visitor.visitFloat; + break; + case Type2.Utf8: + fn = visitor.visitUtf8; + break; + case Type2.LargeUtf8: + fn = visitor.visitLargeUtf8; + break; + case Type2.Utf8View: + fn = visitor.visitUtf8View || visitor.visitUtf8; + break; + case Type2.Binary: + fn = visitor.visitBinary; + break; + case Type2.LargeBinary: + fn = visitor.visitLargeBinary; + break; + case Type2.BinaryView: + fn = visitor.visitBinaryView || visitor.visitBinary; + break; + case Type2.FixedSizeBinary: + fn = visitor.visitFixedSizeBinary; + break; + case Type2.Date: + fn = visitor.visitDate; + break; + case Type2.DateDay: + fn = visitor.visitDateDay || visitor.visitDate; + break; + case Type2.DateMillisecond: + fn = visitor.visitDateMillisecond || visitor.visitDate; + break; + case Type2.Timestamp: + fn = visitor.visitTimestamp; + break; + case Type2.TimestampSecond: + fn = visitor.visitTimestampSecond || visitor.visitTimestamp; + break; + case Type2.TimestampMillisecond: + fn = visitor.visitTimestampMillisecond || visitor.visitTimestamp; + break; + case Type2.TimestampMicrosecond: + fn = visitor.visitTimestampMicrosecond || visitor.visitTimestamp; + break; + case Type2.TimestampNanosecond: + fn = visitor.visitTimestampNanosecond || visitor.visitTimestamp; + break; + case Type2.Time: + fn = visitor.visitTime; + break; + case Type2.TimeSecond: + fn = visitor.visitTimeSecond || visitor.visitTime; + break; + case Type2.TimeMillisecond: + fn = visitor.visitTimeMillisecond || visitor.visitTime; + break; + case Type2.TimeMicrosecond: + fn = visitor.visitTimeMicrosecond || visitor.visitTime; + break; + case Type2.TimeNanosecond: + fn = visitor.visitTimeNanosecond || visitor.visitTime; + break; + case Type2.Decimal: + fn = visitor.visitDecimal; + break; + case Type2.List: + fn = visitor.visitList; + break; + case Type2.LargeList: + fn = visitor.visitLargeList; + break; + case Type2.Struct: + fn = visitor.visitStruct; + break; + case Type2.Union: + fn = visitor.visitUnion; + break; + case Type2.DenseUnion: + fn = visitor.visitDenseUnion || visitor.visitUnion; + break; + case Type2.SparseUnion: + fn = visitor.visitSparseUnion || visitor.visitUnion; + break; + case Type2.Dictionary: + fn = visitor.visitDictionary; + break; + case Type2.Interval: + fn = visitor.visitInterval; + break; + case Type2.IntervalDayTime: + fn = visitor.visitIntervalDayTime || visitor.visitInterval; + break; + case Type2.IntervalYearMonth: + fn = visitor.visitIntervalYearMonth || visitor.visitInterval; + break; + case Type2.IntervalMonthDayNano: + fn = visitor.visitIntervalMonthDayNano || visitor.visitInterval; + break; + case Type2.Duration: + fn = visitor.visitDuration; + break; + case Type2.DurationSecond: + fn = visitor.visitDurationSecond || visitor.visitDuration; + break; + case Type2.DurationMillisecond: + fn = visitor.visitDurationMillisecond || visitor.visitDuration; + break; + case Type2.DurationMicrosecond: + fn = visitor.visitDurationMicrosecond || visitor.visitDuration; + break; + case Type2.DurationNanosecond: + fn = visitor.visitDurationNanosecond || visitor.visitDuration; + break; + case Type2.FixedSizeList: + fn = visitor.visitFixedSizeList; + break; + case Type2.Map: + fn = visitor.visitMap; + break; + } + if (typeof fn === "function") + return fn; + if (!throwIfNotFound) + return () => null; + throw new Error(`Unrecognized type '${Type2[dtype]}'`); +} +function inferDType(type) { + switch (type.typeId) { + case Type2.Null: + return Type2.Null; + case Type2.Int: { + const { bitWidth, isSigned } = type; + switch (bitWidth) { + case 8: + return isSigned ? Type2.Int8 : Type2.Uint8; + case 16: + return isSigned ? Type2.Int16 : Type2.Uint16; + case 32: + return isSigned ? Type2.Int32 : Type2.Uint32; + case 64: + return isSigned ? Type2.Int64 : Type2.Uint64; + } + return Type2.Int; + } + case Type2.Float: + switch (type.precision) { + case Precision.HALF: + return Type2.Float16; + case Precision.SINGLE: + return Type2.Float32; + case Precision.DOUBLE: + return Type2.Float64; + } + return Type2.Float; + case Type2.Binary: + return Type2.Binary; + case Type2.LargeBinary: + return Type2.LargeBinary; + case Type2.BinaryView: + return Type2.BinaryView; + case Type2.Utf8: + return Type2.Utf8; + case Type2.LargeUtf8: + return Type2.LargeUtf8; + case Type2.Utf8View: + return Type2.Utf8View; + case Type2.Bool: + return Type2.Bool; + case Type2.Decimal: + return Type2.Decimal; + case Type2.Time: + switch (type.unit) { + case TimeUnit.SECOND: + return Type2.TimeSecond; + case TimeUnit.MILLISECOND: + return Type2.TimeMillisecond; + case TimeUnit.MICROSECOND: + return Type2.TimeMicrosecond; + case TimeUnit.NANOSECOND: + return Type2.TimeNanosecond; + } + return Type2.Time; + case Type2.Timestamp: + switch (type.unit) { + case TimeUnit.SECOND: + return Type2.TimestampSecond; + case TimeUnit.MILLISECOND: + return Type2.TimestampMillisecond; + case TimeUnit.MICROSECOND: + return Type2.TimestampMicrosecond; + case TimeUnit.NANOSECOND: + return Type2.TimestampNanosecond; + } + return Type2.Timestamp; + case Type2.Date: + switch (type.unit) { + case DateUnit.DAY: + return Type2.DateDay; + case DateUnit.MILLISECOND: + return Type2.DateMillisecond; + } + return Type2.Date; + case Type2.Interval: + switch (type.unit) { + case IntervalUnit.DAY_TIME: + return Type2.IntervalDayTime; + case IntervalUnit.YEAR_MONTH: + return Type2.IntervalYearMonth; + case IntervalUnit.MONTH_DAY_NANO: + return Type2.IntervalMonthDayNano; + } + return Type2.Interval; + case Type2.Duration: + switch (type.unit) { + case TimeUnit.SECOND: + return Type2.DurationSecond; + case TimeUnit.MILLISECOND: + return Type2.DurationMillisecond; + case TimeUnit.MICROSECOND: + return Type2.DurationMicrosecond; + case TimeUnit.NANOSECOND: + return Type2.DurationNanosecond; + } + return Type2.Duration; + case Type2.Map: + return Type2.Map; + case Type2.List: + return Type2.List; + case Type2.LargeList: + return Type2.LargeList; + case Type2.Struct: + return Type2.Struct; + case Type2.Union: + switch (type.mode) { + case UnionMode.Dense: + return Type2.DenseUnion; + case UnionMode.Sparse: + return Type2.SparseUnion; + } + return Type2.Union; + case Type2.FixedSizeBinary: + return Type2.FixedSizeBinary; + case Type2.FixedSizeList: + return Type2.FixedSizeList; + case Type2.Dictionary: + return Type2.Dictionary; + } + throw new Error(`Unrecognized type '${Type2[type.typeId]}'`); +} +var Visitor; +var init_visitor = __esm({ + "node_modules/apache-arrow/visitor.mjs"() { + init_enum(); + init_type2(); + Visitor = class { + visitMany(nodes, ...args) { + return nodes.map((node, i) => this.visit(node, ...args.map((x) => x[i]))); + } + visit(...args) { + return this.getVisitFn(args[0], false).apply(this, args); + } + getVisitFn(node, throwIfNotFound = true) { + return getVisitFn(this, node, throwIfNotFound); + } + getVisitFnByTypeId(typeId, throwIfNotFound = true) { + return getVisitFnByTypeId(this, typeId, throwIfNotFound); + } + visitNull(_node, ..._args) { + return null; + } + visitBool(_node, ..._args) { + return null; + } + visitInt(_node, ..._args) { + return null; + } + visitFloat(_node, ..._args) { + return null; + } + visitUtf8(_node, ..._args) { + return null; + } + visitLargeUtf8(_node, ..._args) { + return null; + } + visitUtf8View(_node, ..._args) { + return null; + } + visitBinary(_node, ..._args) { + return null; + } + visitLargeBinary(_node, ..._args) { + return null; + } + visitBinaryView(_node, ..._args) { + return null; + } + visitFixedSizeBinary(_node, ..._args) { + return null; + } + visitDate(_node, ..._args) { + return null; + } + visitTimestamp(_node, ..._args) { + return null; + } + visitTime(_node, ..._args) { + return null; + } + visitDecimal(_node, ..._args) { + return null; + } + visitList(_node, ..._args) { + return null; + } + visitLargeList(_node, ..._args) { + return null; + } + visitStruct(_node, ..._args) { + return null; + } + visitUnion(_node, ..._args) { + return null; + } + visitDictionary(_node, ..._args) { + return null; + } + visitInterval(_node, ..._args) { + return null; + } + visitDuration(_node, ..._args) { + return null; + } + visitFixedSizeList(_node, ..._args) { + return null; + } + visitMap(_node, ..._args) { + return null; + } + }; + Visitor.prototype.visitInt8 = null; + Visitor.prototype.visitInt16 = null; + Visitor.prototype.visitInt32 = null; + Visitor.prototype.visitInt64 = null; + Visitor.prototype.visitUint8 = null; + Visitor.prototype.visitUint16 = null; + Visitor.prototype.visitUint32 = null; + Visitor.prototype.visitUint64 = null; + Visitor.prototype.visitFloat16 = null; + Visitor.prototype.visitFloat32 = null; + Visitor.prototype.visitFloat64 = null; + Visitor.prototype.visitDateDay = null; + Visitor.prototype.visitDateMillisecond = null; + Visitor.prototype.visitTimestampSecond = null; + Visitor.prototype.visitTimestampMillisecond = null; + Visitor.prototype.visitTimestampMicrosecond = null; + Visitor.prototype.visitTimestampNanosecond = null; + Visitor.prototype.visitTimeSecond = null; + Visitor.prototype.visitTimeMillisecond = null; + Visitor.prototype.visitTimeMicrosecond = null; + Visitor.prototype.visitTimeNanosecond = null; + Visitor.prototype.visitDenseUnion = null; + Visitor.prototype.visitSparseUnion = null; + Visitor.prototype.visitIntervalDayTime = null; + Visitor.prototype.visitIntervalYearMonth = null; + Visitor.prototype.visitIntervalMonthDayNano = null; + Visitor.prototype.visitDuration = null; + Visitor.prototype.visitDurationSecond = null; + Visitor.prototype.visitDurationMillisecond = null; + Visitor.prototype.visitDurationMicrosecond = null; + Visitor.prototype.visitDurationNanosecond = null; + } +}); + +// node_modules/apache-arrow/util/math.mjs +var math_exports = {}; +__export(math_exports, { + float64ToUint16: () => float64ToUint16, + uint16ToFloat64: () => uint16ToFloat64 +}); +function uint16ToFloat64(h) { + const expo = (h & 31744) >> 10; + const sigf = (h & 1023) / 1024; + const sign = Math.pow(-1, (h & 32768) >> 15); + switch (expo) { + case 31: + return sign * (sigf ? Number.NaN : 1 / 0); + case 0: + return sign * (sigf ? 6103515625e-14 * sigf : 0); + } + return sign * Math.pow(2, expo - 15) * (1 + sigf); +} +function float64ToUint16(d) { + if (d !== d) { + return 32256; + } + f64[0] = d; + const sign = (u32[1] & 2147483648) >> 16 & 65535; + let expo = u32[1] & 2146435072, sigf = 0; + if (expo >= 1089470464) { + if (u32[0] > 0) { + expo = 31744; + } else { + expo = (expo & 2080374784) >> 16; + sigf = (u32[1] & 1048575) >> 10; + } + } else if (expo <= 1056964608) { + sigf = 1048576 + (u32[1] & 1048575); + sigf = 1048576 + (sigf << (expo >> 20) - 998) >> 21; + expo = 0; + } else { + expo = expo - 1056964608 >> 10; + sigf = (u32[1] & 1048575) + 512 >> 10; + } + return sign | expo | sigf & 65535; +} +var f64, u32; +var init_math = __esm({ + "node_modules/apache-arrow/util/math.mjs"() { + f64 = new Float64Array(1); + u32 = new Uint32Array(f64.buffer); + } +}); + +// node_modules/apache-arrow/visitor/set.mjs +function wrapSet(fn) { + return (data, _1, _2) => { + if (data.setValid(_1, _2 != null)) { + return fn(data, _1, _2); + } + }; +} +var SetVisitor, setEpochMsToDays, setVariableWidthBytes, setBool, setInt, setFloat, setFloat16, setAnyFloat, setDateDay, setDateMillisecond, setFixedSizeBinary, setBinary, ensureWritableVariadicBuffers, setBinaryViewBytes, setBinaryView, setUtf8, setUtf8View, setDate, setTimestampSecond, setTimestampMillisecond, setTimestampMicrosecond, setTimestampNanosecond, setTimestamp, setTimeSecond, setTimeMillisecond, setTimeMicrosecond, setTimeNanosecond, setTime, setDecimal, setList, setMap, _setStructArrayValue, _setStructVectorValue, _setStructMapValue, _setStructObjectValue, setStruct, setUnion, setDenseUnion, setSparseUnion, setDictionary, setIntervalValue, setIntervalDayTime, setIntervalYearMonth, setIntervalMonthDayNano, setDurationSecond, setDurationMillisecond, setDurationMicrosecond, setDurationNanosecond, setDuration, setFixedSizeList, instance; +var init_set = __esm({ + "node_modules/apache-arrow/visitor/set.mjs"() { + init_vector2(); + init_visitor(); + init_bigint(); + init_utf8(); + init_math(); + init_enum(); + init_type2(); + SetVisitor = class extends Visitor { + }; + setEpochMsToDays = (data, index2, epochMs) => { + data[index2] = Math.floor(epochMs / 864e5); + }; + setVariableWidthBytes = (values, valueOffsets, index2, value) => { + if (index2 + 1 < valueOffsets.length) { + const x = bigIntToNumber(valueOffsets[index2]); + const y = bigIntToNumber(valueOffsets[index2 + 1]); + values.set(value.subarray(0, y - x), x); + } + }; + setBool = ({ offset, values }, index2, val) => { + const idx = offset + index2; + val ? values[idx >> 3] |= 1 << idx % 8 : values[idx >> 3] &= ~(1 << idx % 8); + }; + setInt = ({ values }, index2, value) => { + values[index2] = value; + }; + setFloat = ({ values }, index2, value) => { + values[index2] = value; + }; + setFloat16 = ({ values }, index2, value) => { + values[index2] = float64ToUint16(value); + }; + setAnyFloat = (data, index2, value) => { + switch (data.type.precision) { + case Precision.HALF: + return setFloat16(data, index2, value); + case Precision.SINGLE: + case Precision.DOUBLE: + return setFloat(data, index2, value); + } + }; + setDateDay = ({ values }, index2, value) => { + setEpochMsToDays(values, index2, value.valueOf()); + }; + setDateMillisecond = ({ values }, index2, value) => { + values[index2] = BigInt(value); + }; + setFixedSizeBinary = ({ stride, values }, index2, value) => { + values.set(value.subarray(0, stride), stride * index2); + }; + setBinary = ({ values, valueOffsets }, index2, value) => setVariableWidthBytes(values, valueOffsets, index2, value); + ensureWritableVariadicBuffers = (data) => { + let buffers = data.variadicBuffers; + if (!Array.isArray(buffers) || Object.isFrozen(buffers)) { + buffers = Array.from(buffers); + data.variadicBuffers = buffers; + } + return buffers; + }; + setBinaryViewBytes = (data, index2, bytes) => { + var _a6, _b2, _c2, _d2; + const views = data.values; + if (!views) { + throw new Error("BinaryView data is missing view buffer"); + } + const elementWidth = BinaryView2.ELEMENT_WIDTH; + const viewOffset = index2 * elementWidth; + const end = viewOffset + elementWidth; + if (viewOffset < 0 || end > views.length) { + throw new RangeError(`BinaryView index ${index2} out of bounds`); + } + views.fill(0, viewOffset, end); + const view = new DataView(views.buffer, views.byteOffset + viewOffset, elementWidth); + const length = bytes.length; + view.setInt32(BinaryView2.LENGTH_OFFSET, length, true); + if (length <= BinaryView2.INLINE_CAPACITY) { + views.set(bytes, viewOffset + BinaryView2.INLINE_OFFSET); + return; + } + const prefix = ((_a6 = bytes[0]) !== null && _a6 !== void 0 ? _a6 : 0) | ((_b2 = bytes[1]) !== null && _b2 !== void 0 ? _b2 : 0) << 8 | ((_c2 = bytes[2]) !== null && _c2 !== void 0 ? _c2 : 0) << 16 | ((_d2 = bytes[3]) !== null && _d2 !== void 0 ? _d2 : 0) << 24; + view.setUint32(BinaryView2.INLINE_OFFSET, prefix >>> 0, true); + const buffers = ensureWritableVariadicBuffers(data); + const copy = bytes.slice(); + const bufferIndex = buffers.push(copy) - 1; + view.setInt32(BinaryView2.BUFFER_INDEX_OFFSET, bufferIndex, true); + view.setInt32(BinaryView2.BUFFER_OFFSET_OFFSET, 0, true); + }; + setBinaryView = (data, index2, value) => { + const bytes = value instanceof Uint8Array ? value : new Uint8Array(value); + setBinaryViewBytes(data, index2, bytes); + }; + setUtf8 = ({ values, valueOffsets }, index2, value) => setVariableWidthBytes(values, valueOffsets, index2, encodeUtf8(value)); + setUtf8View = (data, index2, value) => { + const bytes = encodeUtf8(value); + setBinaryViewBytes(data, index2, bytes); + }; + setDate = (data, index2, value) => { + data.type.unit === DateUnit.DAY ? setDateDay(data, index2, value) : setDateMillisecond(data, index2, value); + }; + setTimestampSecond = ({ values }, index2, value) => { + values[index2] = BigInt(value / 1e3); + }; + setTimestampMillisecond = ({ values }, index2, value) => { + values[index2] = BigInt(value); + }; + setTimestampMicrosecond = ({ values }, index2, value) => { + values[index2] = BigInt(value * 1e3); + }; + setTimestampNanosecond = ({ values }, index2, value) => { + values[index2] = BigInt(value * 1e6); + }; + setTimestamp = (data, index2, value) => { + switch (data.type.unit) { + case TimeUnit.SECOND: + return setTimestampSecond(data, index2, value); + case TimeUnit.MILLISECOND: + return setTimestampMillisecond(data, index2, value); + case TimeUnit.MICROSECOND: + return setTimestampMicrosecond(data, index2, value); + case TimeUnit.NANOSECOND: + return setTimestampNanosecond(data, index2, value); + } + }; + setTimeSecond = ({ values }, index2, value) => { + values[index2] = value; + }; + setTimeMillisecond = ({ values }, index2, value) => { + values[index2] = value; + }; + setTimeMicrosecond = ({ values }, index2, value) => { + values[index2] = value; + }; + setTimeNanosecond = ({ values }, index2, value) => { + values[index2] = value; + }; + setTime = (data, index2, value) => { + switch (data.type.unit) { + case TimeUnit.SECOND: + return setTimeSecond(data, index2, value); + case TimeUnit.MILLISECOND: + return setTimeMillisecond(data, index2, value); + case TimeUnit.MICROSECOND: + return setTimeMicrosecond(data, index2, value); + case TimeUnit.NANOSECOND: + return setTimeNanosecond(data, index2, value); + } + }; + setDecimal = ({ values, stride }, index2, value) => { + values.set(value.subarray(0, stride), stride * index2); + }; + setList = (data, index2, value) => { + const values = data.children[0]; + const valueOffsets = data.valueOffsets; + const set = instance.getVisitFn(values); + const begin = bigIntToNumber(valueOffsets[index2]); + const end = bigIntToNumber(valueOffsets[index2 + 1]); + if (Array.isArray(value)) { + for (let idx = -1, itr = begin; itr < end; ) { + set(values, itr++, value[++idx]); } - } - }; - exports2.comp5 = { - parameterPath: "comp", - mapper: { - defaultValue: "blobs", - isConstant: true, - serializedName: "comp", - type: { - name: "String" + } else { + for (let idx = -1, itr = begin; itr < end; ) { + set(values, itr++, value.get(++idx)); } } }; - exports2.where = { - parameterPath: ["options", "where"], - mapper: { - serializedName: "where", - xmlName: "where", - type: { - name: "String" - } + setMap = (data, index2, value) => { + const values = data.children[0]; + const { valueOffsets } = data; + const set = instance.getVisitFn(values); + let { [index2]: idx, [index2 + 1]: end } = valueOffsets; + const entries = value instanceof Map ? value.entries() : Object.entries(value); + for (const val of entries) { + set(values, idx, val); + if (++idx >= end) + break; } }; - exports2.restype2 = { - parameterPath: "restype", - mapper: { - defaultValue: "container", - isConstant: true, - serializedName: "restype", - type: { - name: "String" - } - } + _setStructArrayValue = (o, v) => (set, c, _2, i) => c && set(c, o, v[i]); + _setStructVectorValue = (o, v) => (set, c, _2, i) => c && set(c, o, v.get(i)); + _setStructMapValue = (o, v) => (set, c, f, _2) => c && set(c, o, v.get(f.name)); + _setStructObjectValue = (o, v) => (set, c, f, _2) => c && set(c, o, v[f.name]); + setStruct = (data, index2, value) => { + const childSetters = data.type.children.map((f) => instance.getVisitFn(f.type)); + const set = value instanceof Map ? _setStructMapValue(index2, value) : value instanceof Vector ? _setStructVectorValue(index2, value) : Array.isArray(value) ? _setStructArrayValue(index2, value) : _setStructObjectValue(index2, value); + data.type.children.forEach((f, i) => set(childSetters[i], data.children[i], f, i)); }; - exports2.metadata = { - parameterPath: ["options", "metadata"], - mapper: { - serializedName: "x-ms-meta", - xmlName: "x-ms-meta", - headerCollectionPrefix: "x-ms-meta-", - type: { - name: "Dictionary", - value: { type: { name: "String" } } - } - } + setUnion = (data, index2, value) => { + data.type.mode === UnionMode.Dense ? setDenseUnion(data, index2, value) : setSparseUnion(data, index2, value); }; - exports2.access = { - parameterPath: ["options", "access"], - mapper: { - serializedName: "x-ms-blob-public-access", - xmlName: "x-ms-blob-public-access", - type: { - name: "Enum", - allowedValues: ["container", "blob"] - } - } + setDenseUnion = (data, index2, value) => { + const childIndex = data.type.typeIdToChildIndex[data.typeIds[index2]]; + const child = data.children[childIndex]; + instance.visit(child, data.valueOffsets[index2], value); }; - exports2.defaultEncryptionScope = { - parameterPath: [ - "options", - "containerEncryptionScope", - "defaultEncryptionScope" - ], - mapper: { - serializedName: "x-ms-default-encryption-scope", - xmlName: "x-ms-default-encryption-scope", - type: { - name: "String" - } - } + setSparseUnion = (data, index2, value) => { + const childIndex = data.type.typeIdToChildIndex[data.typeIds[index2]]; + const child = data.children[childIndex]; + instance.visit(child, index2, value); }; - exports2.preventEncryptionScopeOverride = { - parameterPath: [ - "options", - "containerEncryptionScope", - "preventEncryptionScopeOverride" - ], - mapper: { - serializedName: "x-ms-deny-encryption-scope-override", - xmlName: "x-ms-deny-encryption-scope-override", - type: { - name: "Boolean" - } - } + setDictionary = (data, index2, value) => { + var _a6; + (_a6 = data.dictionary) === null || _a6 === void 0 ? void 0 : _a6.set(data.values[index2], value); }; - exports2.leaseId = { - parameterPath: ["options", "leaseAccessConditions", "leaseId"], - mapper: { - serializedName: "x-ms-lease-id", - xmlName: "x-ms-lease-id", - type: { - name: "String" - } + setIntervalValue = (data, index2, value) => { + switch (data.type.unit) { + case IntervalUnit.YEAR_MONTH: + return setIntervalYearMonth(data, index2, value); + case IntervalUnit.DAY_TIME: + return setIntervalDayTime(data, index2, value); + case IntervalUnit.MONTH_DAY_NANO: + return setIntervalMonthDayNano(data, index2, value); } }; - exports2.ifModifiedSince = { - parameterPath: ["options", "modifiedAccessConditions", "ifModifiedSince"], - mapper: { - serializedName: "If-Modified-Since", - xmlName: "If-Modified-Since", - type: { - name: "DateTimeRfc1123" - } - } + setIntervalDayTime = ({ values }, index2, value) => { + values.set(value.subarray(0, 2), 2 * index2); }; - exports2.ifUnmodifiedSince = { - parameterPath: ["options", "modifiedAccessConditions", "ifUnmodifiedSince"], - mapper: { - serializedName: "If-Unmodified-Since", - xmlName: "If-Unmodified-Since", - type: { - name: "DateTimeRfc1123" - } - } + setIntervalYearMonth = ({ values }, index2, value) => { + values[index2] = value[0] * 12 + value[1] % 12; }; - exports2.comp6 = { - parameterPath: "comp", - mapper: { - defaultValue: "metadata", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } - } + setIntervalMonthDayNano = ({ values, stride }, index2, value) => { + values.set(value.subarray(0, stride), stride * index2); }; - exports2.comp7 = { - parameterPath: "comp", - mapper: { - defaultValue: "acl", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } - } + setDurationSecond = ({ values }, index2, value) => { + values[index2] = value; }; - exports2.containerAcl = { - parameterPath: ["options", "containerAcl"], - mapper: { - serializedName: "containerAcl", - xmlName: "SignedIdentifiers", - xmlIsWrapped: true, - xmlElementName: "SignedIdentifier", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "SignedIdentifier" - } - } - } - } + setDurationMillisecond = ({ values }, index2, value) => { + values[index2] = value; }; - exports2.comp8 = { - parameterPath: "comp", - mapper: { - defaultValue: "undelete", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } - } + setDurationMicrosecond = ({ values }, index2, value) => { + values[index2] = value; }; - exports2.deletedContainerName = { - parameterPath: ["options", "deletedContainerName"], - mapper: { - serializedName: "x-ms-deleted-container-name", - xmlName: "x-ms-deleted-container-name", - type: { - name: "String" - } - } + setDurationNanosecond = ({ values }, index2, value) => { + values[index2] = value; }; - exports2.deletedContainerVersion = { - parameterPath: ["options", "deletedContainerVersion"], - mapper: { - serializedName: "x-ms-deleted-container-version", - xmlName: "x-ms-deleted-container-version", - type: { - name: "String" - } + setDuration = (data, index2, value) => { + switch (data.type.unit) { + case TimeUnit.SECOND: + return setDurationSecond(data, index2, value); + case TimeUnit.MILLISECOND: + return setDurationMillisecond(data, index2, value); + case TimeUnit.MICROSECOND: + return setDurationMicrosecond(data, index2, value); + case TimeUnit.NANOSECOND: + return setDurationNanosecond(data, index2, value); } }; - exports2.comp9 = { - parameterPath: "comp", - mapper: { - defaultValue: "rename", - isConstant: true, - serializedName: "comp", - type: { - name: "String" + setFixedSizeList = (data, index2, value) => { + const { stride } = data; + const child = data.children[0]; + const set = instance.getVisitFn(child); + if (Array.isArray(value)) { + for (let idx = -1, offset = index2 * stride; ++idx < stride; ) { + set(child, offset + idx, value[idx]); } - } - }; - exports2.sourceContainerName = { - parameterPath: "sourceContainerName", - mapper: { - serializedName: "x-ms-source-container-name", - required: true, - xmlName: "x-ms-source-container-name", - type: { - name: "String" + } else { + for (let idx = -1, offset = index2 * stride; ++idx < stride; ) { + set(child, offset + idx, value.get(idx)); + } + } + }; + SetVisitor.prototype.visitBool = wrapSet(setBool); + SetVisitor.prototype.visitInt = wrapSet(setInt); + SetVisitor.prototype.visitInt8 = wrapSet(setInt); + SetVisitor.prototype.visitInt16 = wrapSet(setInt); + SetVisitor.prototype.visitInt32 = wrapSet(setInt); + SetVisitor.prototype.visitInt64 = wrapSet(setInt); + SetVisitor.prototype.visitUint8 = wrapSet(setInt); + SetVisitor.prototype.visitUint16 = wrapSet(setInt); + SetVisitor.prototype.visitUint32 = wrapSet(setInt); + SetVisitor.prototype.visitUint64 = wrapSet(setInt); + SetVisitor.prototype.visitFloat = wrapSet(setAnyFloat); + SetVisitor.prototype.visitFloat16 = wrapSet(setFloat16); + SetVisitor.prototype.visitFloat32 = wrapSet(setFloat); + SetVisitor.prototype.visitFloat64 = wrapSet(setFloat); + SetVisitor.prototype.visitUtf8 = wrapSet(setUtf8); + SetVisitor.prototype.visitLargeUtf8 = wrapSet(setUtf8); + SetVisitor.prototype.visitUtf8View = wrapSet(setUtf8View); + SetVisitor.prototype.visitBinary = wrapSet(setBinary); + SetVisitor.prototype.visitLargeBinary = wrapSet(setBinary); + SetVisitor.prototype.visitBinaryView = wrapSet(setBinaryView); + SetVisitor.prototype.visitFixedSizeBinary = wrapSet(setFixedSizeBinary); + SetVisitor.prototype.visitDate = wrapSet(setDate); + SetVisitor.prototype.visitDateDay = wrapSet(setDateDay); + SetVisitor.prototype.visitDateMillisecond = wrapSet(setDateMillisecond); + SetVisitor.prototype.visitTimestamp = wrapSet(setTimestamp); + SetVisitor.prototype.visitTimestampSecond = wrapSet(setTimestampSecond); + SetVisitor.prototype.visitTimestampMillisecond = wrapSet(setTimestampMillisecond); + SetVisitor.prototype.visitTimestampMicrosecond = wrapSet(setTimestampMicrosecond); + SetVisitor.prototype.visitTimestampNanosecond = wrapSet(setTimestampNanosecond); + SetVisitor.prototype.visitTime = wrapSet(setTime); + SetVisitor.prototype.visitTimeSecond = wrapSet(setTimeSecond); + SetVisitor.prototype.visitTimeMillisecond = wrapSet(setTimeMillisecond); + SetVisitor.prototype.visitTimeMicrosecond = wrapSet(setTimeMicrosecond); + SetVisitor.prototype.visitTimeNanosecond = wrapSet(setTimeNanosecond); + SetVisitor.prototype.visitDecimal = wrapSet(setDecimal); + SetVisitor.prototype.visitList = wrapSet(setList); + SetVisitor.prototype.visitLargeList = wrapSet(setList); + SetVisitor.prototype.visitStruct = wrapSet(setStruct); + SetVisitor.prototype.visitUnion = wrapSet(setUnion); + SetVisitor.prototype.visitDenseUnion = wrapSet(setDenseUnion); + SetVisitor.prototype.visitSparseUnion = wrapSet(setSparseUnion); + SetVisitor.prototype.visitDictionary = wrapSet(setDictionary); + SetVisitor.prototype.visitInterval = wrapSet(setIntervalValue); + SetVisitor.prototype.visitIntervalDayTime = wrapSet(setIntervalDayTime); + SetVisitor.prototype.visitIntervalYearMonth = wrapSet(setIntervalYearMonth); + SetVisitor.prototype.visitIntervalMonthDayNano = wrapSet(setIntervalMonthDayNano); + SetVisitor.prototype.visitDuration = wrapSet(setDuration); + SetVisitor.prototype.visitDurationSecond = wrapSet(setDurationSecond); + SetVisitor.prototype.visitDurationMillisecond = wrapSet(setDurationMillisecond); + SetVisitor.prototype.visitDurationMicrosecond = wrapSet(setDurationMicrosecond); + SetVisitor.prototype.visitDurationNanosecond = wrapSet(setDurationNanosecond); + SetVisitor.prototype.visitFixedSizeList = wrapSet(setFixedSizeList); + SetVisitor.prototype.visitMap = wrapSet(setMap); + instance = new SetVisitor(); + } +}); + +// node_modules/apache-arrow/row/struct.mjs +var kParent, kRowIndex, StructRow, StructRowIterator, StructRowProxyHandler, structRowProxyHandler; +var init_struct2 = __esm({ + "node_modules/apache-arrow/row/struct.mjs"() { + init_pretty(); + init_get(); + init_set(); + kParent = /* @__PURE__ */ Symbol.for("parent"); + kRowIndex = /* @__PURE__ */ Symbol.for("rowIndex"); + StructRow = class { + constructor(parent, rowIndex) { + this[kParent] = parent; + this[kRowIndex] = rowIndex; + return new Proxy(this, structRowProxyHandler); + } + toArray() { + return Object.values(this.toJSON()); + } + toJSON() { + const i = this[kRowIndex]; + const parent = this[kParent]; + const keys = parent.type.children; + const json = {}; + for (let j = -1, n = keys.length; ++j < n; ) { + json[keys[j].name] = instance2.visit(parent.children[j], i); } + return json; + } + toString() { + return `{${[...this].map(([key, val]) => `${valueToString(key)}: ${valueToString(val)}`).join(", ")}}`; + } + [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() { + return this.toString(); + } + [Symbol.iterator]() { + return new StructRowIterator(this[kParent], this[kRowIndex]); } }; - exports2.sourceLeaseId = { - parameterPath: ["options", "sourceLeaseId"], - mapper: { - serializedName: "x-ms-source-lease-id", - xmlName: "x-ms-source-lease-id", - type: { - name: "String" + StructRowIterator = class { + constructor(data, rowIndex) { + this.childIndex = 0; + this.children = data.children; + this.rowIndex = rowIndex; + this.childFields = data.type.children; + this.numChildren = this.childFields.length; + } + [Symbol.iterator]() { + return this; + } + next() { + const i = this.childIndex; + if (i < this.numChildren) { + this.childIndex = i + 1; + return { + done: false, + value: [ + this.childFields[i].name, + instance2.visit(this.children[i], this.rowIndex) + ] + }; } + return { done: true, value: null }; } }; - exports2.comp10 = { - parameterPath: "comp", - mapper: { - defaultValue: "lease", - isConstant: true, - serializedName: "comp", - type: { - name: "String" + Object.defineProperties(StructRow.prototype, { + [Symbol.toStringTag]: { enumerable: false, configurable: false, value: "Row" }, + [kParent]: { writable: true, enumerable: false, configurable: false, value: null }, + [kRowIndex]: { writable: true, enumerable: false, configurable: false, value: -1 } + }); + StructRowProxyHandler = class { + isExtensible() { + return false; + } + deleteProperty() { + return false; + } + preventExtensions() { + return true; + } + ownKeys(row) { + return row[kParent].type.children.map((f) => f.name); + } + has(row, key) { + return row[kParent].type.children.some((f) => f.name === key); + } + getOwnPropertyDescriptor(row, key) { + if (row[kParent].type.children.some((f) => f.name === key)) { + return { writable: true, enumerable: true, configurable: true }; } + return; } - }; - exports2.action = { - parameterPath: "action", - mapper: { - defaultValue: "acquire", - isConstant: true, - serializedName: "x-ms-lease-action", - type: { - name: "String" + get(row, key) { + if (Reflect.has(row, key)) { + return row[key]; + } + const idx = row[kParent].type.children.findIndex((f) => f.name === key); + if (idx !== -1) { + const val = instance2.visit(row[kParent].children[idx], row[kRowIndex]); + Reflect.set(row, key, val); + return val; } } - }; - exports2.duration = { - parameterPath: ["options", "duration"], - mapper: { - serializedName: "x-ms-lease-duration", - xmlName: "x-ms-lease-duration", - type: { - name: "Number" + set(row, key, val) { + const idx = row[kParent].type.children.findIndex((f) => f.name === key); + if (idx !== -1) { + instance.visit(row[kParent].children[idx], row[kRowIndex], val); + return Reflect.set(row, key, val); + } else if (Reflect.has(row, key) || typeof key === "symbol") { + return Reflect.set(row, key, val); } + return false; } }; - exports2.proposedLeaseId = { - parameterPath: ["options", "proposedLeaseId"], - mapper: { - serializedName: "x-ms-proposed-lease-id", - xmlName: "x-ms-proposed-lease-id", - type: { - name: "String" + structRowProxyHandler = new StructRowProxyHandler(); + } +}); + +// node_modules/apache-arrow/visitor/get.mjs +function wrapGet(fn) { + return (data, _1) => data.getValid(_1) ? fn(data, _1) : null; +} +var GetVisitor, epochDaysToMs, BINARY_VIEW_SIZE, BINARY_VIEW_INLINE_CAPACITY, getNull, getVariableWidthBytes, getBool, getDateDay, getDateMillisecond, getNumeric, getFloat16, getBigInts, getFixedSizeBinary, getBinary, getBinaryViewBytes, getBinaryViewValue, getUtf8, getUtf8ViewValue, getInt, getFloat, getDate, getTimestampSecond, getTimestampMillisecond, getTimestampMicrosecond, getTimestampNanosecond, getTimestamp, getTimeSecond, getTimeMillisecond, getTimeMicrosecond, getTimeNanosecond, getTime, getDecimal, getList, getMap, getStruct, getUnion, getDenseUnion, getSparseUnion, getDictionary, getInterval, getIntervalDayTime, getIntervalYearMonth, getIntervalMonthDayNano, getDurationSecond, getDurationMillisecond, getDurationMicrosecond, getDurationNanosecond, getDuration, getFixedSizeList, instance2; +var init_get = __esm({ + "node_modules/apache-arrow/visitor/get.mjs"() { + init_bn(); + init_vector2(); + init_visitor(); + init_map2(); + init_struct2(); + init_bigint(); + init_utf8(); + init_math(); + init_enum(); + GetVisitor = class extends Visitor { + }; + epochDaysToMs = (data, index2) => 864e5 * data[index2]; + BINARY_VIEW_SIZE = 16; + BINARY_VIEW_INLINE_CAPACITY = 12; + getNull = (_data, _index) => null; + getVariableWidthBytes = (values, valueOffsets, index2) => { + if (index2 + 1 >= valueOffsets.length) { + return null; + } + const x = bigIntToNumber(valueOffsets[index2]); + const y = bigIntToNumber(valueOffsets[index2 + 1]); + return values.subarray(x, y); + }; + getBool = ({ offset, values }, index2) => { + const idx = offset + index2; + const byte = values[idx >> 3]; + return (byte & 1 << idx % 8) !== 0; + }; + getDateDay = ({ values }, index2) => epochDaysToMs(values, index2); + getDateMillisecond = ({ values }, index2) => bigIntToNumber(values[index2]); + getNumeric = ({ stride, values }, index2) => values[stride * index2]; + getFloat16 = ({ stride, values }, index2) => uint16ToFloat64(values[stride * index2]); + getBigInts = ({ values }, index2) => values[index2]; + getFixedSizeBinary = ({ stride, values }, index2) => values.subarray(stride * index2, stride * (index2 + 1)); + getBinary = ({ values, valueOffsets }, index2) => getVariableWidthBytes(values, valueOffsets, index2); + getBinaryViewBytes = (data, index2) => { + var _a6; + const values = data.values; + if (!values) { + throw new Error("BinaryView data is missing view buffer"); + } + const viewOffset = index2 * BINARY_VIEW_SIZE; + const end = viewOffset + BINARY_VIEW_SIZE; + if (viewOffset < 0 || end > values.length) { + throw new Error(`BinaryView data buffer is too short: expected ${BINARY_VIEW_SIZE} bytes, got ${Math.max(0, values.length - viewOffset)}`); + } + const viewStruct = values.subarray(viewOffset, end); + if (viewStruct.length < BINARY_VIEW_SIZE) { + throw new Error(`BinaryView data buffer is too short: expected ${BINARY_VIEW_SIZE} bytes, got ${viewStruct.length}`); + } + const view = new DataView(values.buffer, viewStruct.byteOffset, BINARY_VIEW_SIZE); + const size = view.getInt32(0, true); + if (size <= 0) { + return new Uint8Array(0); + } + if (size <= BINARY_VIEW_INLINE_CAPACITY) { + return viewStruct.subarray(4, 4 + size); + } + const bufferIndex = view.getInt32(8, true); + const offset = view.getInt32(12, true); + const variadicBuffer = (_a6 = data.variadicBuffers) === null || _a6 === void 0 ? void 0 : _a6[bufferIndex]; + if (!variadicBuffer) { + throw new Error(`BinaryView variadic buffer ${bufferIndex} is missing`); + } + return variadicBuffer.subarray(offset, offset + size); + }; + getBinaryViewValue = (data, index2) => { + return getBinaryViewBytes(data, index2); + }; + getUtf8 = ({ values, valueOffsets }, index2) => { + const bytes = getVariableWidthBytes(values, valueOffsets, index2); + return bytes !== null ? decodeUtf8(bytes) : null; + }; + getUtf8ViewValue = (data, index2) => { + const bytes = getBinaryViewBytes(data, index2); + return decodeUtf8(bytes); + }; + getInt = ({ values }, index2) => values[index2]; + getFloat = ({ type, values }, index2) => type.precision !== Precision.HALF ? values[index2] : uint16ToFloat64(values[index2]); + getDate = (data, index2) => data.type.unit === DateUnit.DAY ? getDateDay(data, index2) : getDateMillisecond(data, index2); + getTimestampSecond = ({ values }, index2) => 1e3 * bigIntToNumber(values[index2]); + getTimestampMillisecond = ({ values }, index2) => bigIntToNumber(values[index2]); + getTimestampMicrosecond = ({ values }, index2) => divideBigInts(values[index2], BigInt(1e3)); + getTimestampNanosecond = ({ values }, index2) => divideBigInts(values[index2], BigInt(1e6)); + getTimestamp = (data, index2) => { + switch (data.type.unit) { + case TimeUnit.SECOND: + return getTimestampSecond(data, index2); + case TimeUnit.MILLISECOND: + return getTimestampMillisecond(data, index2); + case TimeUnit.MICROSECOND: + return getTimestampMicrosecond(data, index2); + case TimeUnit.NANOSECOND: + return getTimestampNanosecond(data, index2); + } + }; + getTimeSecond = ({ values }, index2) => values[index2]; + getTimeMillisecond = ({ values }, index2) => values[index2]; + getTimeMicrosecond = ({ values }, index2) => values[index2]; + getTimeNanosecond = ({ values }, index2) => values[index2]; + getTime = (data, index2) => { + switch (data.type.unit) { + case TimeUnit.SECOND: + return getTimeSecond(data, index2); + case TimeUnit.MILLISECOND: + return getTimeMillisecond(data, index2); + case TimeUnit.MICROSECOND: + return getTimeMicrosecond(data, index2); + case TimeUnit.NANOSECOND: + return getTimeNanosecond(data, index2); + } + }; + getDecimal = ({ values, stride }, index2) => BN.decimal(values.subarray(stride * index2, stride * (index2 + 1))); + getList = (data, index2) => { + const { valueOffsets, stride, children } = data; + const begin = bigIntToNumber(valueOffsets[index2 * stride]); + const end = bigIntToNumber(valueOffsets[index2 * stride + 1]); + const child = children[0]; + const slice = child.slice(begin, end - begin); + return new Vector([slice]); + }; + getMap = (data, index2) => { + const { valueOffsets, children } = data; + const { [index2]: begin, [index2 + 1]: end } = valueOffsets; + const child = children[0]; + return new MapRow(child.slice(begin, end - begin)); + }; + getStruct = (data, index2) => { + return new StructRow(data, index2); + }; + getUnion = (data, index2) => { + return data.type.mode === UnionMode.Dense ? getDenseUnion(data, index2) : getSparseUnion(data, index2); + }; + getDenseUnion = (data, index2) => { + const childIndex = data.type.typeIdToChildIndex[data.typeIds[index2]]; + const child = data.children[childIndex]; + return instance2.visit(child, data.valueOffsets[index2]); + }; + getSparseUnion = (data, index2) => { + const childIndex = data.type.typeIdToChildIndex[data.typeIds[index2]]; + const child = data.children[childIndex]; + return instance2.visit(child, index2); + }; + getDictionary = (data, index2) => { + var _a6; + return (_a6 = data.dictionary) === null || _a6 === void 0 ? void 0 : _a6.get(data.values[index2]); + }; + getInterval = (data, index2) => data.type.unit === IntervalUnit.MONTH_DAY_NANO ? getIntervalMonthDayNano(data, index2) : data.type.unit === IntervalUnit.DAY_TIME ? getIntervalDayTime(data, index2) : getIntervalYearMonth(data, index2); + getIntervalDayTime = ({ values }, index2) => values.subarray(2 * index2, 2 * (index2 + 1)); + getIntervalYearMonth = ({ values }, index2) => { + const interval = values[index2]; + const int32s = new Int32Array(2); + int32s[0] = Math.trunc(interval / 12); + int32s[1] = Math.trunc(interval % 12); + return int32s; + }; + getIntervalMonthDayNano = ({ values }, index2) => values.subarray(4 * index2, 4 * (index2 + 1)); + getDurationSecond = ({ values }, index2) => values[index2]; + getDurationMillisecond = ({ values }, index2) => values[index2]; + getDurationMicrosecond = ({ values }, index2) => values[index2]; + getDurationNanosecond = ({ values }, index2) => values[index2]; + getDuration = (data, index2) => { + switch (data.type.unit) { + case TimeUnit.SECOND: + return getDurationSecond(data, index2); + case TimeUnit.MILLISECOND: + return getDurationMillisecond(data, index2); + case TimeUnit.MICROSECOND: + return getDurationMicrosecond(data, index2); + case TimeUnit.NANOSECOND: + return getDurationNanosecond(data, index2); + } + }; + getFixedSizeList = (data, index2) => { + const { stride, children } = data; + const child = children[0]; + const slice = child.slice(index2 * stride, stride); + return new Vector([slice]); + }; + GetVisitor.prototype.visitNull = wrapGet(getNull); + GetVisitor.prototype.visitBool = wrapGet(getBool); + GetVisitor.prototype.visitInt = wrapGet(getInt); + GetVisitor.prototype.visitInt8 = wrapGet(getNumeric); + GetVisitor.prototype.visitInt16 = wrapGet(getNumeric); + GetVisitor.prototype.visitInt32 = wrapGet(getNumeric); + GetVisitor.prototype.visitInt64 = wrapGet(getBigInts); + GetVisitor.prototype.visitUint8 = wrapGet(getNumeric); + GetVisitor.prototype.visitUint16 = wrapGet(getNumeric); + GetVisitor.prototype.visitUint32 = wrapGet(getNumeric); + GetVisitor.prototype.visitUint64 = wrapGet(getBigInts); + GetVisitor.prototype.visitFloat = wrapGet(getFloat); + GetVisitor.prototype.visitFloat16 = wrapGet(getFloat16); + GetVisitor.prototype.visitFloat32 = wrapGet(getNumeric); + GetVisitor.prototype.visitFloat64 = wrapGet(getNumeric); + GetVisitor.prototype.visitUtf8 = wrapGet(getUtf8); + GetVisitor.prototype.visitLargeUtf8 = wrapGet(getUtf8); + GetVisitor.prototype.visitUtf8View = wrapGet(getUtf8ViewValue); + GetVisitor.prototype.visitBinary = wrapGet(getBinary); + GetVisitor.prototype.visitLargeBinary = wrapGet(getBinary); + GetVisitor.prototype.visitBinaryView = wrapGet(getBinaryViewValue); + GetVisitor.prototype.visitFixedSizeBinary = wrapGet(getFixedSizeBinary); + GetVisitor.prototype.visitDate = wrapGet(getDate); + GetVisitor.prototype.visitDateDay = wrapGet(getDateDay); + GetVisitor.prototype.visitDateMillisecond = wrapGet(getDateMillisecond); + GetVisitor.prototype.visitTimestamp = wrapGet(getTimestamp); + GetVisitor.prototype.visitTimestampSecond = wrapGet(getTimestampSecond); + GetVisitor.prototype.visitTimestampMillisecond = wrapGet(getTimestampMillisecond); + GetVisitor.prototype.visitTimestampMicrosecond = wrapGet(getTimestampMicrosecond); + GetVisitor.prototype.visitTimestampNanosecond = wrapGet(getTimestampNanosecond); + GetVisitor.prototype.visitTime = wrapGet(getTime); + GetVisitor.prototype.visitTimeSecond = wrapGet(getTimeSecond); + GetVisitor.prototype.visitTimeMillisecond = wrapGet(getTimeMillisecond); + GetVisitor.prototype.visitTimeMicrosecond = wrapGet(getTimeMicrosecond); + GetVisitor.prototype.visitTimeNanosecond = wrapGet(getTimeNanosecond); + GetVisitor.prototype.visitDecimal = wrapGet(getDecimal); + GetVisitor.prototype.visitList = wrapGet(getList); + GetVisitor.prototype.visitLargeList = wrapGet(getList); + GetVisitor.prototype.visitStruct = wrapGet(getStruct); + GetVisitor.prototype.visitUnion = wrapGet(getUnion); + GetVisitor.prototype.visitDenseUnion = wrapGet(getDenseUnion); + GetVisitor.prototype.visitSparseUnion = wrapGet(getSparseUnion); + GetVisitor.prototype.visitDictionary = wrapGet(getDictionary); + GetVisitor.prototype.visitInterval = wrapGet(getInterval); + GetVisitor.prototype.visitIntervalDayTime = wrapGet(getIntervalDayTime); + GetVisitor.prototype.visitIntervalYearMonth = wrapGet(getIntervalYearMonth); + GetVisitor.prototype.visitIntervalMonthDayNano = wrapGet(getIntervalMonthDayNano); + GetVisitor.prototype.visitDuration = wrapGet(getDuration); + GetVisitor.prototype.visitDurationSecond = wrapGet(getDurationSecond); + GetVisitor.prototype.visitDurationMillisecond = wrapGet(getDurationMillisecond); + GetVisitor.prototype.visitDurationMicrosecond = wrapGet(getDurationMicrosecond); + GetVisitor.prototype.visitDurationNanosecond = wrapGet(getDurationNanosecond); + GetVisitor.prototype.visitFixedSizeList = wrapGet(getFixedSizeList); + GetVisitor.prototype.visitMap = wrapGet(getMap); + instance2 = new GetVisitor(); + } +}); + +// node_modules/apache-arrow/row/map.mjs +var kKeys, kVals, kKeysAsStrings, _kKeysAsStrings, MapRow, MapRowIterator, MapRowProxyHandler; +var init_map2 = __esm({ + "node_modules/apache-arrow/row/map.mjs"() { + init_vector2(); + init_pretty(); + init_get(); + init_set(); + kKeys = /* @__PURE__ */ Symbol.for("keys"); + kVals = /* @__PURE__ */ Symbol.for("vals"); + kKeysAsStrings = /* @__PURE__ */ Symbol.for("kKeysAsStrings"); + _kKeysAsStrings = /* @__PURE__ */ Symbol.for("_kKeysAsStrings"); + MapRow = class { + constructor(slice) { + this[kKeys] = new Vector([slice.children[0]]).memoize(); + this[kVals] = slice.children[1]; + return new Proxy(this, new MapRowProxyHandler()); + } + /** @ignore */ + get [kKeysAsStrings]() { + return this[_kKeysAsStrings] || (this[_kKeysAsStrings] = Array.from(this[kKeys].toArray(), String)); + } + [Symbol.iterator]() { + return new MapRowIterator(this[kKeys], this[kVals]); + } + get size() { + return this[kKeys].length; + } + toArray() { + return Object.values(this.toJSON()); + } + toJSON() { + const keys = this[kKeys]; + const vals = this[kVals]; + const json = {}; + for (let i = -1, n = keys.length; ++i < n; ) { + json[keys.get(i)] = instance2.visit(vals, i); } + return json; + } + toString() { + return `{${[...this].map(([key, val]) => `${valueToString(key)}: ${valueToString(val)}`).join(", ")}}`; + } + [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() { + return this.toString(); } }; - exports2.action1 = { - parameterPath: "action", - mapper: { - defaultValue: "release", - isConstant: true, - serializedName: "x-ms-lease-action", - type: { - name: "String" + MapRowIterator = class { + constructor(keys, vals) { + this.keys = keys; + this.vals = vals; + this.keyIndex = 0; + this.numKeys = keys.length; + } + [Symbol.iterator]() { + return this; + } + next() { + const i = this.keyIndex; + if (i === this.numKeys) { + return { done: true, value: null }; } + this.keyIndex++; + return { + done: false, + value: [ + this.keys.get(i), + instance2.visit(this.vals, i) + ] + }; } }; - exports2.leaseId1 = { - parameterPath: "leaseId", - mapper: { - serializedName: "x-ms-lease-id", - required: true, - xmlName: "x-ms-lease-id", - type: { - name: "String" + MapRowProxyHandler = class { + isExtensible() { + return false; + } + deleteProperty() { + return false; + } + preventExtensions() { + return true; + } + ownKeys(row) { + return row[kKeysAsStrings]; + } + has(row, key) { + return row[kKeysAsStrings].includes(key); + } + getOwnPropertyDescriptor(row, key) { + const idx = row[kKeysAsStrings].indexOf(key); + if (idx !== -1) { + return { writable: true, enumerable: true, configurable: true }; } + return; } - }; - exports2.action2 = { - parameterPath: "action", - mapper: { - defaultValue: "renew", - isConstant: true, - serializedName: "x-ms-lease-action", - type: { - name: "String" + get(row, key) { + if (Reflect.has(row, key)) { + return row[key]; + } + const idx = row[kKeysAsStrings].indexOf(key); + if (idx !== -1) { + const val = instance2.visit(Reflect.get(row, kVals), idx); + Reflect.set(row, key, val); + return val; } } - }; - exports2.action3 = { - parameterPath: "action", - mapper: { - defaultValue: "break", - isConstant: true, - serializedName: "x-ms-lease-action", - type: { - name: "String" + set(row, key, val) { + const idx = row[kKeysAsStrings].indexOf(key); + if (idx !== -1) { + instance.visit(Reflect.get(row, kVals), idx, val); + return Reflect.set(row, key, val); + } else if (Reflect.has(row, key)) { + return Reflect.set(row, key, val); } + return false; } }; - exports2.breakPeriod = { - parameterPath: ["options", "breakPeriod"], - mapper: { - serializedName: "x-ms-lease-break-period", - xmlName: "x-ms-lease-break-period", - type: { - name: "Number" + Object.defineProperties(MapRow.prototype, { + [Symbol.toStringTag]: { enumerable: false, configurable: false, value: "Row" }, + [kKeys]: { writable: true, enumerable: false, configurable: false, value: null }, + [kVals]: { writable: true, enumerable: false, configurable: false, value: null }, + [_kKeysAsStrings]: { writable: true, enumerable: false, configurable: false, value: null } + }); + } +}); + +// node_modules/apache-arrow/util/vector.mjs +var vector_exports = {}; +__export(vector_exports, { + clampRange: () => clampRange, + createElementComparator: () => createElementComparator, + wrapIndex: () => wrapIndex +}); +function clampRange(source, begin, end, then) { + const { length: len = 0 } = source; + let lhs = typeof begin !== "number" ? 0 : begin; + let rhs = typeof end !== "number" ? len : end; + lhs < 0 && (lhs = (lhs % len + len) % len); + rhs < 0 && (rhs = (rhs % len + len) % len); + rhs < lhs && (tmp = lhs, lhs = rhs, rhs = tmp); + rhs > len && (rhs = len); + return then ? then(source, lhs, rhs) : [lhs, rhs]; +} +function createElementComparator(search) { + const typeofSearch = typeof search; + if (typeofSearch !== "object" || search === null) { + if (isNaNFast(search)) { + return isNaNFast; + } + return (value) => value === search; + } + if (search instanceof Date) { + const valueOfSearch = search.valueOf(); + return (value) => value instanceof Date ? value.valueOf() === valueOfSearch : false; + } + if (ArrayBuffer.isView(search)) { + return (value) => value ? compareArrayLike(search, value) : false; + } + if (search instanceof Map) { + return createMapComparator(search); + } + if (Array.isArray(search)) { + return createArrayLikeComparator(search); + } + if (search instanceof Vector) { + return createVectorComparator(search); + } + return createObjectComparator(search, true); +} +function createArrayLikeComparator(lhs) { + const comparators = []; + for (let i = -1, n = lhs.length; ++i < n; ) { + comparators[i] = createElementComparator(lhs[i]); + } + return createSubElementsComparator(comparators); +} +function createMapComparator(lhs) { + let i = -1; + const comparators = []; + for (const v of lhs.values()) + comparators[++i] = createElementComparator(v); + return createSubElementsComparator(comparators); +} +function createVectorComparator(lhs) { + const comparators = []; + for (let i = -1, n = lhs.length; ++i < n; ) { + comparators[i] = createElementComparator(lhs.get(i)); + } + return createSubElementsComparator(comparators); +} +function createObjectComparator(lhs, allowEmpty = false) { + const keys = Object.keys(lhs); + if (!allowEmpty && keys.length === 0) { + return () => false; + } + const comparators = []; + for (let i = -1, n = keys.length; ++i < n; ) { + comparators[i] = createElementComparator(lhs[keys[i]]); + } + return createSubElementsComparator(comparators, keys); +} +function createSubElementsComparator(comparators, keys) { + return (rhs) => { + if (!rhs || typeof rhs !== "object") { + return false; + } + switch (rhs.constructor) { + case Array: + return compareArray(comparators, rhs); + case Map: + return compareObject(comparators, rhs, rhs.keys()); + case MapRow: + case StructRow: + case Object: + case void 0: + return compareObject(comparators, rhs, keys || Object.keys(rhs)); + } + return rhs instanceof Vector ? compareVector(comparators, rhs) : false; + }; +} +function compareArray(comparators, arr) { + const n = comparators.length; + if (arr.length !== n) { + return false; + } + for (let i = -1; ++i < n; ) { + if (!comparators[i](arr[i])) { + return false; + } + } + return true; +} +function compareVector(comparators, vec) { + const n = comparators.length; + if (vec.length !== n) { + return false; + } + for (let i = -1; ++i < n; ) { + if (!comparators[i](vec.get(i))) { + return false; + } + } + return true; +} +function compareObject(comparators, obj, keys) { + const lKeyItr = keys[Symbol.iterator](); + const rKeyItr = obj instanceof Map ? obj.keys() : Object.keys(obj)[Symbol.iterator](); + const rValItr = obj instanceof Map ? obj.values() : Object.values(obj)[Symbol.iterator](); + let i = 0; + const n = comparators.length; + let rVal = rValItr.next(); + let lKey = lKeyItr.next(); + let rKey = rKeyItr.next(); + for (; i < n && !lKey.done && !rKey.done && !rVal.done; ++i, lKey = lKeyItr.next(), rKey = rKeyItr.next(), rVal = rValItr.next()) { + if (lKey.value !== rKey.value || !comparators[i](rVal.value)) { + break; + } + } + if (i === n && lKey.done && rKey.done && rVal.done) { + return true; + } + lKeyItr.return && lKeyItr.return(); + rKeyItr.return && rKeyItr.return(); + rValItr.return && rValItr.return(); + return false; +} +var tmp, wrapIndex, isNaNFast; +var init_vector = __esm({ + "node_modules/apache-arrow/util/vector.mjs"() { + init_vector2(); + init_map2(); + init_struct2(); + init_buffer(); + wrapIndex = (index2, len) => index2 < 0 ? len + index2 : index2; + isNaNFast = (value) => value !== value; + } +}); + +// node_modules/apache-arrow/util/bit.mjs +var bit_exports = {}; +__export(bit_exports, { + BitIterator: () => BitIterator, + getBit: () => getBit, + getBool: () => getBool2, + packBools: () => packBools, + popcnt_array: () => popcnt_array, + popcnt_bit_range: () => popcnt_bit_range, + popcnt_uint32: () => popcnt_uint32, + setBool: () => setBool2, + truncateBitmap: () => truncateBitmap +}); +function getBool2(_data, _index, byte, bit) { + return (byte & 1 << bit) !== 0; +} +function getBit(_data, _index, byte, bit) { + return (byte & 1 << bit) >> bit; +} +function setBool2(bytes, index2, value) { + return value ? !!(bytes[index2 >> 3] |= 1 << index2 % 8) || true : !(bytes[index2 >> 3] &= ~(1 << index2 % 8)) && false; +} +function truncateBitmap(offset, length, bitmap) { + const alignedSize = bitmap.byteLength + 7 & ~7; + if (offset > 0 || bitmap.byteLength < alignedSize) { + const bytes = new Uint8Array(alignedSize); + bytes.set(offset % 8 === 0 ? bitmap.subarray(offset >> 3) : ( + // Otherwise iterate each bit from the offset and return a new one + packBools(new BitIterator(bitmap, offset, length, null, getBool2)).subarray(0, alignedSize) + )); + return bytes; + } + return bitmap; +} +function packBools(values) { + const xs = []; + let i = 0, bit = 0, byte = 0; + for (const value of values) { + value && (byte |= 1 << bit); + if (++bit === 8) { + xs[i++] = byte; + byte = bit = 0; + } + } + if (i === 0 || bit > 0) { + xs[i++] = byte; + } + const b = new Uint8Array(xs.length + 7 & ~7); + b.set(xs); + return b; +} +function popcnt_bit_range(data, lhs, rhs) { + if (rhs - lhs <= 0) { + return 0; + } + if (rhs - lhs < 8) { + let sum = 0; + for (const bit of new BitIterator(data, lhs, rhs - lhs, data, getBit)) { + sum += bit; + } + return sum; + } + const rhsInside = rhs >> 3 << 3; + const lhsInside = lhs + (lhs % 8 === 0 ? 0 : 8 - lhs % 8); + return ( + // Get the popcnt of bits between the left hand side, and the next highest multiple of 8 + popcnt_bit_range(data, lhs, lhsInside) + // Get the popcnt of bits between the right hand side, and the next lowest multiple of 8 + popcnt_bit_range(data, rhsInside, rhs) + // Get the popcnt of all bits between the left and right hand sides' multiples of 8 + popcnt_array(data, lhsInside >> 3, rhsInside - lhsInside >> 3) + ); +} +function popcnt_array(arr, byteOffset, byteLength) { + let cnt = 0, pos = Math.trunc(byteOffset); + const view = new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + const len = byteLength === void 0 ? arr.byteLength : pos + byteLength; + while (len - pos >= 4) { + cnt += popcnt_uint32(view.getUint32(pos)); + pos += 4; + } + while (len - pos >= 2) { + cnt += popcnt_uint32(view.getUint16(pos)); + pos += 2; + } + while (len - pos >= 1) { + cnt += popcnt_uint32(view.getUint8(pos)); + pos += 1; + } + return cnt; +} +function popcnt_uint32(uint32) { + let i = Math.trunc(uint32); + i = i - (i >>> 1 & 1431655765); + i = (i & 858993459) + (i >>> 2 & 858993459); + return (i + (i >>> 4) & 252645135) * 16843009 >>> 24; +} +var BitIterator; +var init_bit = __esm({ + "node_modules/apache-arrow/util/bit.mjs"() { + BitIterator = class { + constructor(bytes, begin, length, context5, get) { + this.bytes = bytes; + this.length = length; + this.context = context5; + this.get = get; + this.bit = begin % 8; + this.byteIndex = begin >> 3; + this.byte = bytes[this.byteIndex++]; + this.index = 0; + } + next() { + if (this.index < this.length) { + if (this.bit === 8) { + this.bit = 0; + this.byte = this.bytes[this.byteIndex++]; + } + return { + value: this.get(this.context, this.index++, this.byte, this.bit++) + }; } + return { done: true, value: null }; + } + [Symbol.iterator]() { + return this; } }; - exports2.action4 = { - parameterPath: "action", - mapper: { - defaultValue: "change", - isConstant: true, - serializedName: "x-ms-lease-action", - type: { - name: "String" + } +}); + +// node_modules/apache-arrow/data.mjs +function makeData(props) { + return makeDataVisitor.visit(props); +} +var kUnknownNullCount, kDataSymbol, Data, MakeDataVisitor, makeDataVisitor; +var init_data = __esm({ + "node_modules/apache-arrow/data.mjs"() { + init_vector2(); + init_enum(); + init_type2(); + init_bit(); + init_type2(); + init_visitor(); + init_buffer(); + kUnknownNullCount = -1; + kDataSymbol = /* @__PURE__ */ Symbol.for("apache-arrow/Data"); + Data = class _Data { + /** + * Check if an object is an instance of Data. + * This works across different instances of the Arrow library. + */ + /** @nocollapse */ + static isData(x) { + return (x === null || x === void 0 ? void 0 : x[kDataSymbol]) === true; + } + get typeId() { + return this.type.typeId; + } + get ArrayType() { + return this.type.ArrayType; + } + get buffers() { + return [this.valueOffsets, this.values, this.nullBitmap, this.typeIds]; + } + get nullable() { + if (this._nullCount !== 0) { + const { type } = this; + if (DataType.isSparseUnion(type)) { + return this.children.some((child) => child.nullable); + } else if (DataType.isDenseUnion(type)) { + return this.children.some((child) => child.nullable); + } + return this.nullBitmap && this.nullBitmap.byteLength > 0; } + return true; } - }; - exports2.proposedLeaseId1 = { - parameterPath: "proposedLeaseId", - mapper: { - serializedName: "x-ms-proposed-lease-id", - required: true, - xmlName: "x-ms-proposed-lease-id", - type: { - name: "String" + get byteLength() { + let byteLength = 0; + const { valueOffsets, values, nullBitmap, typeIds } = this; + valueOffsets && (byteLength += valueOffsets.byteLength); + values && (byteLength += values.byteLength); + nullBitmap && (byteLength += nullBitmap.byteLength); + typeIds && (byteLength += typeIds.byteLength); + byteLength += this.variadicBuffers.reduce((size, data) => { + var _a6; + return size + ((_a6 = data === null || data === void 0 ? void 0 : data.byteLength) !== null && _a6 !== void 0 ? _a6 : 0); + }, 0); + return this.children.reduce((byteLength2, child) => byteLength2 + child.byteLength, byteLength); + } + get nullCount() { + if (DataType.isUnion(this.type)) { + return this.children.reduce((nullCount2, child) => nullCount2 + child.nullCount, 0); + } + let nullCount = this._nullCount; + let nullBitmap; + if (nullCount <= kUnknownNullCount && (nullBitmap = this.nullBitmap)) { + this._nullCount = nullCount = nullBitmap.length === 0 ? ( + // no null bitmap, so all values are valid + 0 + ) : this.length - popcnt_bit_range(nullBitmap, this.offset, this.offset + this.length); + } + return nullCount; + } + constructor(type, offset, length, nullCount, buffers, children = [], dictionary, variadicBuffers = []) { + var _a6; + this.type = type; + this.children = children; + this.dictionary = dictionary; + this.offset = Math.floor(Math.max(offset || 0, 0)); + this.length = Math.floor(Math.max(length || 0, 0)); + this._nullCount = Math.floor(Math.max(nullCount || 0, -1)); + let buffer; + if (buffers instanceof _Data) { + this.stride = buffers.stride; + this.values = buffers.values; + this.typeIds = buffers.typeIds; + this.nullBitmap = buffers.nullBitmap; + this.valueOffsets = buffers.valueOffsets; + this.variadicBuffers = buffers.variadicBuffers; + } else { + this.stride = strideForType(type); + if (buffers) { + (buffer = buffers[0]) && (this.valueOffsets = buffer); + (buffer = buffers[1]) && (this.values = buffer); + (buffer = buffers[2]) && (this.nullBitmap = buffer); + (buffer = buffers[3]) && (this.typeIds = buffer); + } + this.variadicBuffers = variadicBuffers; + } + (_a6 = this.variadicBuffers) !== null && _a6 !== void 0 ? _a6 : this.variadicBuffers = []; + } + getValid(index2) { + const { type } = this; + if (DataType.isUnion(type)) { + const union = type; + const typeId = this.typeIds[index2]; + const childIndex = union.typeIdToChildIndex[typeId]; + const child = this.children[childIndex]; + const valueOffsets = this.valueOffsets; + const indexInChild = union.mode === UnionMode.Dense && valueOffsets ? Number(valueOffsets[index2]) : index2; + return child.getValid(indexInChild); + } + if (this.nullable && this.nullCount > 0) { + const pos = this.offset + index2; + const val = this.nullBitmap[pos >> 3]; + return (val & 1 << pos % 8) !== 0; } + return true; } - }; - exports2.include1 = { - parameterPath: ["options", "include"], - mapper: { - serializedName: "include", - xmlName: "include", - xmlElementName: "ListBlobsIncludeItem", - type: { - name: "Sequence", - element: { - type: { - name: "Enum", - allowedValues: [ - "copy", - "deleted", - "metadata", - "snapshots", - "uncommittedblobs", - "versions", - "tags", - "immutabilitypolicy", - "legalhold", - "deletedwithversions" - ] + setValid(index2, value) { + let prev; + const { type } = this; + if (DataType.isUnion(type)) { + const union = type; + const typeId = this.typeIds[index2]; + const childIndex = union.typeIdToChildIndex[typeId]; + const child = this.children[childIndex]; + const valueOffsets = this.valueOffsets; + const indexInChild = union.mode === UnionMode.Dense && valueOffsets ? Number(valueOffsets[index2]) : index2; + prev = child.getValid(indexInChild); + child.setValid(indexInChild, value); + } else { + let { nullBitmap } = this; + const { offset, length } = this; + const idx = offset + index2; + const mask = 1 << idx % 8; + const byteOffset = idx >> 3; + if (!nullBitmap || nullBitmap.byteLength <= byteOffset) { + nullBitmap = new Uint8Array((offset + length + 63 & ~63) >> 3).fill(255); + if (this.nullCount > 0) { + nullBitmap.set(truncateBitmap(offset, length, this.nullBitmap), 0); + Object.assign(this, { nullBitmap }); + } else { + Object.assign(this, { nullBitmap, _nullCount: 0 }); } } + const byte = nullBitmap[byteOffset]; + prev = (byte & mask) !== 0; + nullBitmap[byteOffset] = value ? byte | mask : byte & ~mask; } - }, - collectionFormat: "CSV" - }; - exports2.delimiter = { - parameterPath: "delimiter", - mapper: { - serializedName: "delimiter", - required: true, - xmlName: "delimiter", - type: { - name: "String" + if (prev !== !!value) { + this._nullCount = this.nullCount + (value ? -1 : 1); } + return value; } - }; - exports2.snapshot = { - parameterPath: ["options", "snapshot"], - mapper: { - serializedName: "snapshot", - xmlName: "snapshot", - type: { - name: "String" - } + clone(type = this.type, offset = this.offset, length = this.length, nullCount = this._nullCount, buffers = this, children = this.children, variadicBuffers = this.variadicBuffers) { + return new _Data(type, offset, length, nullCount, buffers, children, this.dictionary, variadicBuffers); + } + slice(offset, length) { + const { stride, typeId, children } = this; + const nullCount = +(this._nullCount === 0) - 1; + const childStride = typeId === 16 ? stride : 1; + const buffers = this._sliceBuffers(offset, length, stride, typeId); + return this.clone( + this.type, + this.offset + offset, + length, + nullCount, + buffers, + // Don't slice children if we have value offsets (the variable-width types) + children.length === 0 || this.valueOffsets ? children : this._sliceChildren(children, childStride * offset, childStride * length), + this.variadicBuffers + ); } - }; - exports2.versionId = { - parameterPath: ["options", "versionId"], - mapper: { - serializedName: "versionid", - xmlName: "versionid", - type: { - name: "String" + _changeLengthAndBackfillNullBitmap(newLength) { + if (this.typeId === Type2.Null) { + return this.clone(this.type, 0, newLength, 0, this.buffers, this.children, this.variadicBuffers); + } + const { length, nullCount } = this; + const bitmap = new Uint8Array((newLength + 63 & ~63) >> 3).fill(255, 0, length >> 3); + bitmap[length >> 3] = (1 << length - (length & ~7)) - 1; + if (nullCount > 0) { + bitmap.set(truncateBitmap(this.offset, length, this.nullBitmap), 0); + } + const buffers = this.buffers; + buffers[BufferType.VALIDITY] = bitmap; + return this.clone(this.type, 0, newLength, nullCount + (newLength - length), buffers, this.children, this.variadicBuffers); + } + _sliceBuffers(offset, length, stride, typeId) { + let arr; + const { buffers } = this; + (arr = buffers[BufferType.TYPE]) && (buffers[BufferType.TYPE] = arr.subarray(offset, offset + length)); + if (DataType.isBinaryView(this.type) || DataType.isUtf8View(this.type)) { + const width = BinaryView2.ELEMENT_WIDTH; + (arr = buffers[BufferType.DATA]) && (buffers[BufferType.DATA] = arr.subarray(offset * width, (offset + length) * width)); + } else { + (arr = buffers[BufferType.OFFSET]) && (buffers[BufferType.OFFSET] = arr.subarray(offset, offset + length + 1)) || // Otherwise if no offsets, slice the data buffer. Don't slice the data vector for Booleans, since the offset goes by bits not bytes + (arr = buffers[BufferType.DATA]) && (buffers[BufferType.DATA] = typeId === 6 ? arr : arr.subarray(stride * offset, stride * (offset + length))); } + return buffers; } - }; - exports2.range = { - parameterPath: ["options", "range"], - mapper: { - serializedName: "x-ms-range", - xmlName: "x-ms-range", - type: { - name: "String" - } + _sliceChildren(children, offset, length) { + return children.map((child) => child.slice(offset, length)); } }; - exports2.rangeGetContentMD5 = { - parameterPath: ["options", "rangeGetContentMD5"], - mapper: { - serializedName: "x-ms-range-get-content-md5", - xmlName: "x-ms-range-get-content-md5", - type: { - name: "Boolean" - } + Data.prototype.children = Object.freeze([]); + Data.prototype[kDataSymbol] = true; + Object.defineProperty(Data, Symbol.hasInstance, { + value: function isDataInstance(instance8) { + return Function.prototype[Symbol.hasInstance].call(this, instance8) || this === Data && Data.isData(instance8); } - }; - exports2.rangeGetContentCRC64 = { - parameterPath: ["options", "rangeGetContentCRC64"], - mapper: { - serializedName: "x-ms-range-get-content-crc64", - xmlName: "x-ms-range-get-content-crc64", - type: { - name: "Boolean" - } + }); + MakeDataVisitor = class _MakeDataVisitor extends Visitor { + visit(props) { + return this.getVisitFn(props["type"]).call(this, props); + } + visitNull(props) { + const { ["type"]: type, ["offset"]: offset = 0, ["length"]: length = 0 } = props; + return new Data(type, offset, length, length); + } + visitBool(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const data = toArrayBufferView(type.ArrayType, props["data"]); + const { ["length"]: length = data.length >> 3, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [void 0, data, nullBitmap]); + } + visitInt(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const data = toArrayBufferView(type.ArrayType, props["data"]); + const { ["length"]: length = data.length, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [void 0, data, nullBitmap]); + } + visitFloat(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const data = toArrayBufferView(type.ArrayType, props["data"]); + const { ["length"]: length = data.length, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [void 0, data, nullBitmap]); + } + visitUtf8(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const data = toUint8Array(props["data"]); + const nullBitmap = toUint8Array(props["nullBitmap"]); + const valueOffsets = toInt32Array(props["valueOffsets"]); + const { ["length"]: length = valueOffsets.length - 1, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [valueOffsets, data, nullBitmap]); + } + visitUtf8View(props) { + var _a6; + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const views = toArrayBufferView(type.ArrayType, props["views"]); + const nullBitmap = toUint8Array(props["nullBitmap"]); + const variadicBuffers = (props["variadicBuffers"] || []).map((buffer) => toUint8Array(buffer)); + const length = (_a6 = props["length"]) !== null && _a6 !== void 0 ? _a6 : Math.trunc(views.length / Utf8View2.ELEMENT_WIDTH); + const nullCount = props["nullBitmap"] ? -1 : 0; + return new Data(type, offset, length, nullCount, [void 0, views, nullBitmap], [], void 0, variadicBuffers); + } + visitLargeUtf8(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const data = toUint8Array(props["data"]); + const nullBitmap = toUint8Array(props["nullBitmap"]); + const valueOffsets = toBigInt64Array(props["valueOffsets"]); + const { ["length"]: length = valueOffsets.length - 1, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [valueOffsets, data, nullBitmap]); + } + visitBinary(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const data = toUint8Array(props["data"]); + const nullBitmap = toUint8Array(props["nullBitmap"]); + const valueOffsets = toInt32Array(props["valueOffsets"]); + const { ["length"]: length = valueOffsets.length - 1, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [valueOffsets, data, nullBitmap]); + } + visitBinaryView(props) { + var _a6; + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const views = toArrayBufferView(type.ArrayType, props["views"]); + const nullBitmap = toUint8Array(props["nullBitmap"]); + const variadicBuffers = (props["variadicBuffers"] || []).map((buffer) => toUint8Array(buffer)); + const length = (_a6 = props["length"]) !== null && _a6 !== void 0 ? _a6 : Math.trunc(views.length / BinaryView2.ELEMENT_WIDTH); + const nullCount = props["nullBitmap"] ? -1 : 0; + return new Data(type, offset, length, nullCount, [void 0, views, nullBitmap], [], void 0, variadicBuffers); + } + visitLargeBinary(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const data = toUint8Array(props["data"]); + const nullBitmap = toUint8Array(props["nullBitmap"]); + const valueOffsets = toBigInt64Array(props["valueOffsets"]); + const { ["length"]: length = valueOffsets.length - 1, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [valueOffsets, data, nullBitmap]); + } + visitFixedSizeBinary(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const data = toArrayBufferView(type.ArrayType, props["data"]); + const { ["length"]: length = data.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [void 0, data, nullBitmap]); + } + visitDate(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const data = toArrayBufferView(type.ArrayType, props["data"]); + const { ["length"]: length = data.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [void 0, data, nullBitmap]); + } + visitTimestamp(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const data = toArrayBufferView(type.ArrayType, props["data"]); + const { ["length"]: length = data.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [void 0, data, nullBitmap]); + } + visitTime(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const data = toArrayBufferView(type.ArrayType, props["data"]); + const { ["length"]: length = data.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [void 0, data, nullBitmap]); + } + visitDecimal(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const data = toArrayBufferView(type.ArrayType, props["data"]); + const { ["length"]: length = data.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [void 0, data, nullBitmap]); + } + visitList(props) { + const { ["type"]: type, ["offset"]: offset = 0, ["child"]: child } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const valueOffsets = toInt32Array(props["valueOffsets"]); + const { ["length"]: length = valueOffsets.length - 1, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [valueOffsets, void 0, nullBitmap], [child]); + } + visitLargeList(props) { + const { ["type"]: type, ["offset"]: offset = 0, ["child"]: child } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const valueOffsets = toBigInt64Array(props["valueOffsets"]); + const { ["length"]: length = valueOffsets.length - 1, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [valueOffsets, void 0, nullBitmap], [child]); + } + visitStruct(props) { + const { ["type"]: type, ["offset"]: offset = 0, ["children"]: children = [] } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const { length = children.reduce((len, { length: length2 }) => Math.max(len, length2), 0), nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [void 0, void 0, nullBitmap], children); + } + visitUnion(props) { + const { ["type"]: type, ["offset"]: offset = 0, ["children"]: children = [] } = props; + const typeIds = toArrayBufferView(type.ArrayType, props["typeIds"]); + const { ["length"]: length = typeIds.length, ["nullCount"]: nullCount = -1 } = props; + if (DataType.isSparseUnion(type)) { + return new Data(type, offset, length, nullCount, [void 0, void 0, void 0, typeIds], children); + } + const valueOffsets = toInt32Array(props["valueOffsets"]); + return new Data(type, offset, length, nullCount, [valueOffsets, void 0, void 0, typeIds], children); + } + visitDictionary(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const data = toArrayBufferView(type.indices.ArrayType, props["data"]); + const { ["dictionary"]: dictionary = new Vector([new _MakeDataVisitor().visit({ type: type.dictionary })]) } = props; + const { ["length"]: length = data.length, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [void 0, data, nullBitmap], [], dictionary); + } + visitInterval(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const data = toArrayBufferView(type.ArrayType, props["data"]); + const { ["length"]: length = data.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [void 0, data, nullBitmap]); + } + visitDuration(props) { + const { ["type"]: type, ["offset"]: offset = 0 } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const data = toArrayBufferView(type.ArrayType, props["data"]); + const { ["length"]: length = data.length, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [void 0, data, nullBitmap]); + } + visitFixedSizeList(props) { + const { ["type"]: type, ["offset"]: offset = 0, ["child"]: child = new _MakeDataVisitor().visit({ type: type.valueType }) } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const { ["length"]: length = child.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [void 0, void 0, nullBitmap], [child]); + } + visitMap(props) { + const { ["type"]: type, ["offset"]: offset = 0, ["child"]: child = new _MakeDataVisitor().visit({ type: type.childType }) } = props; + const nullBitmap = toUint8Array(props["nullBitmap"]); + const valueOffsets = toInt32Array(props["valueOffsets"]); + const { ["length"]: length = valueOffsets.length - 1, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props; + return new Data(type, offset, length, nullCount, [valueOffsets, void 0, nullBitmap], [child]); + } + }; + makeDataVisitor = new MakeDataVisitor(); + } +}); + +// node_modules/apache-arrow/util/chunk.mjs +function computeChunkNullable(chunks) { + return chunks.some((chunk) => chunk.nullable); +} +function computeChunkNullCounts(chunks) { + return chunks.reduce((nullCount, chunk) => nullCount + chunk.nullCount, 0); +} +function computeChunkOffsets(chunks) { + return chunks.reduce((offsets, chunk, index2) => { + offsets[index2 + 1] = offsets[index2] + chunk.length; + return offsets; + }, new Uint32Array(chunks.length + 1)); +} +function sliceChunks(chunks, offsets, begin, end) { + const slices = []; + for (let i = -1, n = chunks.length; ++i < n; ) { + const chunk = chunks[i]; + const offset = offsets[i]; + const { length } = chunk; + if (offset >= end) { + break; + } + if (begin >= offset + length) { + continue; + } + if (offset >= begin && offset + length <= end) { + slices.push(chunk); + continue; + } + const from = Math.max(0, begin - offset); + const to = Math.min(end - offset, length); + slices.push(chunk.slice(from, to - from)); + } + if (slices.length === 0) { + slices.push(chunks[0].slice(0, 0)); + } + return slices; +} +function binarySearch(chunks, offsets, idx, fn) { + let lhs = 0, mid = 0, rhs = offsets.length - 1; + do { + if (lhs >= rhs - 1) { + return idx < offsets[rhs] ? fn(chunks, lhs, idx - offsets[lhs]) : null; + } + mid = lhs + Math.trunc((rhs - lhs) * 0.5); + idx < offsets[mid] ? rhs = mid : lhs = mid; + } while (lhs < rhs); +} +function isChunkedValid(data, index2) { + return data.getValid(index2); +} +function wrapChunkedCall1(fn) { + function chunkedFn(chunks, i, j) { + return fn(chunks[i], j); + } + return function(index2) { + const data = this.data; + return binarySearch(data, this._offsets, index2, chunkedFn); + }; +} +function wrapChunkedCall2(fn) { + let _2; + function chunkedFn(chunks, i, j) { + return fn(chunks[i], j, _2); + } + return function(index2, value) { + const data = this.data; + _2 = value; + const result = binarySearch(data, this._offsets, index2, chunkedFn); + _2 = void 0; + return result; + }; +} +function wrapChunkedIndexOf(indexOf) { + let _1; + function chunkedIndexOf(data, chunkIndex, fromIndex) { + let begin = fromIndex, index2 = 0, total = 0; + for (let i = chunkIndex - 1, n = data.length; ++i < n; ) { + const chunk = data[i]; + if (~(index2 = indexOf(chunk, _1, begin))) { + return total + index2; + } + begin = 0; + total += chunk.length; + } + return -1; + } + return function(element, offset) { + _1 = element; + const data = this.data; + const result = typeof offset !== "number" ? chunkedIndexOf(data, 0, 0) : binarySearch(data, this._offsets, offset, chunkedIndexOf); + _1 = void 0; + return result; + }; +} +var ChunkedIterator; +var init_chunk = __esm({ + "node_modules/apache-arrow/util/chunk.mjs"() { + ChunkedIterator = class { + constructor(numChunks = 0, getChunkIterator) { + this.numChunks = numChunks; + this.getChunkIterator = getChunkIterator; + this.chunkIndex = 0; + this.chunkIterator = this.getChunkIterator(0); } - }; - exports2.encryptionKey = { - parameterPath: ["options", "cpkInfo", "encryptionKey"], - mapper: { - serializedName: "x-ms-encryption-key", - xmlName: "x-ms-encryption-key", - type: { - name: "String" + next() { + while (this.chunkIndex < this.numChunks) { + const next = this.chunkIterator.next(); + if (!next.done) { + return next; + } + if (++this.chunkIndex < this.numChunks) { + this.chunkIterator = this.getChunkIterator(this.chunkIndex); + } } + return { done: true, value: null }; } - }; - exports2.encryptionKeySha256 = { - parameterPath: ["options", "cpkInfo", "encryptionKeySha256"], - mapper: { - serializedName: "x-ms-encryption-key-sha256", - xmlName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } + [Symbol.iterator]() { + return this; } }; - exports2.encryptionAlgorithm = { - parameterPath: ["options", "cpkInfo", "encryptionAlgorithm"], - mapper: { - serializedName: "x-ms-encryption-algorithm", - xmlName: "x-ms-encryption-algorithm", - type: { - name: "String" + } +}); + +// node_modules/apache-arrow/visitor/indexof.mjs +function nullIndexOf(data, searchElement) { + return searchElement === null && data.length > 0 ? 0 : -1; +} +function indexOfNull(data, fromIndex) { + const { nullBitmap } = data; + if (!nullBitmap || data.nullCount <= 0) { + return -1; + } + let i = 0; + for (const isValid of new BitIterator(nullBitmap, data.offset + (fromIndex || 0), data.length, nullBitmap, getBool2)) { + if (!isValid) { + return i; + } + ++i; + } + return -1; +} +function indexOfValue(data, searchElement, fromIndex) { + if (searchElement === void 0) { + return -1; + } + if (searchElement === null) { + switch (data.typeId) { + // Unions don't have a nullBitmap of its own, so compare the `searchElement` to `get()`. + case Type2.Union: + break; + // Dictionaries do have a nullBitmap, but their dictionary could also have null elements. + case Type2.Dictionary: + break; + // All other types can iterate the null bitmap + default: + return indexOfNull(data, fromIndex); + } + } + const get = instance2.getVisitFn(data); + const compare3 = createElementComparator(searchElement); + for (let i = (fromIndex || 0) - 1, n = data.length; ++i < n; ) { + if (compare3(get(data, i))) { + return i; + } + } + return -1; +} +function indexOfUnion(data, searchElement, fromIndex) { + const get = instance2.getVisitFn(data); + const compare3 = createElementComparator(searchElement); + for (let i = (fromIndex || 0) - 1, n = data.length; ++i < n; ) { + if (compare3(get(data, i))) { + return i; + } + } + return -1; +} +var IndexOfVisitor, instance3; +var init_indexof = __esm({ + "node_modules/apache-arrow/visitor/indexof.mjs"() { + init_enum(); + init_visitor(); + init_get(); + init_bit(); + init_vector(); + IndexOfVisitor = class extends Visitor { + }; + IndexOfVisitor.prototype.visitNull = nullIndexOf; + IndexOfVisitor.prototype.visitBool = indexOfValue; + IndexOfVisitor.prototype.visitInt = indexOfValue; + IndexOfVisitor.prototype.visitInt8 = indexOfValue; + IndexOfVisitor.prototype.visitInt16 = indexOfValue; + IndexOfVisitor.prototype.visitInt32 = indexOfValue; + IndexOfVisitor.prototype.visitInt64 = indexOfValue; + IndexOfVisitor.prototype.visitUint8 = indexOfValue; + IndexOfVisitor.prototype.visitUint16 = indexOfValue; + IndexOfVisitor.prototype.visitUint32 = indexOfValue; + IndexOfVisitor.prototype.visitUint64 = indexOfValue; + IndexOfVisitor.prototype.visitFloat = indexOfValue; + IndexOfVisitor.prototype.visitFloat16 = indexOfValue; + IndexOfVisitor.prototype.visitFloat32 = indexOfValue; + IndexOfVisitor.prototype.visitFloat64 = indexOfValue; + IndexOfVisitor.prototype.visitUtf8 = indexOfValue; + IndexOfVisitor.prototype.visitLargeUtf8 = indexOfValue; + IndexOfVisitor.prototype.visitUtf8View = indexOfValue; + IndexOfVisitor.prototype.visitBinary = indexOfValue; + IndexOfVisitor.prototype.visitLargeBinary = indexOfValue; + IndexOfVisitor.prototype.visitBinaryView = indexOfValue; + IndexOfVisitor.prototype.visitFixedSizeBinary = indexOfValue; + IndexOfVisitor.prototype.visitDate = indexOfValue; + IndexOfVisitor.prototype.visitDateDay = indexOfValue; + IndexOfVisitor.prototype.visitDateMillisecond = indexOfValue; + IndexOfVisitor.prototype.visitTimestamp = indexOfValue; + IndexOfVisitor.prototype.visitTimestampSecond = indexOfValue; + IndexOfVisitor.prototype.visitTimestampMillisecond = indexOfValue; + IndexOfVisitor.prototype.visitTimestampMicrosecond = indexOfValue; + IndexOfVisitor.prototype.visitTimestampNanosecond = indexOfValue; + IndexOfVisitor.prototype.visitTime = indexOfValue; + IndexOfVisitor.prototype.visitTimeSecond = indexOfValue; + IndexOfVisitor.prototype.visitTimeMillisecond = indexOfValue; + IndexOfVisitor.prototype.visitTimeMicrosecond = indexOfValue; + IndexOfVisitor.prototype.visitTimeNanosecond = indexOfValue; + IndexOfVisitor.prototype.visitDecimal = indexOfValue; + IndexOfVisitor.prototype.visitList = indexOfValue; + IndexOfVisitor.prototype.visitLargeList = indexOfValue; + IndexOfVisitor.prototype.visitStruct = indexOfValue; + IndexOfVisitor.prototype.visitUnion = indexOfValue; + IndexOfVisitor.prototype.visitDenseUnion = indexOfUnion; + IndexOfVisitor.prototype.visitSparseUnion = indexOfUnion; + IndexOfVisitor.prototype.visitDictionary = indexOfValue; + IndexOfVisitor.prototype.visitInterval = indexOfValue; + IndexOfVisitor.prototype.visitIntervalDayTime = indexOfValue; + IndexOfVisitor.prototype.visitIntervalYearMonth = indexOfValue; + IndexOfVisitor.prototype.visitIntervalMonthDayNano = indexOfValue; + IndexOfVisitor.prototype.visitDuration = indexOfValue; + IndexOfVisitor.prototype.visitDurationSecond = indexOfValue; + IndexOfVisitor.prototype.visitDurationMillisecond = indexOfValue; + IndexOfVisitor.prototype.visitDurationMicrosecond = indexOfValue; + IndexOfVisitor.prototype.visitDurationNanosecond = indexOfValue; + IndexOfVisitor.prototype.visitFixedSizeList = indexOfValue; + IndexOfVisitor.prototype.visitMap = indexOfValue; + instance3 = new IndexOfVisitor(); + } +}); + +// node_modules/apache-arrow/visitor/iterator.mjs +function vectorIterator(vector) { + const { type } = vector; + if (vector.nullCount === 0 && vector.stride === 1 && // Don't defer to native iterator for timestamps since Numbers are expected + // (DataType.isTimestamp(type)) && type.unit === TimeUnit.MILLISECOND || + (DataType.isInt(type) && type.bitWidth !== 64 || DataType.isTime(type) && type.bitWidth !== 64 || DataType.isFloat(type) && type.precision !== Precision.HALF)) { + return new ChunkedIterator(vector.data.length, (chunkIndex) => { + const data = vector.data[chunkIndex]; + return data.values.subarray(0, data.length)[Symbol.iterator](); + }); + } + let offset = 0; + return new ChunkedIterator(vector.data.length, (chunkIndex) => { + const data = vector.data[chunkIndex]; + const length = data.length; + const inner = vector.slice(offset, offset + length); + offset += length; + return new VectorIterator(inner); + }); +} +var IteratorVisitor, VectorIterator, instance4; +var init_iterator = __esm({ + "node_modules/apache-arrow/visitor/iterator.mjs"() { + init_visitor(); + init_enum(); + init_type2(); + init_chunk(); + IteratorVisitor = class extends Visitor { + }; + VectorIterator = class { + constructor(vector) { + this.vector = vector; + this.index = 0; + } + next() { + if (this.index < this.vector.length) { + return { + value: this.vector.get(this.index++) + }; } + return { done: true, value: null }; } - }; - exports2.ifMatch = { - parameterPath: ["options", "modifiedAccessConditions", "ifMatch"], - mapper: { - serializedName: "If-Match", - xmlName: "If-Match", - type: { - name: "String" - } + [Symbol.iterator]() { + return this; } }; - exports2.ifNoneMatch = { - parameterPath: ["options", "modifiedAccessConditions", "ifNoneMatch"], - mapper: { - serializedName: "If-None-Match", - xmlName: "If-None-Match", - type: { - name: "String" + IteratorVisitor.prototype.visitNull = vectorIterator; + IteratorVisitor.prototype.visitBool = vectorIterator; + IteratorVisitor.prototype.visitInt = vectorIterator; + IteratorVisitor.prototype.visitInt8 = vectorIterator; + IteratorVisitor.prototype.visitInt16 = vectorIterator; + IteratorVisitor.prototype.visitInt32 = vectorIterator; + IteratorVisitor.prototype.visitInt64 = vectorIterator; + IteratorVisitor.prototype.visitUint8 = vectorIterator; + IteratorVisitor.prototype.visitUint16 = vectorIterator; + IteratorVisitor.prototype.visitUint32 = vectorIterator; + IteratorVisitor.prototype.visitUint64 = vectorIterator; + IteratorVisitor.prototype.visitFloat = vectorIterator; + IteratorVisitor.prototype.visitFloat16 = vectorIterator; + IteratorVisitor.prototype.visitFloat32 = vectorIterator; + IteratorVisitor.prototype.visitFloat64 = vectorIterator; + IteratorVisitor.prototype.visitUtf8 = vectorIterator; + IteratorVisitor.prototype.visitLargeUtf8 = vectorIterator; + IteratorVisitor.prototype.visitUtf8View = vectorIterator; + IteratorVisitor.prototype.visitBinary = vectorIterator; + IteratorVisitor.prototype.visitLargeBinary = vectorIterator; + IteratorVisitor.prototype.visitBinaryView = vectorIterator; + IteratorVisitor.prototype.visitFixedSizeBinary = vectorIterator; + IteratorVisitor.prototype.visitDate = vectorIterator; + IteratorVisitor.prototype.visitDateDay = vectorIterator; + IteratorVisitor.prototype.visitDateMillisecond = vectorIterator; + IteratorVisitor.prototype.visitTimestamp = vectorIterator; + IteratorVisitor.prototype.visitTimestampSecond = vectorIterator; + IteratorVisitor.prototype.visitTimestampMillisecond = vectorIterator; + IteratorVisitor.prototype.visitTimestampMicrosecond = vectorIterator; + IteratorVisitor.prototype.visitTimestampNanosecond = vectorIterator; + IteratorVisitor.prototype.visitTime = vectorIterator; + IteratorVisitor.prototype.visitTimeSecond = vectorIterator; + IteratorVisitor.prototype.visitTimeMillisecond = vectorIterator; + IteratorVisitor.prototype.visitTimeMicrosecond = vectorIterator; + IteratorVisitor.prototype.visitTimeNanosecond = vectorIterator; + IteratorVisitor.prototype.visitDecimal = vectorIterator; + IteratorVisitor.prototype.visitList = vectorIterator; + IteratorVisitor.prototype.visitLargeList = vectorIterator; + IteratorVisitor.prototype.visitStruct = vectorIterator; + IteratorVisitor.prototype.visitUnion = vectorIterator; + IteratorVisitor.prototype.visitDenseUnion = vectorIterator; + IteratorVisitor.prototype.visitSparseUnion = vectorIterator; + IteratorVisitor.prototype.visitDictionary = vectorIterator; + IteratorVisitor.prototype.visitInterval = vectorIterator; + IteratorVisitor.prototype.visitIntervalDayTime = vectorIterator; + IteratorVisitor.prototype.visitIntervalYearMonth = vectorIterator; + IteratorVisitor.prototype.visitIntervalMonthDayNano = vectorIterator; + IteratorVisitor.prototype.visitDuration = vectorIterator; + IteratorVisitor.prototype.visitDurationSecond = vectorIterator; + IteratorVisitor.prototype.visitDurationMillisecond = vectorIterator; + IteratorVisitor.prototype.visitDurationMicrosecond = vectorIterator; + IteratorVisitor.prototype.visitDurationNanosecond = vectorIterator; + IteratorVisitor.prototype.visitFixedSizeList = vectorIterator; + IteratorVisitor.prototype.visitMap = vectorIterator; + instance4 = new IteratorVisitor(); + } +}); + +// node_modules/apache-arrow/vector.mjs +function makeVector(init2) { + if (init2) { + if (init2 instanceof Data) { + return new Vector([init2]); + } + if (init2 instanceof Vector) { + return new Vector(init2.data); + } + if (init2.type instanceof DataType) { + return new Vector([makeData(init2)]); + } + if (Array.isArray(init2)) { + return new Vector(init2.flatMap((v) => unwrapInputs(v))); + } + if (ArrayBuffer.isView(init2)) { + if (init2 instanceof DataView) { + init2 = new Uint8Array(init2.buffer); + } + const props = { offset: 0, length: init2.length, nullCount: -1, data: init2 }; + if (init2 instanceof Int8Array) { + return new Vector([makeData(Object.assign(Object.assign({}, props), { type: new Int8() }))]); + } + if (init2 instanceof Int16Array) { + return new Vector([makeData(Object.assign(Object.assign({}, props), { type: new Int16() }))]); + } + if (init2 instanceof Int32Array) { + return new Vector([makeData(Object.assign(Object.assign({}, props), { type: new Int32() }))]); + } + if (init2 instanceof BigInt64Array) { + return new Vector([makeData(Object.assign(Object.assign({}, props), { type: new Int64() }))]); + } + if (init2 instanceof Uint8Array || init2 instanceof Uint8ClampedArray) { + return new Vector([makeData(Object.assign(Object.assign({}, props), { type: new Uint8() }))]); + } + if (init2 instanceof Uint16Array) { + return new Vector([makeData(Object.assign(Object.assign({}, props), { type: new Uint16() }))]); + } + if (init2 instanceof Uint32Array) { + return new Vector([makeData(Object.assign(Object.assign({}, props), { type: new Uint32() }))]); + } + if (init2 instanceof BigUint64Array) { + return new Vector([makeData(Object.assign(Object.assign({}, props), { type: new Uint64() }))]); + } + if (init2 instanceof Float32Array) { + return new Vector([makeData(Object.assign(Object.assign({}, props), { type: new Float32() }))]); + } + if (init2 instanceof Float64Array) { + return new Vector([makeData(Object.assign(Object.assign({}, props), { type: new Float64() }))]); + } + throw new Error("Unrecognized input"); + } + } + throw new Error("Unrecognized input"); +} +function unwrapInputs(x) { + return x instanceof Data ? [x] : x instanceof Vector ? x.data : makeVector(x).data; +} +var _a2, kVectorSymbol, visitorsByTypeId, vectorPrototypesByTypeId, Vector, MemoizedVector; +var init_vector2 = __esm({ + "node_modules/apache-arrow/vector.mjs"() { + init_enum(); + init_vector(); + init_type2(); + init_data(); + init_chunk(); + init_get(); + init_set(); + init_indexof(); + init_iterator(); + init_type2(); + kVectorSymbol = /* @__PURE__ */ Symbol.for("apache-arrow/Vector"); + visitorsByTypeId = {}; + vectorPrototypesByTypeId = {}; + Vector = class _Vector { + /** + * Check if an object is an instance of Vector. + * This works across different instances of the Arrow library. + */ + /** @nocollapse */ + static isVector(x) { + return (x === null || x === void 0 ? void 0 : x[kVectorSymbol]) === true; + } + constructor(input) { + var _b2, _c2, _d2; + const data = input[0] instanceof _Vector ? input.flatMap((x) => x.data) : input; + if (data.length === 0 || data.some((x) => !(x instanceof Data))) { + throw new TypeError("Vector constructor expects an Array of Data instances."); } - } - }; - exports2.ifTags = { - parameterPath: ["options", "modifiedAccessConditions", "ifTags"], - mapper: { - serializedName: "x-ms-if-tags", - xmlName: "x-ms-if-tags", - type: { - name: "String" + const type = (_b2 = data[0]) === null || _b2 === void 0 ? void 0 : _b2.type; + switch (data.length) { + case 0: + this._offsets = [0]; + break; + case 1: { + const { get, set, indexOf } = visitorsByTypeId[type.typeId]; + const unchunkedData = data[0]; + this.isValid = (index2) => isChunkedValid(unchunkedData, index2); + this.get = (index2) => get(unchunkedData, index2); + this.set = (index2, value) => set(unchunkedData, index2, value); + this.indexOf = (index2) => indexOf(unchunkedData, index2); + this._offsets = [0, unchunkedData.length]; + break; + } + default: + Object.setPrototypeOf(this, vectorPrototypesByTypeId[type.typeId]); + this._offsets = computeChunkOffsets(data); + break; } + this.data = data; + this.type = type; + this.stride = strideForType(type); + this.numChildren = (_d2 = (_c2 = type.children) === null || _c2 === void 0 ? void 0 : _c2.length) !== null && _d2 !== void 0 ? _d2 : 0; + this.length = this._offsets.at(-1); } - }; - exports2.deleteSnapshots = { - parameterPath: ["options", "deleteSnapshots"], - mapper: { - serializedName: "x-ms-delete-snapshots", - xmlName: "x-ms-delete-snapshots", - type: { - name: "Enum", - allowedValues: ["include", "only"] - } + /** + * The aggregate size (in bytes) of this Vector's buffers and/or child Vectors. + */ + get byteLength() { + return this.data.reduce((byteLength, data) => byteLength + data.byteLength, 0); } - }; - exports2.blobDeleteType = { - parameterPath: ["options", "blobDeleteType"], - mapper: { - serializedName: "deletetype", - xmlName: "deletetype", - type: { - name: "String" - } + /** + * Whether this Vector's elements can contain null values. + */ + get nullable() { + return computeChunkNullable(this.data); } - }; - exports2.comp11 = { - parameterPath: "comp", - mapper: { - defaultValue: "expiry", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } + /** + * The number of null elements in this Vector. + */ + get nullCount() { + return computeChunkNullCounts(this.data); } - }; - exports2.expiryOptions = { - parameterPath: "expiryOptions", - mapper: { - serializedName: "x-ms-expiry-option", - required: true, - xmlName: "x-ms-expiry-option", - type: { - name: "String" - } + /** + * The Array or TypedArray constructor used for the JS representation + * of the element's values in {@link Vector.prototype.toArray `toArray()`}. + */ + get ArrayType() { + return this.type.ArrayType; } - }; - exports2.expiresOn = { - parameterPath: ["options", "expiresOn"], - mapper: { - serializedName: "x-ms-expiry-time", - xmlName: "x-ms-expiry-time", - type: { - name: "String" - } + /** + * The name that should be printed when the Vector is logged in a message. + */ + get [Symbol.toStringTag]() { + return `${this.VectorName}<${this.type[Symbol.toStringTag]}>`; } - }; - exports2.blobCacheControl = { - parameterPath: ["options", "blobHttpHeaders", "blobCacheControl"], - mapper: { - serializedName: "x-ms-blob-cache-control", - xmlName: "x-ms-blob-cache-control", - type: { - name: "String" - } + /** + * The name of this Vector. + */ + get VectorName() { + return `${Type2[this.type.typeId]}Vector`; } - }; - exports2.blobContentType = { - parameterPath: ["options", "blobHttpHeaders", "blobContentType"], - mapper: { - serializedName: "x-ms-blob-content-type", - xmlName: "x-ms-blob-content-type", - type: { - name: "String" - } + /** + * Check whether an element is null. + * @param index The index at which to read the validity bitmap. + */ + // @ts-ignore + isValid(index2) { + return false; } - }; - exports2.blobContentMD5 = { - parameterPath: ["options", "blobHttpHeaders", "blobContentMD5"], - mapper: { - serializedName: "x-ms-blob-content-md5", - xmlName: "x-ms-blob-content-md5", - type: { - name: "ByteArray" - } + /** + * Get an element value by position. + * @param index The index of the element to read. + */ + // @ts-ignore + get(index2) { + return null; } - }; - exports2.blobContentEncoding = { - parameterPath: ["options", "blobHttpHeaders", "blobContentEncoding"], - mapper: { - serializedName: "x-ms-blob-content-encoding", - xmlName: "x-ms-blob-content-encoding", - type: { - name: "String" - } + /** + * Get an element value by position. + * @param index The index of the element to read. A negative index will count back from the last element. + */ + at(index2) { + return this.get(wrapIndex(index2, this.length)); } - }; - exports2.blobContentLanguage = { - parameterPath: ["options", "blobHttpHeaders", "blobContentLanguage"], - mapper: { - serializedName: "x-ms-blob-content-language", - xmlName: "x-ms-blob-content-language", - type: { - name: "String" - } + /** + * Set an element value by position. + * @param index The index of the element to write. + * @param value The value to set. + */ + // @ts-ignore + set(index2, value) { + return; } - }; - exports2.blobContentDisposition = { - parameterPath: ["options", "blobHttpHeaders", "blobContentDisposition"], - mapper: { - serializedName: "x-ms-blob-content-disposition", - xmlName: "x-ms-blob-content-disposition", - type: { - name: "String" - } + /** + * Retrieve the index of the first occurrence of a value in an Vector. + * @param element The value to locate in the Vector. + * @param offset The index at which to begin the search. If offset is omitted, the search starts at index 0. + */ + // @ts-ignore + indexOf(element, offset) { + return -1; } - }; - exports2.comp12 = { - parameterPath: "comp", - mapper: { - defaultValue: "immutabilityPolicies", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } + includes(element, offset) { + return this.indexOf(element, offset) > -1; } - }; - exports2.immutabilityPolicyExpiry = { - parameterPath: ["options", "immutabilityPolicyExpiry"], - mapper: { - serializedName: "x-ms-immutability-policy-until-date", - xmlName: "x-ms-immutability-policy-until-date", - type: { - name: "DateTimeRfc1123" - } + /** + * Iterator for the Vector's elements. + */ + [Symbol.iterator]() { + return instance4.visit(this); } - }; - exports2.immutabilityPolicyMode = { - parameterPath: ["options", "immutabilityPolicyMode"], - mapper: { - serializedName: "x-ms-immutability-policy-mode", - xmlName: "x-ms-immutability-policy-mode", - type: { - name: "Enum", - allowedValues: ["Mutable", "Unlocked", "Locked"] + /** + * Combines two or more Vectors of the same type. + * @param others Additional Vectors to add to the end of this Vector. + */ + concat(...others) { + return new _Vector(this.data.concat(others.flatMap((x) => x.data).flat(Number.POSITIVE_INFINITY))); + } + /** + * Return a zero-copy sub-section of this Vector. + * @param start The beginning of the specified portion of the Vector. + * @param end The end of the specified portion of the Vector. This is exclusive of the element at the index 'end'. + */ + slice(begin, end) { + return new _Vector(clampRange(this, begin, end, ({ data, _offsets }, begin2, end2) => sliceChunks(data, _offsets, begin2, end2))); + } + toJSON() { + return [...this]; + } + /** + * Return a JavaScript Array or TypedArray of the Vector's elements. + * + * @note If this Vector contains a single Data chunk and the Vector's type is a + * primitive numeric type corresponding to one of the JavaScript TypedArrays, this + * method returns a zero-copy slice of the underlying TypedArray values. If there's + * more than one chunk, the resulting TypedArray will be a copy of the data from each + * chunk's underlying TypedArray values. + * + * @returns An Array or TypedArray of the Vector's elements, based on the Vector's DataType. + */ + toArray() { + const { type, data, length, stride, ArrayType } = this; + switch (type.typeId) { + case Type2.Int: + case Type2.Float: + case Type2.Decimal: + case Type2.Time: + case Type2.Timestamp: + switch (data.length) { + case 0: + return new ArrayType(); + case 1: + return data[0].values.subarray(0, length * stride); + default: + return data.reduce((memo, { values, length: chunk_length }) => { + memo.array.set(values.subarray(0, chunk_length * stride), memo.offset); + memo.offset += chunk_length * stride; + return memo; + }, { array: new ArrayType(length * stride), offset: 0 }).array; + } } + return [...this]; } - }; - exports2.comp13 = { - parameterPath: "comp", - mapper: { - defaultValue: "legalhold", - isConstant: true, - serializedName: "comp", - type: { - name: "String" + /** + * Returns a string representation of the Vector. + * + * @returns A string representation of the Vector. + */ + toString() { + return `[${[...this].join(",")}]`; + } + /** + * Returns a child Vector by name, or null if this Vector has no child with the given name. + * @param name The name of the child to retrieve. + */ + getChild(name) { + var _b2; + return this.getChildAt((_b2 = this.type.children) === null || _b2 === void 0 ? void 0 : _b2.findIndex((f) => f.name === name)); + } + /** + * Returns a child Vector by index, or null if this Vector has no child at the supplied index. + * @param index The index of the child to retrieve. + */ + getChildAt(index2) { + if (index2 > -1 && index2 < this.numChildren) { + return new _Vector(this.data.map(({ children }) => children[index2])); } + return null; } - }; - exports2.legalHold = { - parameterPath: "legalHold", - mapper: { - serializedName: "x-ms-legal-hold", - required: true, - xmlName: "x-ms-legal-hold", - type: { - name: "Boolean" + get isMemoized() { + if (DataType.isDictionary(this.type)) { + return this.data[0].dictionary.isMemoized; } + return false; } - }; - exports2.encryptionScope = { - parameterPath: ["options", "encryptionScope"], - mapper: { - serializedName: "x-ms-encryption-scope", - xmlName: "x-ms-encryption-scope", - type: { - name: "String" + /** + * Adds memoization to the Vector's {@link get} method. For dictionary + * vectors, this method return a vector that memoizes only the dictionary + * values. + * + * Memoization is very useful when decoding a value is expensive such as + * Utf8. The memoization creates a cache of the size of the Vector and + * therefore increases memory usage. + * + * @returns A new vector that memoizes calls to {@link get}. + */ + memoize() { + if (DataType.isDictionary(this.type)) { + const dictionary = new MemoizedVector(this.data[0].dictionary); + const newData = this.data.map((data) => { + const cloned = data.clone(); + cloned.dictionary = dictionary; + return cloned; + }); + return new _Vector(newData); } + return new MemoizedVector(this); } - }; - exports2.comp14 = { - parameterPath: "comp", - mapper: { - defaultValue: "snapshot", - isConstant: true, - serializedName: "comp", - type: { - name: "String" + /** + * Returns a vector without memoization of the {@link get} method. If this + * vector is not memoized, this method returns this vector. + * + * @returns A new vector without memoization. + */ + unmemoize() { + if (DataType.isDictionary(this.type) && this.isMemoized) { + const dictionary = this.data[0].dictionary.unmemoize(); + const newData = this.data.map((data) => { + const newData2 = data.clone(); + newData2.dictionary = dictionary; + return newData2; + }); + return new _Vector(newData); } + return this; } }; - exports2.tier = { - parameterPath: ["options", "tier"], - mapper: { - serializedName: "x-ms-access-tier", - xmlName: "x-ms-access-tier", - type: { - name: "Enum", - allowedValues: [ - "P4", - "P6", - "P10", - "P15", - "P20", - "P30", - "P40", - "P50", - "P60", - "P70", - "P80", - "Hot", - "Cool", - "Archive", - "Cold" - ] - } + _a2 = Symbol.toStringTag; + Vector[_a2] = ((proto) => { + proto.type = DataType.prototype; + proto.data = []; + proto.length = 0; + proto.stride = 1; + proto.numChildren = 0; + proto._offsets = new Uint32Array([0]); + proto[Symbol.isConcatSpreadable] = true; + proto[kVectorSymbol] = true; + const typeIds = Object.keys(Type2).map((T) => Type2[T]).filter((T) => typeof T === "number" && T !== Type2.NONE); + for (const typeId of typeIds) { + const get = instance2.getVisitFnByTypeId(typeId); + const set = instance.getVisitFnByTypeId(typeId); + const indexOf = instance3.getVisitFnByTypeId(typeId); + visitorsByTypeId[typeId] = { get, set, indexOf }; + vectorPrototypesByTypeId[typeId] = Object.create(proto, { + ["isValid"]: { value: wrapChunkedCall1(isChunkedValid) }, + ["get"]: { value: wrapChunkedCall1(instance2.getVisitFnByTypeId(typeId)) }, + ["set"]: { value: wrapChunkedCall2(instance.getVisitFnByTypeId(typeId)) }, + ["indexOf"]: { value: wrapChunkedIndexOf(instance3.getVisitFnByTypeId(typeId)) } + }); + } + return "Vector"; + })(Vector.prototype); + Object.defineProperty(Vector, Symbol.hasInstance, { + value: function isVectorInstance(instance8) { + return Function.prototype[Symbol.hasInstance].call(this, instance8) || this === Vector && Vector.isVector(instance8); + } + }); + MemoizedVector = class _MemoizedVector extends Vector { + constructor(vector) { + super(vector.data); + const get = this.get; + const set = this.set; + const slice = this.slice; + const cache = new Array(this.length); + Object.defineProperty(this, "get", { + value(index2) { + const cachedValue = cache[index2]; + if (cachedValue !== void 0) { + return cachedValue; + } + const value = get.call(this, index2); + cache[index2] = value; + return value; + } + }); + Object.defineProperty(this, "set", { + value(index2, value) { + set.call(this, index2, value); + cache[index2] = value; + } + }); + Object.defineProperty(this, "slice", { + value: (begin, end) => new _MemoizedVector(slice.call(this, begin, end)) + }); + Object.defineProperty(this, "isMemoized", { value: true }); + Object.defineProperty(this, "unmemoize", { + value: () => new Vector(this.data) + }); + Object.defineProperty(this, "memoize", { + value: () => this + }); } }; - exports2.rehydratePriority = { - parameterPath: ["options", "rehydratePriority"], - mapper: { - serializedName: "x-ms-rehydrate-priority", - xmlName: "x-ms-rehydrate-priority", - type: { - name: "Enum", - allowedValues: ["High", "Standard"] + } +}); + +// node_modules/apache-arrow/builder/valid.mjs +function createIsValidFunction(nullValues) { + if (!nullValues || nullValues.length <= 0) { + return function isValid(value) { + return true; + }; + } + let fnBody = ""; + const noNaNs = nullValues.filter((x) => x === x); + if (noNaNs.length > 0) { + fnBody = ` + switch (x) {${noNaNs.map((x) => ` + case ${valueToCase(x)}:`).join("")} + return false; + }`; + } + if (nullValues.length !== noNaNs.length) { + fnBody = `if (x !== x) return false; +${fnBody}`; + } + return new Function(`x`, `${fnBody} +return true;`); +} +function valueToCase(x) { + if (typeof x !== "bigint") { + return valueToString(x); + } + return `${valueToString(x)}n`; +} +var init_valid = __esm({ + "node_modules/apache-arrow/builder/valid.mjs"() { + init_pretty(); + } +}); + +// node_modules/apache-arrow/builder/buffer.mjs +function roundLengthUpToNearest64Bytes(len, BPE) { + const bytesMinus1 = Math.ceil(len) * BPE - 1; + return (bytesMinus1 - bytesMinus1 % 64 + 64 || 64) / BPE; +} +function resizeArray(arr, len = 0) { + return arr.length >= len ? arr.subarray(0, len) : memcpy(new arr.constructor(len), arr, 0); +} +var BufferBuilder, DataBufferBuilder, BitmapBufferBuilder, OffsetsBufferBuilder; +var init_buffer3 = __esm({ + "node_modules/apache-arrow/builder/buffer.mjs"() { + init_buffer(); + BufferBuilder = class { + constructor(bufferType, initialSize = 0, stride = 1) { + this.length = Math.ceil(initialSize / stride); + this.buffer = new bufferType(this.length); + this.stride = stride; + this.BYTES_PER_ELEMENT = bufferType.BYTES_PER_ELEMENT; + this.ArrayType = bufferType; + } + get byteLength() { + return Math.ceil(this.length * this.stride) * this.BYTES_PER_ELEMENT; + } + get reservedLength() { + return this.buffer.length / this.stride; + } + get reservedByteLength() { + return this.buffer.byteLength; + } + // @ts-ignore + set(index2, value) { + return this; + } + append(value) { + return this.set(this.length, value); + } + reserve(extra) { + if (extra > 0) { + this.length += extra; + const stride = this.stride; + const length = this.length * stride; + const reserved = this.buffer.length; + if (length >= reserved) { + this._resize(reserved === 0 ? roundLengthUpToNearest64Bytes(length * 1, this.BYTES_PER_ELEMENT) : roundLengthUpToNearest64Bytes(length * 2, this.BYTES_PER_ELEMENT)); + } } + return this; + } + flush(length = this.length) { + length = roundLengthUpToNearest64Bytes(length * this.stride, this.BYTES_PER_ELEMENT); + const array2 = resizeArray(this.buffer, length); + this.clear(); + return array2; + } + clear() { + this.length = 0; + this.buffer = new this.ArrayType(); + return this; + } + _resize(newLength) { + return this.buffer = resizeArray(this.buffer, newLength); } }; - exports2.sourceIfModifiedSince = { - parameterPath: [ - "options", - "sourceModifiedAccessConditions", - "sourceIfModifiedSince" - ], - mapper: { - serializedName: "x-ms-source-if-modified-since", - xmlName: "x-ms-source-if-modified-since", - type: { - name: "DateTimeRfc1123" - } + DataBufferBuilder = class extends BufferBuilder { + last() { + return this.get(this.length - 1); + } + get(index2) { + return this.buffer[index2]; + } + set(index2, value) { + this.reserve(index2 - this.length + 1); + this.buffer[index2 * this.stride] = value; + return this; } }; - exports2.sourceIfUnmodifiedSince = { - parameterPath: [ - "options", - "sourceModifiedAccessConditions", - "sourceIfUnmodifiedSince" - ], - mapper: { - serializedName: "x-ms-source-if-unmodified-since", - xmlName: "x-ms-source-if-unmodified-since", - type: { - name: "DateTimeRfc1123" - } + BitmapBufferBuilder = class extends DataBufferBuilder { + constructor() { + super(Uint8Array, 0, 1 / 8); + this.numValid = 0; + } + get numInvalid() { + return this.length - this.numValid; + } + get(idx) { + return this.buffer[idx >> 3] >> idx % 8 & 1; + } + set(idx, val) { + const { buffer } = this.reserve(idx - this.length + 1); + const byte = idx >> 3, bit = idx % 8, cur = buffer[byte] >> bit & 1; + val ? cur === 0 && (buffer[byte] |= 1 << bit, ++this.numValid) : cur === 1 && (buffer[byte] &= ~(1 << bit), --this.numValid); + return this; + } + clear() { + this.numValid = 0; + return super.clear(); } }; - exports2.sourceIfMatch = { - parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfMatch"], - mapper: { - serializedName: "x-ms-source-if-match", - xmlName: "x-ms-source-if-match", - type: { - name: "String" + OffsetsBufferBuilder = class extends DataBufferBuilder { + constructor(type) { + super(type.OffsetArrayType, 1, 1); + } + append(value) { + return this.set(this.length - 1, value); + } + set(index2, value) { + const offset = this.length - 1; + const buffer = this.reserve(index2 - offset + 1).buffer; + if (offset < index2++ && offset >= 0) { + buffer.fill(buffer[offset], offset, index2); } + buffer[index2] = buffer[index2 - 1] + value; + return this; } - }; - exports2.sourceIfNoneMatch = { - parameterPath: [ - "options", - "sourceModifiedAccessConditions", - "sourceIfNoneMatch" - ], - mapper: { - serializedName: "x-ms-source-if-none-match", - xmlName: "x-ms-source-if-none-match", - type: { - name: "String" + flush(length = this.length - 1) { + if (length > this.length) { + this.set(length - 1, this.BYTES_PER_ELEMENT > 4 ? BigInt(0) : 0); } + return super.flush(length + 1); } }; - exports2.sourceIfTags = { - parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfTags"], - mapper: { - serializedName: "x-ms-source-if-tags", - xmlName: "x-ms-source-if-tags", - type: { - name: "String" + } +}); + +// node_modules/apache-arrow/builder.mjs +var Builder, FixedWidthBuilder, VariableWidthBuilder; +var init_builder = __esm({ + "node_modules/apache-arrow/builder.mjs"() { + init_vector2(); + init_data(); + init_map2(); + init_type2(); + init_valid(); + init_buffer3(); + Builder = class { + /** @nocollapse */ + // @ts-ignore + static throughNode(options) { + throw new Error(`"throughNode" not available in this environment`); + } + /** @nocollapse */ + // @ts-ignore + static throughDOM(options) { + throw new Error(`"throughDOM" not available in this environment`); + } + /** + * Construct a builder with the given Arrow DataType with optional null values, + * which will be interpreted as "null" when set or appended to the `Builder`. + * @param {{ type: T, nullValues?: any[] }} options A `BuilderOptions` object used to create this `Builder`. + */ + constructor({ "type": type, "nullValues": nulls }) { + this.length = 0; + this.finished = false; + this.type = type; + this.children = []; + this.nullValues = nulls; + this.stride = strideForType(type); + this._nulls = new BitmapBufferBuilder(); + if (nulls && nulls.length > 0) { + this._isValid = createIsValidFunction(nulls); } } - }; - exports2.copySource = { - parameterPath: "copySource", - mapper: { - serializedName: "x-ms-copy-source", - required: true, - xmlName: "x-ms-copy-source", - type: { - name: "String" + /** + * Flush the `Builder` and return a `Vector`. + * @returns {Vector} A `Vector` of the flushed values. + */ + toVector() { + return new Vector([this.flush()]); + } + get ArrayType() { + return this.type.ArrayType; + } + get nullCount() { + return this._nulls.numInvalid; + } + get numChildren() { + return this.children.length; + } + /** + * @returns The aggregate length (in bytes) of the values that have been written. + */ + get byteLength() { + let size = 0; + const { _offsets, _values, _nulls, _typeIds, children } = this; + _offsets && (size += _offsets.byteLength); + _values && (size += _values.byteLength); + _nulls && (size += _nulls.byteLength); + _typeIds && (size += _typeIds.byteLength); + return children.reduce((size2, child) => size2 + child.byteLength, size); + } + /** + * @returns The aggregate number of rows that have been reserved to write new values. + */ + get reservedLength() { + return this._nulls.reservedLength; + } + /** + * @returns The aggregate length (in bytes) that has been reserved to write new values. + */ + get reservedByteLength() { + let size = 0; + this._offsets && (size += this._offsets.reservedByteLength); + this._values && (size += this._values.reservedByteLength); + this._nulls && (size += this._nulls.reservedByteLength); + this._typeIds && (size += this._typeIds.reservedByteLength); + return this.children.reduce((size2, child) => size2 + child.reservedByteLength, size); + } + get valueOffsets() { + return this._offsets ? this._offsets.buffer : null; + } + get values() { + return this._values ? this._values.buffer : null; + } + get nullBitmap() { + return this._nulls ? this._nulls.buffer : null; + } + get typeIds() { + return this._typeIds ? this._typeIds.buffer : null; + } + /** + * Appends a value (or null) to this `Builder`. + * This is equivalent to `builder.set(builder.length, value)`. + * @param {T['TValue'] | TNull } value The value to append. + */ + append(value) { + return this.set(this.length, value); + } + /** + * Validates whether a value is valid (true), or null (false) + * @param {T['TValue'] | TNull } value The value to compare against null the value representations + */ + isValid(value) { + return this._isValid(value); + } + /** + * Write a value (or null-value sentinel) at the supplied index. + * If the value matches one of the null-value representations, a 1-bit is + * written to the null `BitmapBufferBuilder`. Otherwise, a 0 is written to + * the null `BitmapBufferBuilder`, and the value is passed to + * `Builder.prototype.setValue()`. + * @param {number} index The index of the value to write. + * @param {T['TValue'] | TNull } value The value to write at the supplied index. + * @returns {this} The updated `Builder` instance. + */ + set(index2, value) { + if (this.setValid(index2, this.isValid(value))) { + this.setValue(index2, value); } + return this; } - }; - exports2.blobTagsString = { - parameterPath: ["options", "blobTagsString"], - mapper: { - serializedName: "x-ms-tags", - xmlName: "x-ms-tags", - type: { - name: "String" + /** + * Write a value to the underlying buffers at the supplied index, bypassing + * the null-value check. This is a low-level method that + * @param {number} index + * @param {T['TValue'] | TNull } value + */ + setValue(index2, value) { + this._setValue(this, index2, value); + } + setValid(index2, valid4) { + this.length = this._nulls.set(index2, +valid4).length; + return valid4; + } + // @ts-ignore + addChild(child, name = `${this.numChildren}`) { + throw new Error(`Cannot append children to non-nested type "${this.type}"`); + } + /** + * Retrieve the child `Builder` at the supplied `index`, or null if no child + * exists at that index. + * @param {number} index The index of the child `Builder` to retrieve. + * @returns {Builder | null} The child Builder at the supplied index or null. + */ + getChildAt(index2) { + return this.children[index2] || null; + } + /** + * Commit all the values that have been written to their underlying + * ArrayBuffers, including any child Builders if applicable, and reset + * the internal `Builder` state. + * @returns A `Data` of the buffers and children representing the values written. + */ + flush() { + let data; + let typeIds; + let nullBitmap; + let valueOffsets; + const { type, length, nullCount, _typeIds, _offsets, _values, _nulls } = this; + if (typeIds = _typeIds === null || _typeIds === void 0 ? void 0 : _typeIds.flush(length)) { + valueOffsets = _offsets === null || _offsets === void 0 ? void 0 : _offsets.flush(length); + } else if (valueOffsets = _offsets === null || _offsets === void 0 ? void 0 : _offsets.flush(length)) { + data = _values === null || _values === void 0 ? void 0 : _values.flush(_offsets.last()); + } else { + data = _values === null || _values === void 0 ? void 0 : _values.flush(length); } + if (nullCount > 0) { + nullBitmap = _nulls === null || _nulls === void 0 ? void 0 : _nulls.flush(length); + } + const children = this.children.map((child) => child.flush()); + this.clear(); + return makeData({ + type, + length, + nullCount, + children, + "child": children[0], + data, + typeIds, + nullBitmap, + valueOffsets + }); + } + /** + * Finalize this `Builder`, and child builders if applicable. + * @returns {this} The finalized `Builder` instance. + */ + finish() { + this.finished = true; + for (const child of this.children) + child.finish(); + return this; + } + /** + * Clear this Builder's internal state, including child Builders if applicable, and reset the length to 0. + * @returns {this} The cleared `Builder` instance. + */ + clear() { + var _a6, _b2, _c2, _d2; + this.length = 0; + (_a6 = this._nulls) === null || _a6 === void 0 ? void 0 : _a6.clear(); + (_b2 = this._values) === null || _b2 === void 0 ? void 0 : _b2.clear(); + (_c2 = this._offsets) === null || _c2 === void 0 ? void 0 : _c2.clear(); + (_d2 = this._typeIds) === null || _d2 === void 0 ? void 0 : _d2.clear(); + for (const child of this.children) + child.clear(); + return this; } }; - exports2.sealBlob = { - parameterPath: ["options", "sealBlob"], - mapper: { - serializedName: "x-ms-seal-blob", - xmlName: "x-ms-seal-blob", - type: { - name: "Boolean" - } + Builder.prototype.length = 1; + Builder.prototype.stride = 1; + Builder.prototype.children = null; + Builder.prototype.finished = false; + Builder.prototype.nullValues = null; + Builder.prototype._isValid = () => true; + FixedWidthBuilder = class extends Builder { + constructor(opts) { + super(opts); + this._values = new DataBufferBuilder(this.ArrayType, 0, this.stride); } - }; - exports2.legalHold1 = { - parameterPath: ["options", "legalHold"], - mapper: { - serializedName: "x-ms-legal-hold", - xmlName: "x-ms-legal-hold", - type: { - name: "Boolean" - } + setValue(index2, value) { + const values = this._values; + values.reserve(index2 - values.length + 1); + return super.setValue(index2, value); } }; - exports2.xMsRequiresSync = { - parameterPath: "xMsRequiresSync", - mapper: { - defaultValue: "true", - isConstant: true, - serializedName: "x-ms-requires-sync", - type: { - name: "String" + VariableWidthBuilder = class extends Builder { + constructor(opts) { + super(opts); + this._pendingLength = 0; + this._offsets = new OffsetsBufferBuilder(opts.type); + } + setValue(index2, value) { + const pending = this._pending || (this._pending = /* @__PURE__ */ new Map()); + const current = pending.get(index2); + current && (this._pendingLength -= current.length); + this._pendingLength += value instanceof MapRow ? value[kKeys].length : value.length; + pending.set(index2, value); + } + setValid(index2, isValid) { + if (!super.setValid(index2, isValid)) { + (this._pending || (this._pending = /* @__PURE__ */ new Map())).set(index2, void 0); + return false; } + return true; } - }; - exports2.sourceContentMD5 = { - parameterPath: ["options", "sourceContentMD5"], - mapper: { - serializedName: "x-ms-source-content-md5", - xmlName: "x-ms-source-content-md5", - type: { - name: "ByteArray" - } + clear() { + this._pendingLength = 0; + this._pending = void 0; + return super.clear(); } - }; - exports2.copySourceAuthorization = { - parameterPath: ["options", "copySourceAuthorization"], - mapper: { - serializedName: "x-ms-copy-source-authorization", - xmlName: "x-ms-copy-source-authorization", - type: { - name: "String" - } + flush() { + this._flush(); + return super.flush(); } - }; - exports2.copySourceTags = { - parameterPath: ["options", "copySourceTags"], - mapper: { - serializedName: "x-ms-copy-source-tag-option", - xmlName: "x-ms-copy-source-tag-option", - type: { - name: "Enum", - allowedValues: ["REPLACE", "COPY"] - } + finish() { + this._flush(); + return super.finish(); } - }; - exports2.fileRequestIntent = { - parameterPath: ["options", "fileRequestIntent"], - mapper: { - serializedName: "x-ms-file-request-intent", - xmlName: "x-ms-file-request-intent", - type: { - name: "String" + _flush() { + const pending = this._pending; + const pendingLength = this._pendingLength; + this._pendingLength = 0; + this._pending = void 0; + if (pending && pending.size > 0) { + this._flushPending(pending, pendingLength); } + return this; } }; - exports2.comp15 = { - parameterPath: "comp", - mapper: { - defaultValue: "copy", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } + } +}); + +// node_modules/apache-arrow/fb/block.mjs +var Block; +var init_block = __esm({ + "node_modules/apache-arrow/fb/block.mjs"() { + Block = class { + constructor() { + this.bb = null; + this.bb_pos = 0; } - }; - exports2.copyActionAbortConstant = { - parameterPath: "copyActionAbortConstant", - mapper: { - defaultValue: "abort", - isConstant: true, - serializedName: "x-ms-copy-action", - type: { - name: "String" - } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; } - }; - exports2.copyId = { - parameterPath: "copyId", - mapper: { - serializedName: "copyid", - required: true, - xmlName: "copyid", - type: { - name: "String" - } + /** + * Index to the start of the RecordBlock (note this is past the Message header) + */ + offset() { + return this.bb.readInt64(this.bb_pos); } - }; - exports2.comp16 = { - parameterPath: "comp", - mapper: { - defaultValue: "tier", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } + /** + * Length of the metadata + */ + metaDataLength() { + return this.bb.readInt32(this.bb_pos + 8); } - }; - exports2.tier1 = { - parameterPath: "tier", - mapper: { - serializedName: "x-ms-access-tier", - required: true, - xmlName: "x-ms-access-tier", - type: { - name: "Enum", - allowedValues: [ - "P4", - "P6", - "P10", - "P15", - "P20", - "P30", - "P40", - "P50", - "P60", - "P70", - "P80", - "Hot", - "Cool", - "Archive", - "Cold" - ] - } + /** + * Length of the data (this is aligned so there can be a gap between this and + * the metadata). + */ + bodyLength() { + return this.bb.readInt64(this.bb_pos + 16); } - }; - exports2.queryRequest = { - parameterPath: ["options", "queryRequest"], - mapper: mappers_js_1.QueryRequest - }; - exports2.comp17 = { - parameterPath: "comp", - mapper: { - defaultValue: "query", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } + static sizeOf() { + return 24; + } + static createBlock(builder, offset, metaDataLength, bodyLength) { + builder.prep(8, 24); + builder.writeInt64(BigInt(bodyLength !== null && bodyLength !== void 0 ? bodyLength : 0)); + builder.pad(4); + builder.writeInt32(metaDataLength); + builder.writeInt64(BigInt(offset !== null && offset !== void 0 ? offset : 0)); + return builder.offset(); } }; - exports2.comp18 = { - parameterPath: "comp", - mapper: { - defaultValue: "tags", - isConstant: true, - serializedName: "comp", - type: { - name: "String" + } +}); + +// node_modules/apache-arrow/fb/footer.mjs +var flatbuffers31, Footer; +var init_footer = __esm({ + "node_modules/apache-arrow/fb/footer.mjs"() { + flatbuffers31 = __toESM(require_flatbuffers(), 1); + init_block(); + init_key_value(); + init_metadata_version(); + init_schema(); + Footer = class _Footer { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsFooter(bb, obj) { + return (obj || new _Footer()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsFooter(bb, obj) { + bb.setPosition(bb.position() + flatbuffers31.SIZE_PREFIX_LENGTH); + return (obj || new _Footer()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + version() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt16(this.bb_pos + offset) : MetadataVersion.V1; + } + schema(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Schema3()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + dictionaries(index2, obj) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? (obj || new Block()).__init(this.bb.__vector(this.bb_pos + offset) + index2 * 24, this.bb) : null; + } + dictionariesLength() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + recordBatches(index2, obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? (obj || new Block()).__init(this.bb.__vector(this.bb_pos + offset) + index2 * 24, this.bb) : null; + } + recordBatchesLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + /** + * User-defined metadata + */ + customMetadata(index2, obj) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null; + } + customMetadataLength() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static startFooter(builder) { + builder.startObject(5); + } + static addVersion(builder, version) { + builder.addFieldInt16(0, version, MetadataVersion.V1); + } + static addSchema(builder, schemaOffset) { + builder.addFieldOffset(1, schemaOffset, 0); + } + static addDictionaries(builder, dictionariesOffset) { + builder.addFieldOffset(2, dictionariesOffset, 0); + } + static startDictionariesVector(builder, numElems) { + builder.startVector(24, numElems, 8); + } + static addRecordBatches(builder, recordBatchesOffset) { + builder.addFieldOffset(3, recordBatchesOffset, 0); + } + static startRecordBatchesVector(builder, numElems) { + builder.startVector(24, numElems, 8); + } + static addCustomMetadata(builder, customMetadataOffset) { + builder.addFieldOffset(4, customMetadataOffset, 0); + } + static createCustomMetadataVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); } + return builder.endVector(); + } + static startCustomMetadataVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endFooter(builder) { + const offset = builder.endObject(); + return offset; + } + static finishFooterBuffer(builder, offset) { + builder.finish(offset); + } + static finishSizePrefixedFooterBuffer(builder, offset) { + builder.finish(offset, void 0, true); } }; - exports2.tags = { - parameterPath: ["options", "tags"], - mapper: mappers_js_1.BlobTags - }; - exports2.transactionalContentMD5 = { - parameterPath: ["options", "transactionalContentMD5"], - mapper: { - serializedName: "Content-MD5", - xmlName: "Content-MD5", - type: { - name: "ByteArray" + } +}); + +// node_modules/apache-arrow/schema.mjs +function mergeMaps(m1, m2) { + return new Map([...m1 || /* @__PURE__ */ new Map(), ...m2 || /* @__PURE__ */ new Map()]); +} +function generateDictionaryMap(fields, dictionaries = /* @__PURE__ */ new Map()) { + for (let i = -1, n = fields.length; ++i < n; ) { + const field = fields[i]; + const type = field.type; + if (DataType.isDictionary(type)) { + if (!dictionaries.has(type.id)) { + dictionaries.set(type.id, type.dictionary); + } else if (dictionaries.get(type.id) !== type.dictionary) { + throw new Error(`Cannot create Schema containing two different dictionaries with the same Id`); + } + } + if (type.children && type.children.length > 0) { + generateDictionaryMap(type.children, dictionaries); + } + } + return dictionaries; +} +var kSchemaSymbol, kFieldSymbol, Schema4, Field2; +var init_schema2 = __esm({ + "node_modules/apache-arrow/schema.mjs"() { + init_enum(); + init_type2(); + kSchemaSymbol = /* @__PURE__ */ Symbol.for("apache-arrow/Schema"); + kFieldSymbol = /* @__PURE__ */ Symbol.for("apache-arrow/Field"); + Schema4 = class _Schema { + /** + * Check if an object is an instance of Schema. + * This works across different instances of the Arrow library. + */ + /** @nocollapse */ + static isSchema(x) { + return (x === null || x === void 0 ? void 0 : x[kSchemaSymbol]) === true; + } + constructor(fields = [], metadata, dictionaries, metadataVersion = MetadataVersion.V5) { + this.fields = fields || []; + this.metadata = metadata || /* @__PURE__ */ new Map(); + if (!dictionaries) { + dictionaries = generateDictionaryMap(this.fields); } + this.dictionaries = dictionaries; + this.metadataVersion = metadataVersion; + } + get [Symbol.toStringTag]() { + return "Schema"; + } + get names() { + return this.fields.map((f) => f.name); + } + toString() { + return `Schema<{ ${this.fields.map((f, i) => `${i}: ${f}`).join(", ")} }>`; + } + /** + * Construct a new Schema containing only specified fields. + * + * @param fieldNames Names of fields to keep. + * @returns A new Schema of fields matching the specified names. + */ + select(fieldNames) { + const names = new Set(fieldNames); + const fields = this.fields.filter((f) => names.has(f.name)); + return new _Schema(fields, this.metadata); + } + /** + * Construct a new Schema containing only fields at the specified indices. + * + * @param fieldIndices Indices of fields to keep. + * @returns A new Schema of fields at the specified indices. + */ + selectAt(fieldIndices) { + const fields = fieldIndices.map((i) => this.fields[i]).filter(Boolean); + return new _Schema(fields, this.metadata); + } + assign(...args) { + const other = args[0] instanceof _Schema ? args[0] : Array.isArray(args[0]) ? new _Schema(args[0]) : new _Schema(args); + const curFields = [...this.fields]; + const metadata = mergeMaps(mergeMaps(/* @__PURE__ */ new Map(), this.metadata), other.metadata); + const newFields = other.fields.filter((f2) => { + const i = curFields.findIndex((f) => f.name === f2.name); + return ~i ? (curFields[i] = f2.clone({ + metadata: mergeMaps(mergeMaps(/* @__PURE__ */ new Map(), curFields[i].metadata), f2.metadata) + })) && false : true; + }); + const newDictionaries = generateDictionaryMap(newFields, /* @__PURE__ */ new Map()); + return new _Schema([...curFields, ...newFields], metadata, new Map([...this.dictionaries, ...newDictionaries])); } }; - exports2.transactionalContentCrc64 = { - parameterPath: ["options", "transactionalContentCrc64"], - mapper: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", - type: { - name: "ByteArray" + Schema4.prototype.fields = null; + Schema4.prototype.metadata = null; + Schema4.prototype.dictionaries = null; + Schema4.prototype[kSchemaSymbol] = true; + Object.defineProperty(Schema4, Symbol.hasInstance, { + value: function isSchemaInstance(instance8) { + return Function.prototype[Symbol.hasInstance].call(this, instance8) || this === Schema4 && Schema4.isSchema(instance8); + } + }); + Field2 = class _Field { + /** + * Check if an object is an instance of Field. + * This works across different instances of the Arrow library. + */ + /** @nocollapse */ + static isField(x) { + return (x === null || x === void 0 ? void 0 : x[kFieldSymbol]) === true; + } + /** @nocollapse */ + static new(...args) { + let [name, type, nullable, metadata] = args; + if (args[0] && typeof args[0] === "object") { + ({ name } = args[0]); + type === void 0 && (type = args[0].type); + nullable === void 0 && (nullable = args[0].nullable); + metadata === void 0 && (metadata = args[0].metadata); } + return new _Field(`${name}`, type, nullable, metadata); + } + constructor(name, type, nullable = false, metadata) { + this.name = name; + this.type = type; + this.nullable = nullable; + this.metadata = metadata || /* @__PURE__ */ new Map(); + } + get typeId() { + return this.type.typeId; + } + get [Symbol.toStringTag]() { + return "Field"; + } + toString() { + return `${this.name}: ${this.type}`; + } + clone(...args) { + let [name, type, nullable, metadata] = args; + !args[0] || typeof args[0] !== "object" ? [name = this.name, type = this.type, nullable = this.nullable, metadata = this.metadata] = args : { name = this.name, type = this.type, nullable = this.nullable, metadata = this.metadata } = args[0]; + return _Field.new(name, type, nullable, metadata); } }; - exports2.blobType = { - parameterPath: "blobType", - mapper: { - defaultValue: "PageBlob", - isConstant: true, - serializedName: "x-ms-blob-type", - type: { - name: "String" + Field2.prototype.type = null; + Field2.prototype.name = null; + Field2.prototype.nullable = null; + Field2.prototype.metadata = null; + Field2.prototype[kFieldSymbol] = true; + Object.defineProperty(Field2, Symbol.hasInstance, { + value: function isFieldInstance(instance8) { + return Function.prototype[Symbol.hasInstance].call(this, instance8) || this === Field2 && Field2.isField(instance8); + } + }); + } +}); + +// node_modules/apache-arrow/ipc/metadata/file.mjs +var flatbuffers32, Builder3, ByteBuffer2, Footer_, OffHeapFooter, FileBlock; +var init_file = __esm({ + "node_modules/apache-arrow/ipc/metadata/file.mjs"() { + init_block(); + init_footer(); + flatbuffers32 = __toESM(require_flatbuffers(), 1); + init_schema2(); + init_enum(); + init_buffer(); + init_bigint(); + Builder3 = flatbuffers32.Builder; + ByteBuffer2 = flatbuffers32.ByteBuffer; + Footer_ = class { + /** @nocollapse */ + static decode(buf) { + buf = new ByteBuffer2(toUint8Array(buf)); + const footer = Footer.getRootAsFooter(buf); + const schema = Schema4.decode(footer.schema(), /* @__PURE__ */ new Map(), footer.version()); + return new OffHeapFooter(schema, footer); + } + /** @nocollapse */ + static encode(footer) { + const b = new Builder3(); + const schemaOffset = Schema4.encode(b, footer.schema); + Footer.startRecordBatchesVector(b, footer.numRecordBatches); + for (const rb of [...footer.recordBatches()].slice().reverse()) { + FileBlock.encode(b, rb); + } + const recordBatchesOffset = b.endVector(); + Footer.startDictionariesVector(b, footer.numDictionaries); + for (const db of [...footer.dictionaryBatches()].slice().reverse()) { + FileBlock.encode(b, db); + } + const dictionaryBatchesOffset = b.endVector(); + Footer.startFooter(b); + Footer.addSchema(b, schemaOffset); + Footer.addVersion(b, MetadataVersion.V5); + Footer.addRecordBatches(b, recordBatchesOffset); + Footer.addDictionaries(b, dictionaryBatchesOffset); + Footer.finishFooterBuffer(b, Footer.endFooter(b)); + return b.asUint8Array(); + } + get numRecordBatches() { + return this._recordBatches.length; + } + get numDictionaries() { + return this._dictionaryBatches.length; + } + constructor(schema, version = MetadataVersion.V5, recordBatches, dictionaryBatches) { + this.schema = schema; + this.version = version; + recordBatches && (this._recordBatches = recordBatches); + dictionaryBatches && (this._dictionaryBatches = dictionaryBatches); + } + *recordBatches() { + for (let block, i = -1, n = this.numRecordBatches; ++i < n; ) { + if (block = this.getRecordBatch(i)) { + yield block; + } } } - }; - exports2.blobContentLength = { - parameterPath: "blobContentLength", - mapper: { - serializedName: "x-ms-blob-content-length", - required: true, - xmlName: "x-ms-blob-content-length", - type: { - name: "Number" + *dictionaryBatches() { + for (let block, i = -1, n = this.numDictionaries; ++i < n; ) { + if (block = this.getDictionaryBatch(i)) { + yield block; + } } } + getRecordBatch(index2) { + return index2 >= 0 && index2 < this.numRecordBatches && this._recordBatches[index2] || null; + } + getDictionaryBatch(index2) { + return index2 >= 0 && index2 < this.numDictionaries && this._dictionaryBatches[index2] || null; + } }; - exports2.blobSequenceNumber = { - parameterPath: ["options", "blobSequenceNumber"], - mapper: { - defaultValue: 0, - serializedName: "x-ms-blob-sequence-number", - xmlName: "x-ms-blob-sequence-number", - type: { - name: "Number" + OffHeapFooter = class extends Footer_ { + get numRecordBatches() { + return this._footer.recordBatchesLength(); + } + get numDictionaries() { + return this._footer.dictionariesLength(); + } + constructor(schema, _footer) { + super(schema, _footer.version()); + this._footer = _footer; + } + getRecordBatch(index2) { + if (index2 >= 0 && index2 < this.numRecordBatches) { + const fileBlock = this._footer.recordBatches(index2); + if (fileBlock) { + return FileBlock.decode(fileBlock); + } } + return null; } - }; - exports2.contentType1 = { - parameterPath: ["options", "contentType"], - mapper: { - defaultValue: "application/octet-stream", - isConstant: true, - serializedName: "Content-Type", - type: { - name: "String" + getDictionaryBatch(index2) { + if (index2 >= 0 && index2 < this.numDictionaries) { + const fileBlock = this._footer.dictionaries(index2); + if (fileBlock) { + return FileBlock.decode(fileBlock); + } } + return null; } }; - exports2.body1 = { - parameterPath: "body", - mapper: { - serializedName: "body", - required: true, - xmlName: "body", - type: { - name: "Stream" - } + FileBlock = class _FileBlock { + /** @nocollapse */ + static decode(block) { + return new _FileBlock(block.metaDataLength(), block.bodyLength(), block.offset()); + } + /** @nocollapse */ + static encode(b, fileBlock) { + const { metaDataLength } = fileBlock; + const offset = BigInt(fileBlock.offset); + const bodyLength = BigInt(fileBlock.bodyLength); + return Block.createBlock(b, offset, metaDataLength, bodyLength); + } + constructor(metaDataLength, bodyLength, offset) { + this.metaDataLength = metaDataLength; + this.offset = bigIntToNumber(offset); + this.bodyLength = bigIntToNumber(bodyLength); } }; - exports2.accept2 = { - parameterPath: "accept", - mapper: { - defaultValue: "application/xml", - isConstant: true, - serializedName: "Accept", - type: { - name: "String" + } +}); + +// node_modules/apache-arrow/fb/message.mjs +var flatbuffers33, Message; +var init_message = __esm({ + "node_modules/apache-arrow/fb/message.mjs"() { + flatbuffers33 = __toESM(require_flatbuffers(), 1); + init_key_value(); + init_message_header(); + init_metadata_version(); + Message = class _Message { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsMessage(bb, obj) { + return (obj || new _Message()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsMessage(bb, obj) { + bb.setPosition(bb.position() + flatbuffers33.SIZE_PREFIX_LENGTH); + return (obj || new _Message()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + version() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt16(this.bb_pos + offset) : MetadataVersion.V1; + } + headerType() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readUint8(this.bb_pos + offset) : MessageHeader.NONE; + } + header(obj) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.__union(obj, this.bb_pos + offset) : null; + } + bodyLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0"); + } + customMetadata(index2, obj) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index2 * 4), this.bb) : null; + } + customMetadataLength() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static startMessage(builder) { + builder.startObject(5); + } + static addVersion(builder, version) { + builder.addFieldInt16(0, version, MetadataVersion.V1); + } + static addHeaderType(builder, headerType) { + builder.addFieldInt8(1, headerType, MessageHeader.NONE); + } + static addHeader(builder, headerOffset) { + builder.addFieldOffset(2, headerOffset, 0); + } + static addBodyLength(builder, bodyLength) { + builder.addFieldInt64(3, bodyLength, BigInt("0")); + } + static addCustomMetadata(builder, customMetadataOffset) { + builder.addFieldOffset(4, customMetadataOffset, 0); + } + static createCustomMetadataVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startCustomMetadataVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endMessage(builder) { + const offset = builder.endObject(); + return offset; + } + static finishMessageBuffer(builder, offset) { + builder.finish(offset); + } + static finishSizePrefixedMessageBuffer(builder, offset) { + builder.finish(offset, void 0, true); + } + static createMessage(builder, version, headerType, headerOffset, bodyLength, customMetadataOffset) { + _Message.startMessage(builder); + _Message.addVersion(builder, version); + _Message.addHeaderType(builder, headerType); + _Message.addHeader(builder, headerOffset); + _Message.addBodyLength(builder, bodyLength); + _Message.addCustomMetadata(builder, customMetadataOffset); + return _Message.endMessage(builder); + } + }; + } +}); + +// node_modules/apache-arrow/visitor/typeassembler.mjs +var TypeAssembler, instance5; +var init_typeassembler = __esm({ + "node_modules/apache-arrow/visitor/typeassembler.mjs"() { + init_visitor(); + init_null(); + init_int(); + init_floating_point(); + init_binary(); + init_binary_view(); + init_large_binary(); + init_bool(); + init_utf82(); + init_utf8_view(); + init_large_utf8(); + init_decimal(); + init_date(); + init_time(); + init_timestamp(); + init_interval(); + init_duration(); + init_list(); + init_large_list(); + init_struct(); + init_union(); + init_dictionary_encoding(); + init_fixed_size_binary(); + init_fixed_size_list(); + init_map(); + TypeAssembler = class extends Visitor { + visit(node, builder) { + return node == null || builder == null ? void 0 : super.visit(node, builder); + } + visitNull(_node, b) { + Null.startNull(b); + return Null.endNull(b); + } + visitInt(node, b) { + Int.startInt(b); + Int.addBitWidth(b, node.bitWidth); + Int.addIsSigned(b, node.isSigned); + return Int.endInt(b); + } + visitFloat(node, b) { + FloatingPoint.startFloatingPoint(b); + FloatingPoint.addPrecision(b, node.precision); + return FloatingPoint.endFloatingPoint(b); + } + visitBinary(_node, b) { + Binary.startBinary(b); + return Binary.endBinary(b); + } + visitBinaryView(_node, b) { + BinaryView.startBinaryView(b); + return BinaryView.endBinaryView(b); + } + visitLargeBinary(_node, b) { + LargeBinary.startLargeBinary(b); + return LargeBinary.endLargeBinary(b); + } + visitBool(_node, b) { + Bool.startBool(b); + return Bool.endBool(b); + } + visitUtf8(_node, b) { + Utf8.startUtf8(b); + return Utf8.endUtf8(b); + } + visitUtf8View(_node, b) { + Utf8View.startUtf8View(b); + return Utf8View.endUtf8View(b); + } + visitLargeUtf8(_node, b) { + LargeUtf8.startLargeUtf8(b); + return LargeUtf8.endLargeUtf8(b); + } + visitDecimal(node, b) { + Decimal.startDecimal(b); + Decimal.addScale(b, node.scale); + Decimal.addPrecision(b, node.precision); + Decimal.addBitWidth(b, node.bitWidth); + return Decimal.endDecimal(b); + } + visitDate(node, b) { + Date2.startDate(b); + Date2.addUnit(b, node.unit); + return Date2.endDate(b); + } + visitTime(node, b) { + Time.startTime(b); + Time.addUnit(b, node.unit); + Time.addBitWidth(b, node.bitWidth); + return Time.endTime(b); + } + visitTimestamp(node, b) { + const timezone = node.timezone && b.createString(node.timezone) || void 0; + Timestamp.startTimestamp(b); + Timestamp.addUnit(b, node.unit); + if (timezone !== void 0) { + Timestamp.addTimezone(b, timezone); + } + return Timestamp.endTimestamp(b); + } + visitInterval(node, b) { + Interval.startInterval(b); + Interval.addUnit(b, node.unit); + return Interval.endInterval(b); + } + visitDuration(node, b) { + Duration.startDuration(b); + Duration.addUnit(b, node.unit); + return Duration.endDuration(b); + } + visitList(_node, b) { + List.startList(b); + return List.endList(b); + } + visitLargeList(_node, b) { + LargeList.startLargeList(b); + return LargeList.endLargeList(b); + } + visitStruct(_node, b) { + Struct_.startStruct_(b); + return Struct_.endStruct_(b); + } + visitUnion(node, b) { + Union.startTypeIdsVector(b, node.typeIds.length); + const typeIds = Union.createTypeIdsVector(b, node.typeIds); + Union.startUnion(b); + Union.addMode(b, node.mode); + Union.addTypeIds(b, typeIds); + return Union.endUnion(b); + } + visitDictionary(node, b) { + const indexType = this.visit(node.indices, b); + DictionaryEncoding.startDictionaryEncoding(b); + DictionaryEncoding.addId(b, BigInt(node.id)); + DictionaryEncoding.addIsOrdered(b, node.isOrdered); + if (indexType !== void 0) { + DictionaryEncoding.addIndexType(b, indexType); + } + return DictionaryEncoding.endDictionaryEncoding(b); + } + visitFixedSizeBinary(node, b) { + FixedSizeBinary.startFixedSizeBinary(b); + FixedSizeBinary.addByteWidth(b, node.byteWidth); + return FixedSizeBinary.endFixedSizeBinary(b); + } + visitFixedSizeList(node, b) { + FixedSizeList.startFixedSizeList(b); + FixedSizeList.addListSize(b, node.listSize); + return FixedSizeList.endFixedSizeList(b); + } + visitMap(node, b) { + Map2.startMap(b); + Map2.addKeysSorted(b, node.keysSorted); + return Map2.endMap(b); + } + }; + instance5 = new TypeAssembler(); + } +}); + +// node_modules/apache-arrow/ipc/metadata/json.mjs +function schemaFromJSON(_schema, dictionaries = /* @__PURE__ */ new Map()) { + return new Schema4(schemaFieldsFromJSON(_schema, dictionaries), customMetadataFromJSON(_schema["metadata"]), dictionaries); +} +function recordBatchFromJSON(b) { + return new RecordBatch2(b["count"], fieldNodesFromJSON(b["columns"]), buffersFromJSON(b["columns"]), null, variadicBufferCountsFromJSON(b["columns"])); +} +function dictionaryBatchFromJSON(b) { + return new DictionaryBatch2(recordBatchFromJSON(b["data"]), b["id"], b["isDelta"]); +} +function schemaFieldsFromJSON(_schema, dictionaries) { + return (_schema["fields"] || []).filter(Boolean).map((f) => Field2.fromJSON(f, dictionaries)); +} +function fieldChildrenFromJSON(_field, dictionaries) { + return (_field["children"] || []).filter(Boolean).map((f) => Field2.fromJSON(f, dictionaries)); +} +function fieldNodesFromJSON(xs) { + return (xs || []).reduce((fieldNodes, column) => [ + ...fieldNodes, + new FieldNode2(column["count"], nullCountFromJSON(column["VALIDITY"])), + ...fieldNodesFromJSON(column["children"]) + ], []); +} +function buffersFromJSON(xs, buffers = []) { + for (let i = -1, n = (xs || []).length; ++i < n; ) { + const column = xs[i]; + column["VALIDITY"] && buffers.push(new BufferRegion(buffers.length, column["VALIDITY"].length)); + column["TYPE_ID"] && buffers.push(new BufferRegion(buffers.length, column["TYPE_ID"].length)); + column["OFFSET"] && buffers.push(new BufferRegion(buffers.length, column["OFFSET"].length)); + column["DATA"] && buffers.push(new BufferRegion(buffers.length, column["DATA"].length)); + column["VIEWS"] && buffers.push(new BufferRegion(buffers.length, column["VIEWS"].length)); + if (column["VARIADIC_DATA_BUFFERS"]) { + for (const buf of column["VARIADIC_DATA_BUFFERS"]) { + buffers.push(new BufferRegion(buffers.length, buf.length)); + } + } + buffers = buffersFromJSON(column["children"], buffers); + } + return buffers; +} +function nullCountFromJSON(validity) { + return (validity || []).reduce((sum, val) => sum + +(val === 0), 0); +} +function variadicBufferCountsFromJSON(xs) { + return (xs || []).reduce((counts, column) => [ + ...counts, + ...column["VARIADIC_DATA_BUFFERS"] ? [column["VARIADIC_DATA_BUFFERS"].length] : [], + ...variadicBufferCountsFromJSON(column["children"]) + ], []); +} +function fieldFromJSON(_field, dictionaries) { + let id; + let keys; + let field; + let dictMeta; + let type; + let dictType; + if (!dictionaries || !(dictMeta = _field["dictionary"])) { + type = typeFromJSON(_field, fieldChildrenFromJSON(_field, dictionaries)); + field = new Field2(_field["name"], type, _field["nullable"], customMetadataFromJSON(_field["metadata"])); + } else if (!dictionaries.has(id = dictMeta["id"])) { + keys = (keys = dictMeta["indexType"]) ? indexTypeFromJSON(keys) : new Int32(); + dictionaries.set(id, type = typeFromJSON(_field, fieldChildrenFromJSON(_field, dictionaries))); + dictType = new Dictionary(type, keys, id, dictMeta["isOrdered"]); + field = new Field2(_field["name"], dictType, _field["nullable"], customMetadataFromJSON(_field["metadata"])); + } else { + keys = (keys = dictMeta["indexType"]) ? indexTypeFromJSON(keys) : new Int32(); + dictType = new Dictionary(dictionaries.get(id), keys, id, dictMeta["isOrdered"]); + field = new Field2(_field["name"], dictType, _field["nullable"], customMetadataFromJSON(_field["metadata"])); + } + return field || null; +} +function customMetadataFromJSON(metadata = []) { + return new Map(metadata.map(({ key, value }) => [key, value])); +} +function indexTypeFromJSON(_type) { + return new Int_(_type["isSigned"], _type["bitWidth"]); +} +function typeFromJSON(f, children) { + const typeId = f["type"]["name"]; + switch (typeId) { + case "NONE": + return new Null2(); + case "null": + return new Null2(); + case "binary": + return new Binary2(); + case "largebinary": + return new LargeBinary2(); + case "binaryview": + return new BinaryView2(); + case "utf8": + return new Utf82(); + case "largeutf8": + return new LargeUtf82(); + case "utf8view": + return new Utf8View2(); + case "bool": + return new Bool2(); + case "list": + return new List2((children || [])[0]); + case "largelist": + return new LargeList2((children || [])[0]); + case "struct": + return new Struct(children || []); + case "struct_": + return new Struct(children || []); + } + switch (typeId) { + case "int": { + const t = f["type"]; + return new Int_(t["isSigned"], t["bitWidth"]); + } + case "floatingpoint": { + const t = f["type"]; + return new Float(Precision[t["precision"]]); + } + case "decimal": { + const t = f["type"]; + return new Decimal2(t["scale"], t["precision"], t["bitWidth"]); + } + case "date": { + const t = f["type"]; + return new Date_(DateUnit[t["unit"]]); + } + case "time": { + const t = f["type"]; + return new Time_(TimeUnit[t["unit"]], t["bitWidth"]); + } + case "timestamp": { + const t = f["type"]; + return new Timestamp_(TimeUnit[t["unit"]], t["timezone"]); + } + case "interval": { + const t = f["type"]; + return new Interval_(IntervalUnit[t["unit"]]); + } + case "duration": { + const t = f["type"]; + return new Duration2(TimeUnit[t["unit"]]); + } + case "union": { + const t = f["type"]; + const [m, ...ms] = (t["mode"] + "").toLowerCase(); + const mode = m.toUpperCase() + ms.join(""); + return new Union_(UnionMode[mode], t["typeIds"] || [], children || []); + } + case "fixedsizebinary": { + const t = f["type"]; + return new FixedSizeBinary2(t["byteWidth"]); + } + case "fixedsizelist": { + const t = f["type"]; + return new FixedSizeList2(t["listSize"], (children || [])[0]); + } + case "map": { + const t = f["type"]; + return new Map_((children || [])[0], t["keysSorted"]); + } + } + throw new Error(`Unrecognized type: "${typeId}"`); +} +var init_json = __esm({ + "node_modules/apache-arrow/ipc/metadata/json.mjs"() { + init_schema2(); + init_type2(); + init_message2(); + init_enum(); + } +}); + +// node_modules/apache-arrow/ipc/metadata/message.mjs +function messageHeaderFromJSON(message, type) { + return (() => { + switch (type) { + case MessageHeader.Schema: + return Schema4.fromJSON(message); + case MessageHeader.RecordBatch: + return RecordBatch2.fromJSON(message); + case MessageHeader.DictionaryBatch: + return DictionaryBatch2.fromJSON(message); + } + throw new Error(`Unrecognized Message type: { name: ${MessageHeader[type]}, type: ${type} }`); + }); +} +function decodeMessageHeader(message, type) { + return (() => { + switch (type) { + case MessageHeader.Schema: + return Schema4.decode(message.header(new Schema3()), /* @__PURE__ */ new Map(), message.version()); + case MessageHeader.RecordBatch: + return RecordBatch2.decode(message.header(new RecordBatch()), message.version()); + case MessageHeader.DictionaryBatch: + return DictionaryBatch2.decode(message.header(new DictionaryBatch()), message.version()); + } + throw new Error(`Unrecognized Message type: { name: ${MessageHeader[type]}, type: ${type} }`); + }); +} +function decodeSchema(_schema, dictionaries = /* @__PURE__ */ new Map(), version = MetadataVersion.V5) { + const fields = decodeSchemaFields(_schema, dictionaries); + return new Schema4(fields, decodeCustomMetadata(_schema), dictionaries, version); +} +function decodeRecordBatch(batch, version = MetadataVersion.V5) { + const recordBatch = new RecordBatch2(batch.length(), decodeFieldNodes(batch), decodeBuffers(batch, version), decodeBodyCompression(batch.compression()), decodeVariadicBufferCounts(batch)); + return recordBatch; +} +function decodeDictionaryBatch(batch, version = MetadataVersion.V5) { + return new DictionaryBatch2(RecordBatch2.decode(batch.data(), version), batch.id(), batch.isDelta()); +} +function decodeBufferRegion(b) { + return new BufferRegion(b.offset(), b.length()); +} +function decodeFieldNode(f) { + return new FieldNode2(f.length(), f.nullCount()); +} +function decodeFieldNodes(batch) { + const nodes = []; + for (let f, i = -1, j = -1, n = batch.nodesLength(); ++i < n; ) { + if (f = batch.nodes(i)) { + nodes[++j] = FieldNode2.decode(f); + } + } + return nodes; +} +function decodeBuffers(batch, version) { + const bufferRegions = []; + for (let b, i = -1, j = -1, n = batch.buffersLength(); ++i < n; ) { + if (b = batch.buffers(i)) { + if (version < MetadataVersion.V4) { + b.bb_pos += 8 * (i + 1); + } + bufferRegions[++j] = BufferRegion.decode(b); + } + } + return bufferRegions; +} +function decodeVariadicBufferCounts(batch) { + const counts = []; + const length = Math.trunc(batch.variadicBufferCountsLength()); + for (let i = 0; i < length; ++i) { + counts.push(bigIntToNumber(batch.variadicBufferCounts(i))); + } + return counts; +} +function decodeSchemaFields(schema, dictionaries) { + const fields = []; + for (let f, i = -1, j = -1, n = schema.fieldsLength(); ++i < n; ) { + if (f = schema.fields(i)) { + fields[++j] = Field2.decode(f, dictionaries); + } + } + return fields; +} +function decodeFieldChildren(field, dictionaries) { + const children = []; + for (let f, i = -1, j = -1, n = field.childrenLength(); ++i < n; ) { + if (f = field.children(i)) { + children[++j] = Field2.decode(f, dictionaries); + } + } + return children; +} +function decodeField(f, dictionaries) { + let id; + let field; + let type; + let keys; + let dictType; + let dictMeta; + if (!dictionaries || !(dictMeta = f.dictionary())) { + type = decodeFieldType(f, decodeFieldChildren(f, dictionaries)); + field = new Field2(f.name(), type, f.nullable(), decodeCustomMetadata(f)); + } else if (!dictionaries.has(id = bigIntToNumber(dictMeta.id()))) { + keys = (keys = dictMeta.indexType()) ? decodeIndexType(keys) : new Int32(); + dictionaries.set(id, type = decodeFieldType(f, decodeFieldChildren(f, dictionaries))); + dictType = new Dictionary(type, keys, id, dictMeta.isOrdered()); + field = new Field2(f.name(), dictType, f.nullable(), decodeCustomMetadata(f)); + } else { + keys = (keys = dictMeta.indexType()) ? decodeIndexType(keys) : new Int32(); + dictType = new Dictionary(dictionaries.get(id), keys, id, dictMeta.isOrdered()); + field = new Field2(f.name(), dictType, f.nullable(), decodeCustomMetadata(f)); + } + return field || null; +} +function decodeCustomMetadata(parent) { + const data = /* @__PURE__ */ new Map(); + if (parent) { + for (let entry, key, i = -1, n = Math.trunc(parent.customMetadataLength()); ++i < n; ) { + if ((entry = parent.customMetadata(i)) && (key = entry.key()) != null) { + data.set(key, entry.value()); + } + } + } + return data; +} +function decodeMessageCustomMetadata(message) { + const data = /* @__PURE__ */ new Map(); + for (let entry, key, i = -1, n = Math.trunc(message.customMetadataLength()); ++i < n; ) { + if ((entry = message.customMetadata(i)) && (key = entry.key()) != null) { + data.set(key, entry.value()); + } + } + return data; +} +function decodeIndexType(_type) { + return new Int_(_type.isSigned(), _type.bitWidth()); +} +function decodeFieldType(f, children) { + const typeId = f.typeType(); + switch (typeId) { + case Type["NONE"]: + return new Null2(); + case Type["Null"]: + return new Null2(); + case Type["Binary"]: + return new Binary2(); + case Type["LargeBinary"]: + return new LargeBinary2(); + case Type["BinaryView"]: + return new BinaryView2(); + case Type["Utf8"]: + return new Utf82(); + case Type["LargeUtf8"]: + return new LargeUtf82(); + case Type["Utf8View"]: + return new Utf8View2(); + case Type["Bool"]: + return new Bool2(); + case Type["List"]: + return new List2((children || [])[0]); + case Type["LargeList"]: + return new LargeList2((children || [])[0]); + case Type["Struct_"]: + return new Struct(children || []); + } + switch (typeId) { + case Type["Int"]: { + const t = f.type(new Int()); + return new Int_(t.isSigned(), t.bitWidth()); + } + case Type["FloatingPoint"]: { + const t = f.type(new FloatingPoint()); + return new Float(t.precision()); + } + case Type["Decimal"]: { + const t = f.type(new Decimal()); + return new Decimal2(t.scale(), t.precision(), t.bitWidth()); + } + case Type["Date"]: { + const t = f.type(new Date2()); + return new Date_(t.unit()); + } + case Type["Time"]: { + const t = f.type(new Time()); + return new Time_(t.unit(), t.bitWidth()); + } + case Type["Timestamp"]: { + const t = f.type(new Timestamp()); + return new Timestamp_(t.unit(), t.timezone()); + } + case Type["Interval"]: { + const t = f.type(new Interval()); + return new Interval_(t.unit()); + } + case Type["Duration"]: { + const t = f.type(new Duration()); + return new Duration2(t.unit()); + } + case Type["Union"]: { + const t = f.type(new Union()); + return new Union_(t.mode(), t.typeIdsArray() || [], children || []); + } + case Type["FixedSizeBinary"]: { + const t = f.type(new FixedSizeBinary()); + return new FixedSizeBinary2(t.byteWidth()); + } + case Type["FixedSizeList"]: { + const t = f.type(new FixedSizeList()); + return new FixedSizeList2(t.listSize(), (children || [])[0]); + } + case Type["Map"]: { + const t = f.type(new Map2()); + return new Map_((children || [])[0], t.keysSorted()); + } + } + throw new Error(`Unrecognized type: "${Type[typeId]}" (${typeId})`); +} +function decodeBodyCompression(b) { + return b ? new BodyCompression2(b.codec(), b.method()) : null; +} +function encodeSchema(b, schema) { + const fieldOffsets = schema.fields.map((f) => Field2.encode(b, f)); + Schema3.startFieldsVector(b, fieldOffsets.length); + const fieldsVectorOffset = Schema3.createFieldsVector(b, fieldOffsets); + const metadataOffset = !(schema.metadata && schema.metadata.size > 0) ? -1 : Schema3.createCustomMetadataVector(b, [...schema.metadata].map(([k, v]) => { + const key = b.createString(`${k}`); + const val = b.createString(`${v}`); + KeyValue.startKeyValue(b); + KeyValue.addKey(b, key); + KeyValue.addValue(b, val); + return KeyValue.endKeyValue(b); + })); + Schema3.startSchema(b); + Schema3.addFields(b, fieldsVectorOffset); + Schema3.addEndianness(b, platformIsLittleEndian ? Endianness.Little : Endianness.Big); + if (metadataOffset !== -1) { + Schema3.addCustomMetadata(b, metadataOffset); + } + return Schema3.endSchema(b); +} +function encodeField(b, field) { + let nameOffset = -1; + let typeOffset = -1; + let dictionaryOffset = -1; + const type = field.type; + let typeId = field.typeId; + if (!DataType.isDictionary(type)) { + typeOffset = instance5.visit(type, b); + } else { + typeId = type.dictionary.typeId; + dictionaryOffset = instance5.visit(type, b); + typeOffset = instance5.visit(type.dictionary, b); + } + const childOffsets = (type.children || []).map((f) => Field2.encode(b, f)); + const childrenVectorOffset = Field.createChildrenVector(b, childOffsets); + const metadataOffset = !(field.metadata && field.metadata.size > 0) ? -1 : Field.createCustomMetadataVector(b, [...field.metadata].map(([k, v]) => { + const key = b.createString(`${k}`); + const val = b.createString(`${v}`); + KeyValue.startKeyValue(b); + KeyValue.addKey(b, key); + KeyValue.addValue(b, val); + return KeyValue.endKeyValue(b); + })); + if (field.name) { + nameOffset = b.createString(field.name); + } + Field.startField(b); + Field.addType(b, typeOffset); + Field.addTypeType(b, typeId); + Field.addChildren(b, childrenVectorOffset); + Field.addNullable(b, !!field.nullable); + if (nameOffset !== -1) { + Field.addName(b, nameOffset); + } + if (dictionaryOffset !== -1) { + Field.addDictionary(b, dictionaryOffset); + } + if (metadataOffset !== -1) { + Field.addCustomMetadata(b, metadataOffset); + } + return Field.endField(b); +} +function encodeRecordBatch(b, recordBatch) { + const nodes = recordBatch.nodes || []; + const buffers = recordBatch.buffers || []; + const variadicBufferCounts = recordBatch.variadicBufferCounts || []; + RecordBatch.startNodesVector(b, nodes.length); + for (const n of nodes.slice().reverse()) + FieldNode2.encode(b, n); + const nodesVectorOffset = b.endVector(); + RecordBatch.startBuffersVector(b, buffers.length); + for (const b_ of buffers.slice().reverse()) + BufferRegion.encode(b, b_); + const buffersVectorOffset = b.endVector(); + let bodyCompressionOffset = null; + if (recordBatch.compression !== null) { + bodyCompressionOffset = encodeBodyCompression(b, recordBatch.compression); + } + let variadicBufferCountsOffset = -1; + if (variadicBufferCounts.length > 0) { + variadicBufferCountsOffset = RecordBatch.createVariadicBufferCountsVector(b, variadicBufferCounts.map(BigInt)); + } + RecordBatch.startRecordBatch(b); + RecordBatch.addLength(b, BigInt(recordBatch.length)); + RecordBatch.addNodes(b, nodesVectorOffset); + RecordBatch.addBuffers(b, buffersVectorOffset); + if (recordBatch.compression !== null && bodyCompressionOffset) { + RecordBatch.addCompression(b, bodyCompressionOffset); + } + if (variadicBufferCountsOffset !== -1) { + RecordBatch.addVariadicBufferCounts(b, variadicBufferCountsOffset); + } + return RecordBatch.endRecordBatch(b); +} +function encodeBodyCompression(b, node) { + BodyCompression.startBodyCompression(b); + BodyCompression.addCodec(b, node.type); + BodyCompression.addMethod(b, node.method); + return BodyCompression.endBodyCompression(b); +} +function encodeDictionaryBatch(b, dictionaryBatch) { + const dataOffset = RecordBatch2.encode(b, dictionaryBatch.data); + DictionaryBatch.startDictionaryBatch(b); + DictionaryBatch.addId(b, BigInt(dictionaryBatch.id)); + DictionaryBatch.addIsDelta(b, dictionaryBatch.isDelta); + DictionaryBatch.addData(b, dataOffset); + return DictionaryBatch.endDictionaryBatch(b); +} +function encodeFieldNode(b, node) { + return FieldNode.createFieldNode(b, BigInt(node.length), BigInt(node.nullCount)); +} +function encodeBufferRegion(b, node) { + return Buffer2.createBuffer(b, BigInt(node.offset), BigInt(node.length)); +} +var flatbuffers34, Builder5, ByteBuffer4, Message2, RecordBatch2, DictionaryBatch2, BufferRegion, FieldNode2, BodyCompression2, platformIsLittleEndian; +var init_message2 = __esm({ + "node_modules/apache-arrow/ipc/metadata/message.mjs"() { + flatbuffers34 = __toESM(require_flatbuffers(), 1); + init_schema(); + init_int(); + init_record_batch(); + init_dictionary_batch(); + init_buffer2(); + init_field(); + init_field_node(); + init_type(); + init_key_value(); + init_endianness(); + init_floating_point(); + init_decimal(); + init_date(); + init_time(); + init_timestamp(); + init_interval(); + init_duration(); + init_union(); + init_fixed_size_binary(); + init_fixed_size_list(); + init_map(); + init_message(); + init_body_compression(); + init_body_compression_method(); + init_schema2(); + init_buffer(); + init_bigint(); + init_enum(); + init_typeassembler(); + init_json(); + init_type2(); + Builder5 = flatbuffers34.Builder; + ByteBuffer4 = flatbuffers34.ByteBuffer; + Message2 = class _Message { + /** @nocollapse */ + static fromJSON(msg, headerType) { + const message = new _Message(0, MetadataVersion.V5, headerType); + message._createHeader = messageHeaderFromJSON(msg, headerType); + return message; + } + /** @nocollapse */ + static decode(buf) { + buf = new ByteBuffer4(toUint8Array(buf)); + const _message = Message.getRootAsMessage(buf); + const bodyLength = _message.bodyLength(); + const version = _message.version(); + const headerType = _message.headerType(); + const metadata = decodeMessageCustomMetadata(_message); + const message = new _Message(bodyLength, version, headerType, void 0, metadata); + message._createHeader = decodeMessageHeader(_message, headerType); + return message; + } + /** @nocollapse */ + static encode(message) { + const b = new Builder5(); + let headerOffset = -1; + if (message.isSchema()) { + headerOffset = Schema4.encode(b, message.header()); + } else if (message.isRecordBatch()) { + headerOffset = RecordBatch2.encode(b, message.header()); + } else if (message.isDictionaryBatch()) { + headerOffset = DictionaryBatch2.encode(b, message.header()); + } + const customMetadataOffset = !(message.metadata && message.metadata.size > 0) ? -1 : Message.createCustomMetadataVector(b, [...message.metadata].map(([k, v]) => { + const key = b.createString(`${k}`); + const val = b.createString(`${v}`); + KeyValue.startKeyValue(b); + KeyValue.addKey(b, key); + KeyValue.addValue(b, val); + return KeyValue.endKeyValue(b); + })); + Message.startMessage(b); + Message.addVersion(b, MetadataVersion.V5); + Message.addHeader(b, headerOffset); + Message.addHeaderType(b, message.headerType); + Message.addBodyLength(b, BigInt(message.bodyLength)); + if (customMetadataOffset !== -1) { + Message.addCustomMetadata(b, customMetadataOffset); } + Message.finishMessageBuffer(b, Message.endMessage(b)); + return b.asUint8Array(); } - }; - exports2.comp19 = { - parameterPath: "comp", - mapper: { - defaultValue: "page", - isConstant: true, - serializedName: "comp", - type: { - name: "String" + /** @nocollapse */ + static from(header, bodyLength = 0) { + if (header instanceof Schema4) { + return new _Message(0, MetadataVersion.V5, MessageHeader.Schema, header); + } + if (header instanceof RecordBatch2) { + return new _Message(bodyLength, MetadataVersion.V5, MessageHeader.RecordBatch, header, header.metadata); } + if (header instanceof DictionaryBatch2) { + return new _Message(bodyLength, MetadataVersion.V5, MessageHeader.DictionaryBatch, header); + } + throw new Error(`Unrecognized Message header: ${header}`); + } + get type() { + return this.headerType; + } + get version() { + return this._version; + } + get headerType() { + return this._headerType; + } + get compression() { + return this._compression; + } + get bodyLength() { + return this._bodyLength; + } + get metadata() { + return this._metadata; + } + header() { + return this._createHeader(); + } + isSchema() { + return this.headerType === MessageHeader.Schema; + } + isRecordBatch() { + return this.headerType === MessageHeader.RecordBatch; + } + isDictionaryBatch() { + return this.headerType === MessageHeader.DictionaryBatch; + } + constructor(bodyLength, version, headerType, header, metadata) { + this._version = version; + this._headerType = headerType; + this.body = new Uint8Array(0); + this._compression = header === null || header === void 0 ? void 0 : header.compression; + header && (this._createHeader = () => header); + this._bodyLength = bigIntToNumber(bodyLength); + this._metadata = metadata || /* @__PURE__ */ new Map(); } }; - exports2.pageWrite = { - parameterPath: "pageWrite", - mapper: { - defaultValue: "update", - isConstant: true, - serializedName: "x-ms-page-write", - type: { - name: "String" - } + RecordBatch2 = class { + get nodes() { + return this._nodes; + } + get length() { + return this._length; + } + get buffers() { + return this._buffers; + } + get compression() { + return this._compression; + } + get variadicBufferCounts() { + return this._variadicBufferCounts; + } + get metadata() { + return this._metadata; + } + constructor(length, nodes, buffers, compression, variadicBufferCounts = [], metadata) { + this._nodes = nodes; + this._buffers = buffers; + this._length = bigIntToNumber(length); + this._compression = compression; + this._variadicBufferCounts = variadicBufferCounts; + this._metadata = metadata || /* @__PURE__ */ new Map(); } }; - exports2.ifSequenceNumberLessThanOrEqualTo = { - parameterPath: [ - "options", - "sequenceNumberAccessConditions", - "ifSequenceNumberLessThanOrEqualTo" - ], - mapper: { - serializedName: "x-ms-if-sequence-number-le", - xmlName: "x-ms-if-sequence-number-le", - type: { - name: "Number" - } + DictionaryBatch2 = class { + get id() { + return this._id; + } + get data() { + return this._data; + } + get isDelta() { + return this._isDelta; + } + get length() { + return this.data.length; + } + get nodes() { + return this.data.nodes; + } + get buffers() { + return this.data.buffers; + } + constructor(data, id, isDelta = false) { + this._data = data; + this._isDelta = isDelta; + this._id = bigIntToNumber(id); } }; - exports2.ifSequenceNumberLessThan = { - parameterPath: [ - "options", - "sequenceNumberAccessConditions", - "ifSequenceNumberLessThan" - ], - mapper: { - serializedName: "x-ms-if-sequence-number-lt", - xmlName: "x-ms-if-sequence-number-lt", - type: { - name: "Number" - } + BufferRegion = class { + constructor(offset, length) { + this.offset = bigIntToNumber(offset); + this.length = bigIntToNumber(length); } }; - exports2.ifSequenceNumberEqualTo = { - parameterPath: [ - "options", - "sequenceNumberAccessConditions", - "ifSequenceNumberEqualTo" - ], - mapper: { - serializedName: "x-ms-if-sequence-number-eq", - xmlName: "x-ms-if-sequence-number-eq", - type: { - name: "Number" - } + FieldNode2 = class { + constructor(length, nullCount) { + this.length = bigIntToNumber(length); + this.nullCount = bigIntToNumber(nullCount); } }; - exports2.pageWrite1 = { - parameterPath: "pageWrite", - mapper: { - defaultValue: "clear", - isConstant: true, - serializedName: "x-ms-page-write", - type: { - name: "String" - } + BodyCompression2 = class { + constructor(type, method = BodyCompressionMethod.BUFFER) { + this.type = type; + this.method = method; } }; - exports2.sourceUrl = { - parameterPath: "sourceUrl", - mapper: { - serializedName: "x-ms-copy-source", - required: true, - xmlName: "x-ms-copy-source", - type: { - name: "String" - } + Field2["encode"] = encodeField; + Field2["decode"] = decodeField; + Field2["fromJSON"] = fieldFromJSON; + Schema4["encode"] = encodeSchema; + Schema4["decode"] = decodeSchema; + Schema4["fromJSON"] = schemaFromJSON; + RecordBatch2["encode"] = encodeRecordBatch; + RecordBatch2["decode"] = decodeRecordBatch; + RecordBatch2["fromJSON"] = recordBatchFromJSON; + DictionaryBatch2["encode"] = encodeDictionaryBatch; + DictionaryBatch2["decode"] = decodeDictionaryBatch; + DictionaryBatch2["fromJSON"] = dictionaryBatchFromJSON; + FieldNode2["encode"] = encodeFieldNode; + FieldNode2["decode"] = decodeFieldNode; + BufferRegion["encode"] = encodeBufferRegion; + BufferRegion["decode"] = decodeBufferRegion; + BodyCompression2["encode"] = encodeBodyCompression; + BodyCompression2["decode"] = decodeBodyCompression; + platformIsLittleEndian = (() => { + const buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16( + 0, + 256, + true + /* littleEndian */ + ); + return new Int16Array(buffer)[0] === 256; + })(); + } +}); + +// node_modules/apache-arrow/io/interfaces.mjs +var ITERATOR_DONE, ArrowJSON, ReadableInterop, AsyncQueue; +var init_interfaces = __esm({ + "node_modules/apache-arrow/io/interfaces.mjs"() { + init_tslib_es6(); + init_adapters(); + ITERATOR_DONE = Object.freeze({ done: true, value: void 0 }); + ArrowJSON = class { + constructor(_json) { + this._json = _json; + } + get schema() { + return this._json["schema"]; + } + get batches() { + return this._json["batches"] || []; + } + get dictionaries() { + return this._json["dictionaries"] || []; } }; - exports2.sourceRange = { - parameterPath: "sourceRange", - mapper: { - serializedName: "x-ms-source-range", - required: true, - xmlName: "x-ms-source-range", - type: { - name: "String" - } + ReadableInterop = class { + tee() { + return this._getDOMStream().tee(); + } + pipe(writable, options) { + return this._getNodeStream().pipe(writable, options); + } + pipeTo(writable, options) { + return this._getDOMStream().pipeTo(writable, options); + } + pipeThrough(duplex, options) { + return this._getDOMStream().pipeThrough(duplex, options); + } + _getDOMStream() { + return this._DOMStream || (this._DOMStream = this.toDOMStream()); + } + _getNodeStream() { + return this._nodeStream || (this._nodeStream = this.toNodeStream()); } }; - exports2.sourceContentCrc64 = { - parameterPath: ["options", "sourceContentCrc64"], - mapper: { - serializedName: "x-ms-source-content-crc64", - xmlName: "x-ms-source-content-crc64", - type: { - name: "ByteArray" + AsyncQueue = class extends ReadableInterop { + constructor() { + super(); + this._values = []; + this.resolvers = []; + this._closedPromise = new Promise((r) => this._closedPromiseResolve = r); + } + get closed() { + return this._closedPromise; + } + cancel(reason) { + return __awaiter(this, void 0, void 0, function* () { + yield this.return(reason); + }); + } + write(value) { + if (this._ensureOpen()) { + this.resolvers.length <= 0 ? this._values.push(value) : this.resolvers.shift().resolve({ done: false, value }); } } - }; - exports2.range1 = { - parameterPath: "range", - mapper: { - serializedName: "x-ms-range", - required: true, - xmlName: "x-ms-range", - type: { - name: "String" + abort(value) { + if (this._closedPromiseResolve) { + this.resolvers.length <= 0 ? this._error = { error: value } : this.resolvers.shift().reject({ done: true, value }); } } - }; - exports2.comp20 = { - parameterPath: "comp", - mapper: { - defaultValue: "pagelist", - isConstant: true, - serializedName: "comp", - type: { - name: "String" + close() { + if (this._closedPromiseResolve) { + const { resolvers } = this; + while (resolvers.length > 0) { + resolvers.shift().resolve(ITERATOR_DONE); + } + this._closedPromiseResolve(); + this._closedPromiseResolve = void 0; } } - }; - exports2.prevsnapshot = { - parameterPath: ["options", "prevsnapshot"], - mapper: { - serializedName: "prevsnapshot", - xmlName: "prevsnapshot", - type: { - name: "String" + [Symbol.asyncIterator]() { + return this; + } + toDOMStream(options) { + return adapters_default.toDOMStream(this._closedPromiseResolve || this._error ? this : this._values, options); + } + toNodeStream(options) { + return adapters_default.toNodeStream(this._closedPromiseResolve || this._error ? this : this._values, options); + } + throw(_2) { + return __awaiter(this, void 0, void 0, function* () { + yield this.abort(_2); + return ITERATOR_DONE; + }); + } + return(_2) { + return __awaiter(this, void 0, void 0, function* () { + yield this.close(); + return ITERATOR_DONE; + }); + } + read(size) { + return __awaiter(this, void 0, void 0, function* () { + return (yield this.next(size, "read")).value; + }); + } + peek(size) { + return __awaiter(this, void 0, void 0, function* () { + return (yield this.next(size, "peek")).value; + }); + } + next(..._args) { + if (this._values.length > 0) { + return Promise.resolve({ done: false, value: this._values.shift() }); + } else if (this._error) { + return Promise.reject({ done: true, value: this._error.error }); + } else if (!this._closedPromiseResolve) { + return Promise.resolve(ITERATOR_DONE); + } else { + return new Promise((resolve15, reject) => { + this.resolvers.push({ resolve: resolve15, reject }); + }); } } - }; - exports2.prevSnapshotUrl = { - parameterPath: ["options", "prevSnapshotUrl"], - mapper: { - serializedName: "x-ms-previous-snapshot-url", - xmlName: "x-ms-previous-snapshot-url", - type: { - name: "String" + _ensureOpen() { + if (this._closedPromiseResolve) { + return true; } + throw new Error(`AsyncQueue is closed`); } }; - exports2.sequenceNumberAction = { - parameterPath: "sequenceNumberAction", - mapper: { - serializedName: "x-ms-sequence-number-action", - required: true, - xmlName: "x-ms-sequence-number-action", - type: { - name: "Enum", - allowedValues: ["max", "update", "increment"] + } +}); + +// node_modules/apache-arrow/io/stream.mjs +var AsyncByteQueue, ByteStream, AsyncByteStream, ByteStreamSource, AsyncByteStreamSource; +var init_stream = __esm({ + "node_modules/apache-arrow/io/stream.mjs"() { + init_tslib_es6(); + init_adapters(); + init_utf8(); + init_interfaces(); + init_buffer(); + init_compat(); + AsyncByteQueue = class extends AsyncQueue { + write(value) { + if ((value = toUint8Array(value)).byteLength > 0) { + return super.write(value); } } + toString(sync = false) { + return sync ? decodeUtf8(this.toUint8Array(true)) : this.toUint8Array(false).then(decodeUtf8); + } + toUint8Array(sync = false) { + return sync ? joinUint8Arrays(this._values)[0] : (() => __awaiter(this, void 0, void 0, function* () { + var _a6, e_1, _b2, _c2; + const buffers = []; + let byteLength = 0; + try { + for (var _d2 = true, _e2 = __asyncValues(this), _f2; _f2 = yield _e2.next(), _a6 = _f2.done, !_a6; _d2 = true) { + _c2 = _f2.value; + _d2 = false; + const chunk = _c2; + buffers.push(chunk); + byteLength += chunk.byteLength; + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d2 && !_a6 && (_b2 = _e2.return)) yield _b2.call(_e2); + } finally { + if (e_1) throw e_1.error; + } + } + return joinUint8Arrays(buffers, byteLength)[0]; + }))(); + } }; - exports2.comp21 = { - parameterPath: "comp", - mapper: { - defaultValue: "incrementalcopy", - isConstant: true, - serializedName: "comp", - type: { - name: "String" + ByteStream = class { + constructor(source) { + if (source) { + this.source = new ByteStreamSource(adapters_default.fromIterable(source)); } } + [Symbol.iterator]() { + return this; + } + next(value) { + return this.source.next(value); + } + throw(value) { + return this.source.throw(value); + } + return(value) { + return this.source.return(value); + } + peek(size) { + return this.source.peek(size); + } + read(size) { + return this.source.read(size); + } }; - exports2.blobType1 = { - parameterPath: "blobType", - mapper: { - defaultValue: "AppendBlob", - isConstant: true, - serializedName: "x-ms-blob-type", - type: { - name: "String" + AsyncByteStream = class _AsyncByteStream { + constructor(source) { + if (source instanceof _AsyncByteStream) { + this.source = source.source; + } else if (source instanceof AsyncByteQueue) { + this.source = new AsyncByteStreamSource(adapters_default.fromAsyncIterable(source)); + } else if (isReadableNodeStream(source)) { + this.source = new AsyncByteStreamSource(adapters_default.fromNodeStream(source)); + } else if (isReadableDOMStream(source)) { + this.source = new AsyncByteStreamSource(adapters_default.fromDOMStream(source)); + } else if (isFetchResponse(source)) { + this.source = new AsyncByteStreamSource(adapters_default.fromDOMStream(source.body)); + } else if (isIterable(source)) { + this.source = new AsyncByteStreamSource(adapters_default.fromIterable(source)); + } else if (isPromise(source)) { + this.source = new AsyncByteStreamSource(adapters_default.fromAsyncIterable(source)); + } else if (isAsyncIterable(source)) { + this.source = new AsyncByteStreamSource(adapters_default.fromAsyncIterable(source)); } } + [Symbol.asyncIterator]() { + return this; + } + next(value) { + return this.source.next(value); + } + throw(value) { + return this.source.throw(value); + } + return(value) { + return this.source.return(value); + } + get closed() { + return this.source.closed; + } + cancel(reason) { + return this.source.cancel(reason); + } + peek(size) { + return this.source.peek(size); + } + read(size) { + return this.source.read(size); + } }; - exports2.comp22 = { - parameterPath: "comp", - mapper: { - defaultValue: "appendblock", - isConstant: true, - serializedName: "comp", - type: { - name: "String" - } + ByteStreamSource = class { + constructor(source) { + this.source = source; + } + cancel(reason) { + this.return(reason); + } + peek(size) { + return this.next(size, "peek").value; + } + read(size) { + return this.next(size, "read").value; + } + next(size, cmd = "read") { + return this.source.next({ cmd, size }); + } + throw(value) { + return Object.create(this.source.throw && this.source.throw(value) || ITERATOR_DONE); + } + return(value) { + return Object.create(this.source.return && this.source.return(value) || ITERATOR_DONE); } }; - exports2.maxSize = { - parameterPath: ["options", "appendPositionAccessConditions", "maxSize"], - mapper: { - serializedName: "x-ms-blob-condition-maxsize", - xmlName: "x-ms-blob-condition-maxsize", - type: { - name: "Number" - } + AsyncByteStreamSource = class { + constructor(source) { + this.source = source; + this._closedPromise = new Promise((r) => this._closedPromiseResolve = r); + } + cancel(reason) { + return __awaiter(this, void 0, void 0, function* () { + yield this.return(reason); + }); + } + get closed() { + return this._closedPromise; + } + read(size) { + return __awaiter(this, void 0, void 0, function* () { + return (yield this.next(size, "read")).value; + }); + } + peek(size) { + return __awaiter(this, void 0, void 0, function* () { + return (yield this.next(size, "peek")).value; + }); + } + next(size_1) { + return __awaiter(this, arguments, void 0, function* (size, cmd = "read") { + return yield this.source.next({ cmd, size }); + }); + } + throw(value) { + return __awaiter(this, void 0, void 0, function* () { + const result = this.source.throw && (yield this.source.throw(value)) || ITERATOR_DONE; + this._closedPromiseResolve && this._closedPromiseResolve(); + this._closedPromiseResolve = void 0; + return Object.create(result); + }); + } + return(value) { + return __awaiter(this, void 0, void 0, function* () { + const result = this.source.return && (yield this.source.return(value)) || ITERATOR_DONE; + this._closedPromiseResolve && this._closedPromiseResolve(); + this._closedPromiseResolve = void 0; + return Object.create(result); + }); } }; - exports2.appendPosition = { - parameterPath: [ - "options", - "appendPositionAccessConditions", - "appendPosition" - ], - mapper: { - serializedName: "x-ms-blob-condition-appendpos", - xmlName: "x-ms-blob-condition-appendpos", - type: { - name: "Number" + } +}); + +// node_modules/apache-arrow/io/file.mjs +var RandomAccessFile, AsyncRandomAccessFile; +var init_file2 = __esm({ + "node_modules/apache-arrow/io/file.mjs"() { + init_tslib_es6(); + init_stream(); + init_buffer(); + RandomAccessFile = class extends ByteStream { + constructor(buffer, byteLength) { + super(); + this.position = 0; + this.buffer = toUint8Array(buffer); + this.size = byteLength === void 0 ? this.buffer.byteLength : byteLength; + } + readInt32(position) { + const { buffer, byteOffset } = this.readAt(position, 4); + return new DataView(buffer, byteOffset).getInt32(0, true); + } + seek(position) { + this.position = Math.min(position, this.size); + return position < this.size; + } + read(nBytes) { + const { buffer, size, position } = this; + if (buffer && position < size) { + if (typeof nBytes !== "number") { + nBytes = Number.POSITIVE_INFINITY; + } + this.position = Math.min(size, position + Math.min(size - position, nBytes)); + return buffer.subarray(position, this.position); } + return null; + } + readAt(position, nBytes) { + const buf = this.buffer; + const end = Math.min(this.size, position + nBytes); + return buf ? buf.subarray(position, end) : new Uint8Array(nBytes); + } + close() { + this.buffer && (this.buffer = null); + } + throw(value) { + this.close(); + return { done: true, value }; + } + return(value) { + this.close(); + return { done: true, value }; } }; - exports2.sourceRange1 = { - parameterPath: ["options", "sourceRange"], - mapper: { - serializedName: "x-ms-source-range", - xmlName: "x-ms-source-range", - type: { - name: "String" + AsyncRandomAccessFile = class extends AsyncByteStream { + constructor(file, byteLength) { + super(); + this.position = 0; + this._handle = file; + if (typeof byteLength === "number") { + this.size = byteLength; + } else { + this._pending = (() => __awaiter(this, void 0, void 0, function* () { + this.size = (yield file.stat()).size; + delete this._pending; + }))(); } } + readInt32(position) { + return __awaiter(this, void 0, void 0, function* () { + const { buffer, byteOffset } = yield this.readAt(position, 4); + return new DataView(buffer, byteOffset).getInt32(0, true); + }); + } + seek(position) { + return __awaiter(this, void 0, void 0, function* () { + this._pending && (yield this._pending); + this.position = Math.min(position, this.size); + return position < this.size; + }); + } + read(nBytes) { + return __awaiter(this, void 0, void 0, function* () { + this._pending && (yield this._pending); + const { _handle: file, size, position } = this; + if (file && position < size) { + if (typeof nBytes !== "number") { + nBytes = Number.POSITIVE_INFINITY; + } + let pos = position, offset = 0, bytesRead = 0; + const end = Math.min(size, pos + Math.min(size - pos, nBytes)); + const buffer = new Uint8Array(Math.max(0, (this.position = end) - pos)); + while ((pos += bytesRead) < end && (offset += bytesRead) < buffer.byteLength) { + ({ bytesRead } = yield file.read(buffer, offset, buffer.byteLength - offset, pos)); + } + return buffer; + } + return null; + }); + } + readAt(position, nBytes) { + return __awaiter(this, void 0, void 0, function* () { + this._pending && (yield this._pending); + const { _handle: file, size } = this; + if (file && position + nBytes < size) { + const end = Math.min(size, position + nBytes); + const buffer = new Uint8Array(end - position); + return (yield file.read(buffer, 0, nBytes, position)).buffer; + } + return new Uint8Array(nBytes); + }); + } + close() { + return __awaiter(this, void 0, void 0, function* () { + const f = this._handle; + this._handle = null; + f && (yield f.close()); + }); + } + throw(value) { + return __awaiter(this, void 0, void 0, function* () { + yield this.close(); + return { done: true, value }; + }); + } + return(value) { + return __awaiter(this, void 0, void 0, function* () { + yield this.close(); + return { done: true, value }; + }); + } }; - exports2.comp23 = { - parameterPath: "comp", - mapper: { - defaultValue: "seal", - isConstant: true, - serializedName: "comp", - type: { - name: "String" + } +}); + +// node_modules/apache-arrow/util/int.mjs +var int_exports = {}; +__export(int_exports, { + BaseInt64: () => BaseInt64, + Int128: () => Int128, + Int64: () => Int642, + Uint64: () => Uint642 +}); +function intAsHex(value) { + if (value < 0) { + value = 4294967295 + value + 1; + } + return `0x${value.toString(16)}`; +} +var carryBit16, kInt32DecimalDigits, kPowersOfTen, BaseInt64, Uint642, Int642, Int128; +var init_int2 = __esm({ + "node_modules/apache-arrow/util/int.mjs"() { + carryBit16 = 1 << 16; + kInt32DecimalDigits = 8; + kPowersOfTen = [ + 1, + 10, + 100, + 1e3, + 1e4, + 1e5, + 1e6, + 1e7, + 1e8 + ]; + BaseInt64 = class { + constructor(buffer) { + this.buffer = buffer; + } + high() { + return this.buffer[1]; + } + low() { + return this.buffer[0]; + } + _times(other) { + const L = new Uint32Array([ + this.buffer[1] >>> 16, + this.buffer[1] & 65535, + this.buffer[0] >>> 16, + this.buffer[0] & 65535 + ]); + const R = new Uint32Array([ + other.buffer[1] >>> 16, + other.buffer[1] & 65535, + other.buffer[0] >>> 16, + other.buffer[0] & 65535 + ]); + let product = L[3] * R[3]; + this.buffer[0] = product & 65535; + let sum = product >>> 16; + product = L[2] * R[3]; + sum += product; + product = L[3] * R[2] >>> 0; + sum += product; + this.buffer[0] += sum << 16; + this.buffer[1] = sum >>> 0 < product ? carryBit16 : 0; + this.buffer[1] += sum >>> 16; + this.buffer[1] += L[1] * R[3] + L[2] * R[2] + L[3] * R[1]; + this.buffer[1] += L[0] * R[3] + L[1] * R[2] + L[2] * R[1] + L[3] * R[0] << 16; + return this; + } + _plus(other) { + const sum = this.buffer[0] + other.buffer[0] >>> 0; + this.buffer[1] += other.buffer[1]; + if (sum < this.buffer[0] >>> 0) { + ++this.buffer[1]; } + this.buffer[0] = sum; + } + lessThan(other) { + return this.buffer[1] < other.buffer[1] || this.buffer[1] === other.buffer[1] && this.buffer[0] < other.buffer[0]; + } + equals(other) { + return this.buffer[1] === other.buffer[1] && this.buffer[0] == other.buffer[0]; + } + greaterThan(other) { + return other.lessThan(this); + } + hex() { + return `${intAsHex(this.buffer[1])} ${intAsHex(this.buffer[0])}`; } }; - exports2.blobType2 = { - parameterPath: "blobType", - mapper: { - defaultValue: "BlockBlob", - isConstant: true, - serializedName: "x-ms-blob-type", - type: { - name: "String" + Uint642 = class _Uint64 extends BaseInt64 { + times(other) { + this._times(other); + return this; + } + plus(other) { + this._plus(other); + return this; + } + /** @nocollapse */ + static from(val, out_buffer = new Uint32Array(2)) { + return _Uint64.fromString(typeof val === "string" ? val : val.toString(), out_buffer); + } + /** @nocollapse */ + static fromNumber(num, out_buffer = new Uint32Array(2)) { + return _Uint64.fromString(num.toString(), out_buffer); + } + /** @nocollapse */ + static fromString(str, out_buffer = new Uint32Array(2)) { + const length = str.length; + const out = new _Uint64(out_buffer); + for (let posn = 0; posn < length; ) { + const group = kInt32DecimalDigits < length - posn ? kInt32DecimalDigits : length - posn; + const chunk = new _Uint64(new Uint32Array([Number.parseInt(str.slice(posn, posn + group), 10), 0])); + const multiple = new _Uint64(new Uint32Array([kPowersOfTen[group], 0])); + out.times(multiple); + out.plus(chunk); + posn += group; } + return out; } - }; - exports2.copySourceBlobProperties = { - parameterPath: ["options", "copySourceBlobProperties"], - mapper: { - serializedName: "x-ms-copy-source-blob-properties", - xmlName: "x-ms-copy-source-blob-properties", - type: { - name: "Boolean" + /** @nocollapse */ + static convertArray(values) { + const data = new Uint32Array(values.length * 2); + for (let i = -1, n = values.length; ++i < n; ) { + _Uint64.from(values[i], new Uint32Array(data.buffer, data.byteOffset + 2 * i * 4, 2)); } + return data; + } + /** @nocollapse */ + static multiply(left, right) { + const rtrn = new _Uint64(new Uint32Array(left.buffer)); + return rtrn.times(right); + } + /** @nocollapse */ + static add(left, right) { + const rtrn = new _Uint64(new Uint32Array(left.buffer)); + return rtrn.plus(right); } }; - exports2.comp24 = { - parameterPath: "comp", - mapper: { - defaultValue: "block", - isConstant: true, - serializedName: "comp", - type: { - name: "String" + Int642 = class _Int64 extends BaseInt64 { + negate() { + this.buffer[0] = ~this.buffer[0] + 1; + this.buffer[1] = ~this.buffer[1]; + if (this.buffer[0] == 0) { + ++this.buffer[1]; } + return this; } - }; - exports2.blockId = { - parameterPath: "blockId", - mapper: { - serializedName: "blockid", - required: true, - xmlName: "blockid", - type: { - name: "String" + times(other) { + this._times(other); + return this; + } + plus(other) { + this._plus(other); + return this; + } + lessThan(other) { + const this_high = this.buffer[1] << 0; + const other_high = other.buffer[1] << 0; + return this_high < other_high || this_high === other_high && this.buffer[0] < other.buffer[0]; + } + /** @nocollapse */ + static from(val, out_buffer = new Uint32Array(2)) { + return _Int64.fromString(typeof val === "string" ? val : val.toString(), out_buffer); + } + /** @nocollapse */ + static fromNumber(num, out_buffer = new Uint32Array(2)) { + return _Int64.fromString(num.toString(), out_buffer); + } + /** @nocollapse */ + static fromString(str, out_buffer = new Uint32Array(2)) { + const negate2 = str.startsWith("-"); + const length = str.length; + const out = new _Int64(out_buffer); + for (let posn = negate2 ? 1 : 0; posn < length; ) { + const group = kInt32DecimalDigits < length - posn ? kInt32DecimalDigits : length - posn; + const chunk = new _Int64(new Uint32Array([Number.parseInt(str.slice(posn, posn + group), 10), 0])); + const multiple = new _Int64(new Uint32Array([kPowersOfTen[group], 0])); + out.times(multiple); + out.plus(chunk); + posn += group; + } + return negate2 ? out.negate() : out; + } + /** @nocollapse */ + static convertArray(values) { + const data = new Uint32Array(values.length * 2); + for (let i = -1, n = values.length; ++i < n; ) { + _Int64.from(values[i], new Uint32Array(data.buffer, data.byteOffset + 2 * i * 4, 2)); } + return data; + } + /** @nocollapse */ + static multiply(left, right) { + const rtrn = new _Int64(new Uint32Array(left.buffer)); + return rtrn.times(right); + } + /** @nocollapse */ + static add(left, right) { + const rtrn = new _Int64(new Uint32Array(left.buffer)); + return rtrn.plus(right); } }; - exports2.blocks = { - parameterPath: "blocks", - mapper: mappers_js_1.BlockLookupList - }; - exports2.comp25 = { - parameterPath: "comp", - mapper: { - defaultValue: "blocklist", - isConstant: true, - serializedName: "comp", - type: { - name: "String" + Int128 = class _Int128 { + constructor(buffer) { + this.buffer = buffer; + } + high() { + return new Int642(new Uint32Array(this.buffer.buffer, this.buffer.byteOffset + 8, 2)); + } + low() { + return new Int642(new Uint32Array(this.buffer.buffer, this.buffer.byteOffset, 2)); + } + negate() { + this.buffer[0] = ~this.buffer[0] + 1; + this.buffer[1] = ~this.buffer[1]; + this.buffer[2] = ~this.buffer[2]; + this.buffer[3] = ~this.buffer[3]; + if (this.buffer[0] == 0) { + ++this.buffer[1]; + } + if (this.buffer[1] == 0) { + ++this.buffer[2]; } + if (this.buffer[2] == 0) { + ++this.buffer[3]; + } + return this; } - }; - exports2.listType = { - parameterPath: "listType", - mapper: { - defaultValue: "committed", - serializedName: "blocklisttype", - required: true, - xmlName: "blocklisttype", - type: { - name: "Enum", - allowedValues: ["committed", "uncommitted", "all"] + times(other) { + const L0 = new Uint642(new Uint32Array([this.buffer[3], 0])); + const L1 = new Uint642(new Uint32Array([this.buffer[2], 0])); + const L2 = new Uint642(new Uint32Array([this.buffer[1], 0])); + const L3 = new Uint642(new Uint32Array([this.buffer[0], 0])); + const R0 = new Uint642(new Uint32Array([other.buffer[3], 0])); + const R1 = new Uint642(new Uint32Array([other.buffer[2], 0])); + const R2 = new Uint642(new Uint32Array([other.buffer[1], 0])); + const R3 = new Uint642(new Uint32Array([other.buffer[0], 0])); + let product = Uint642.multiply(L3, R3); + this.buffer[0] = product.low(); + const sum = new Uint642(new Uint32Array([product.high(), 0])); + product = Uint642.multiply(L2, R3); + sum.plus(product); + product = Uint642.multiply(L3, R2); + sum.plus(product); + this.buffer[1] = sum.low(); + this.buffer[3] = sum.lessThan(product) ? 1 : 0; + this.buffer[2] = sum.high(); + const high = new Uint642(new Uint32Array(this.buffer.buffer, this.buffer.byteOffset + 8, 2)); + high.plus(Uint642.multiply(L1, R3)).plus(Uint642.multiply(L2, R2)).plus(Uint642.multiply(L3, R1)); + this.buffer[3] += Uint642.multiply(L0, R3).plus(Uint642.multiply(L1, R2)).plus(Uint642.multiply(L2, R1)).plus(Uint642.multiply(L3, R0)).low(); + return this; + } + plus(other) { + const sums = new Uint32Array(4); + sums[3] = this.buffer[3] + other.buffer[3] >>> 0; + sums[2] = this.buffer[2] + other.buffer[2] >>> 0; + sums[1] = this.buffer[1] + other.buffer[1] >>> 0; + sums[0] = this.buffer[0] + other.buffer[0] >>> 0; + if (sums[0] < this.buffer[0] >>> 0) { + ++sums[1]; + } + if (sums[1] < this.buffer[1] >>> 0) { + ++sums[2]; + } + if (sums[2] < this.buffer[2] >>> 0) { + ++sums[3]; + } + this.buffer[3] = sums[3]; + this.buffer[2] = sums[2]; + this.buffer[1] = sums[1]; + this.buffer[0] = sums[0]; + return this; + } + hex() { + return `${intAsHex(this.buffer[3])} ${intAsHex(this.buffer[2])} ${intAsHex(this.buffer[1])} ${intAsHex(this.buffer[0])}`; + } + /** @nocollapse */ + static multiply(left, right) { + const rtrn = new _Int128(new Uint32Array(left.buffer)); + return rtrn.times(right); + } + /** @nocollapse */ + static add(left, right) { + const rtrn = new _Int128(new Uint32Array(left.buffer)); + return rtrn.plus(right); + } + /** @nocollapse */ + static from(val, out_buffer = new Uint32Array(4)) { + return _Int128.fromString(typeof val === "string" ? val : val.toString(), out_buffer); + } + /** @nocollapse */ + static fromNumber(num, out_buffer = new Uint32Array(4)) { + return _Int128.fromString(num.toString(), out_buffer); + } + /** @nocollapse */ + static fromString(str, out_buffer = new Uint32Array(4)) { + const negate2 = str.startsWith("-"); + const length = str.length; + const out = new _Int128(out_buffer); + for (let posn = negate2 ? 1 : 0; posn < length; ) { + const group = kInt32DecimalDigits < length - posn ? kInt32DecimalDigits : length - posn; + const chunk = new _Int128(new Uint32Array([Number.parseInt(str.slice(posn, posn + group), 10), 0, 0, 0])); + const multiple = new _Int128(new Uint32Array([kPowersOfTen[group], 0, 0, 0])); + out.times(multiple); + out.plus(chunk); + posn += group; + } + return negate2 ? out.negate() : out; + } + /** @nocollapse */ + static convertArray(values) { + const data = new Uint32Array(values.length * 4); + for (let i = -1, n = values.length; ++i < n; ) { + _Int128.from(values[i], new Uint32Array(data.buffer, data.byteOffset + 4 * 4 * i, 4)); } + return data; } }; } }); -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/service.js -var require_service = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/service.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServiceImpl = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var coreClient = tslib_1.__importStar(require_commonjs8()); - var Mappers = tslib_1.__importStar(require_mappers()); - var Parameters = tslib_1.__importStar(require_parameters()); - var ServiceImpl = class { - client; - /** - * Initialize a new instance of the class Service class. - * @param client Reference to the service client - */ - constructor(client) { - this.client = client; +// node_modules/apache-arrow/util/interval.mjs +var interval_exports = {}; +__export(interval_exports, { + toIntervalDayTimeInt32Array: () => toIntervalDayTimeInt32Array, + toIntervalDayTimeObjects: () => toIntervalDayTimeObjects, + toIntervalMonthDayNanoInt32Array: () => toIntervalMonthDayNanoInt32Array, + toIntervalMonthDayNanoObjects: () => toIntervalMonthDayNanoObjects +}); +function toIntervalDayTimeInt32Array(objects) { + var _a6, _b2; + const length = objects.length; + const array2 = new Int32Array(length * 2); + for (let oi = 0, ai = 0; oi < length; oi++) { + const interval = objects[oi]; + array2[ai++] = (_a6 = interval["days"]) !== null && _a6 !== void 0 ? _a6 : 0; + array2[ai++] = (_b2 = interval["milliseconds"]) !== null && _b2 !== void 0 ? _b2 : 0; + } + return array2; +} +function toIntervalMonthDayNanoInt32Array(objects) { + var _a6, _b2; + const length = objects.length; + const data = new Int32Array(length * 4); + for (let oi = 0, ai = 0; oi < length; oi++) { + const interval = objects[oi]; + data[ai++] = (_a6 = interval["months"]) !== null && _a6 !== void 0 ? _a6 : 0; + data[ai++] = (_b2 = interval["days"]) !== null && _b2 !== void 0 ? _b2 : 0; + const nanoseconds = interval["nanoseconds"]; + if (nanoseconds) { + const ns = BigInt(nanoseconds); + data[ai++] = Number(ns & BigInt(4294967295)) >>> 0; + data[ai++] = Number(ns >> BigInt(32)) >>> 0; + } else { + ai += 2; + } + } + return data; +} +function toIntervalDayTimeObjects(array2) { + const length = array2.length; + const objects = new Array(length / 2); + for (let ai = 0, oi = 0; ai < length; ai += 2) { + objects[oi++] = { + "days": array2[ai], + "milliseconds": array2[ai + 1] + }; + } + return objects; +} +function toIntervalMonthDayNanoObjects(array2, stringifyNano) { + const length = array2.length; + const objects = new Array(length / 4); + for (let ai = 0, oi = 0; ai < length; ai += 4) { + const nanoseconds = BigInt(array2[ai + 3]) << BigInt(32) | BigInt(array2[ai + 2] >>> 0); + objects[oi++] = { + "months": array2[ai], + "days": array2[ai + 1], + "nanoseconds": stringifyNano ? `${nanoseconds}` : nanoseconds + }; + } + return objects; +} +var init_interval2 = __esm({ + "node_modules/apache-arrow/util/interval.mjs"() { + } +}); + +// node_modules/apache-arrow/visitor/vectorloader.mjs +function hexStringToBytes(hexString) { + const data = new Uint8Array(hexString.length / 2); + for (let i = 0; i < hexString.length; i += 2) { + data[i >> 1] = Number.parseInt(hexString.slice(i, i + 2), 16); + } + return data; +} +function binaryDataFromJSON(values) { + return hexStringToBytes(values.join("")); +} +function parseViewDataFromJSON(views, parseInlined) { + const data = new Uint8Array(views.length * 16); + const dataView = new DataView(data.buffer); + for (const [i, view] of views.entries()) { + const offset = i * 16; + const size = view["SIZE"]; + dataView.setInt32(offset, size, true); + if (view["INLINED"] !== void 0) { + const bytes = parseInlined(view["INLINED"]); + for (let j = 0; j < bytes.length && j < 12; j++) { + data[offset + 4 + j] = bytes[j]; } - /** - * Sets properties for a storage account's Blob service endpoint, including properties for Storage - * Analytics and CORS (Cross-Origin Resource Sharing) rules - * @param blobServiceProperties The StorageService properties. - * @param options The options parameters. - */ - setProperties(blobServiceProperties, options) { - return this.client.sendOperationRequest({ blobServiceProperties, options }, setPropertiesOperationSpec); + } else { + const prefix = view["PREFIX_HEX"]; + for (let j = 0; j < 8 && j < prefix.length; j += 2) { + data[offset + 4 + (j >> 1)] = Number.parseInt(prefix.slice(j, j + 2), 16); } - /** - * gets the properties of a storage account's Blob service, including properties for Storage Analytics - * and CORS (Cross-Origin Resource Sharing) rules. - * @param options The options parameters. - */ - getProperties(options) { - return this.client.sendOperationRequest({ options }, getPropertiesOperationSpec); + dataView.setInt32(offset + 8, view["BUFFER_INDEX"], true); + dataView.setInt32(offset + 12, view["OFFSET"], true); + } + } + return data; +} +function binaryViewDataFromJSON(views) { + return parseViewDataFromJSON(views, (inlined) => { + const bytes = new Uint8Array(inlined.length / 2); + for (let i = 0; i < inlined.length; i += 2) { + bytes[i >> 1] = Number.parseInt(inlined.slice(i, i + 2), 16); + } + return bytes; + }); +} +function utf8ViewDataFromJSON(views) { + return parseViewDataFromJSON(views, (inlined) => { + const encoder2 = new TextEncoder(); + return encoder2.encode(inlined); + }); +} +var VectorLoader, JSONVectorLoader, CompressedVectorLoader; +var init_vectorloader = __esm({ + "node_modules/apache-arrow/visitor/vectorloader.mjs"() { + init_data(); + init_schema2(); + init_type2(); + init_visitor(); + init_bit(); + init_utf8(); + init_int2(); + init_enum(); + init_buffer(); + init_interval2(); + VectorLoader = class extends Visitor { + constructor(bytes, nodes, buffers, dictionaries, metadataVersion = MetadataVersion.V5, variadicBufferCounts = []) { + super(); + this.nodesIndex = -1; + this.buffersIndex = -1; + this.variadicBufferIndex = -1; + this.bytes = bytes; + this.nodes = nodes; + this.buffers = buffers; + this.dictionaries = dictionaries; + this.metadataVersion = metadataVersion; + this.variadicBufferCounts = variadicBufferCounts; } - /** - * Retrieves statistics related to replication for the Blob service. It is only available on the - * secondary location endpoint when read-access geo-redundant replication is enabled for the storage - * account. - * @param options The options parameters. - */ - getStatistics(options) { - return this.client.sendOperationRequest({ options }, getStatisticsOperationSpec); + visit(node) { + return super.visit(node instanceof Field2 ? node.type : node); } - /** - * The List Containers Segment operation returns a list of the containers under the specified account - * @param options The options parameters. - */ - listContainersSegment(options) { - return this.client.sendOperationRequest({ options }, listContainersSegmentOperationSpec); + visitNull(type, { length } = this.nextFieldNode()) { + return makeData({ type, length }); } - /** - * Retrieves a user delegation key for the Blob service. This is only a valid operation when using - * bearer token authentication. - * @param keyInfo Key information - * @param options The options parameters. - */ - getUserDelegationKey(keyInfo, options) { - return this.client.sendOperationRequest({ keyInfo, options }, getUserDelegationKeyOperationSpec); + visitBool(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) }); } - /** - * Returns the sku name and account kind - * @param options The options parameters. - */ - getAccountInfo(options) { - return this.client.sendOperationRequest({ options }, getAccountInfoOperationSpec); + visitInt(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) }); } - /** - * The Batch operation allows multiple API calls to be embedded into a single HTTP request. - * @param contentLength The length of the request. - * @param multipartContentType Required. The value of this header must be multipart/mixed with a batch - * boundary. Example header value: multipart/mixed; boundary=batch_ - * @param body Initial data - * @param options The options parameters. - */ - submitBatch(contentLength, multipartContentType, body, options) { - return this.client.sendOperationRequest({ contentLength, multipartContentType, body, options }, submitBatchOperationSpec); + visitFloat(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) }); } - /** - * The Filter Blobs operation enables callers to list blobs across all containers whose tags match a - * given search expression. Filter blobs searches across all containers within a storage account but - * can be scoped within the expression to a single container. - * @param options The options parameters. - */ - filterBlobs(options) { - return this.client.sendOperationRequest({ options }, filterBlobsOperationSpec); + visitUtf8(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), valueOffsets: this.readOffsets(type), data: this.readData(type) }); } - }; - exports2.ServiceImpl = ServiceImpl; - var xmlSerializer = coreClient.createSerializer( - Mappers, - /* isXml */ - true - ); - var setPropertiesOperationSpec = { - path: "/", - httpMethod: "PUT", - responses: { - 202: { - headersMapper: Mappers.ServiceSetPropertiesHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ServiceSetPropertiesExceptionHeaders - } - }, - requestBody: Parameters.blobServiceProperties, - queryParameters: [ - Parameters.restype, - Parameters.comp, - Parameters.timeoutInSeconds - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.contentType, - Parameters.accept, - Parameters.version, - Parameters.requestId - ], - isXML: true, - contentType: "application/xml; charset=utf-8", - mediaType: "xml", - serializer: xmlSerializer - }; - var getPropertiesOperationSpec = { - path: "/", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.BlobServiceProperties, - headersMapper: Mappers.ServiceGetPropertiesHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ServiceGetPropertiesExceptionHeaders - } - }, - queryParameters: [ - Parameters.restype, - Parameters.comp, - Parameters.timeoutInSeconds - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1 - ], - isXML: true, - serializer: xmlSerializer - }; - var getStatisticsOperationSpec = { - path: "/", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.BlobServiceStatistics, - headersMapper: Mappers.ServiceGetStatisticsHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ServiceGetStatisticsExceptionHeaders - } - }, - queryParameters: [ - Parameters.restype, - Parameters.timeoutInSeconds, - Parameters.comp1 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1 - ], - isXML: true, - serializer: xmlSerializer - }; - var listContainersSegmentOperationSpec = { - path: "/", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.ListContainersSegmentResponse, - headersMapper: Mappers.ServiceListContainersSegmentHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ServiceListContainersSegmentExceptionHeaders + visitLargeUtf8(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), valueOffsets: this.readOffsets(type), data: this.readData(type) }); + } + visitUtf8View(type, { length, nullCount } = this.nextFieldNode()) { + const nullBitmap = this.readNullBitmap(type, nullCount); + const views = this.readData(type); + const variadicBuffers = this.readVariadicBuffers(this.nextVariadicBufferCount()); + return makeData({ + type, + length, + nullCount, + nullBitmap, + ["views"]: views, + ["variadicBuffers"]: variadicBuffers + }); + } + visitBinary(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), valueOffsets: this.readOffsets(type), data: this.readData(type) }); + } + visitLargeBinary(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), valueOffsets: this.readOffsets(type), data: this.readData(type) }); + } + visitBinaryView(type, { length, nullCount } = this.nextFieldNode()) { + const nullBitmap = this.readNullBitmap(type, nullCount); + const views = this.readData(type); + const variadicBuffers = this.readVariadicBuffers(this.nextVariadicBufferCount()); + return makeData({ + type, + length, + nullCount, + nullBitmap, + ["views"]: views, + ["variadicBuffers"]: variadicBuffers + }); + } + visitFixedSizeBinary(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) }); + } + visitDate(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) }); + } + visitTimestamp(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) }); + } + visitTime(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) }); + } + visitDecimal(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) }); + } + visitList(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), valueOffsets: this.readOffsets(type), "child": this.visit(type.children[0]) }); + } + visitLargeList(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), valueOffsets: this.readOffsets(type), "child": this.visit(type.children[0]) }); + } + visitStruct(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), children: this.visitMany(type.children) }); + } + visitUnion(type, { length, nullCount } = this.nextFieldNode()) { + if (this.metadataVersion < MetadataVersion.V5) { + this.readNullBitmap(type, nullCount); } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.comp2, - Parameters.prefix, - Parameters.marker, - Parameters.maxPageSize, - Parameters.include - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1 - ], - isXML: true, - serializer: xmlSerializer + return type.mode === UnionMode.Sparse ? this.visitSparseUnion(type, { length, nullCount }) : this.visitDenseUnion(type, { length, nullCount }); + } + visitDenseUnion(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, typeIds: this.readTypeIds(type), valueOffsets: this.readOffsets(type), children: this.visitMany(type.children) }); + } + visitSparseUnion(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, typeIds: this.readTypeIds(type), children: this.visitMany(type.children) }); + } + visitDictionary(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type.indices), dictionary: this.readDictionary(type) }); + } + visitInterval(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) }); + } + visitDuration(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) }); + } + visitFixedSizeList(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), "child": this.visit(type.children[0]) }); + } + visitMap(type, { length, nullCount } = this.nextFieldNode()) { + return makeData({ type, length, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), valueOffsets: this.readOffsets(type), "child": this.visit(type.children[0]) }); + } + nextFieldNode() { + return this.nodes[++this.nodesIndex]; + } + nextBufferRange() { + return this.buffers[++this.buffersIndex]; + } + readNullBitmap(type, nullCount, buffer = this.nextBufferRange()) { + return nullCount > 0 && this.readData(type, buffer) || new Uint8Array(0); + } + readOffsets(type, buffer) { + return this.readData(type, buffer); + } + readTypeIds(type, buffer) { + return this.readData(type, buffer); + } + readData(_type, { length, offset } = this.nextBufferRange()) { + return this.bytes.subarray(offset, offset + length); + } + readVariadicBuffers(length) { + return Array.from({ length }, () => this.readData(null)); + } + nextVariadicBufferCount() { + var _a6; + return (_a6 = this.variadicBufferCounts[++this.variadicBufferIndex]) !== null && _a6 !== void 0 ? _a6 : 0; + } + readDictionary(type) { + return this.dictionaries.get(type.id); + } }; - var getUserDelegationKeyOperationSpec = { - path: "/", - httpMethod: "POST", - responses: { - 200: { - bodyMapper: Mappers.UserDelegationKey, - headersMapper: Mappers.ServiceGetUserDelegationKeyHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ServiceGetUserDelegationKeyExceptionHeaders + JSONVectorLoader = class extends VectorLoader { + constructor(sources, nodes, buffers, dictionaries, metadataVersion, variadicBufferCounts = []) { + super(new Uint8Array(0), nodes, buffers, dictionaries, metadataVersion, variadicBufferCounts); + this.sources = sources; + } + readNullBitmap(_type, nullCount, { offset } = this.nextBufferRange()) { + return nullCount <= 0 ? new Uint8Array(0) : packBools(this.sources[offset]); + } + readOffsets(_type, { offset } = this.nextBufferRange()) { + return toArrayBufferView(Uint8Array, toArrayBufferView(_type.OffsetArrayType, this.sources[offset])); + } + readTypeIds(type, { offset } = this.nextBufferRange()) { + return toArrayBufferView(Uint8Array, toArrayBufferView(type.ArrayType, this.sources[offset])); + } + readData(type, { offset } = this.nextBufferRange()) { + const { sources } = this; + if (DataType.isTimestamp(type)) { + return toArrayBufferView(Uint8Array, Int642.convertArray(sources[offset])); + } else if ((DataType.isInt(type) || DataType.isTime(type)) && type.bitWidth === 64 || DataType.isDuration(type)) { + return toArrayBufferView(Uint8Array, Int642.convertArray(sources[offset])); + } else if (DataType.isDate(type) && type.unit === DateUnit.MILLISECOND) { + return toArrayBufferView(Uint8Array, Int642.convertArray(sources[offset])); + } else if (DataType.isDecimal(type)) { + return toArrayBufferView(Uint8Array, Int128.convertArray(sources[offset])); + } else if (DataType.isBinary(type) || DataType.isLargeBinary(type) || DataType.isFixedSizeBinary(type)) { + return binaryDataFromJSON(sources[offset]); + } else if (DataType.isBinaryView(type)) { + return binaryViewDataFromJSON(sources[offset]); + } else if (DataType.isUtf8View(type)) { + return utf8ViewDataFromJSON(sources[offset]); + } else if (DataType.isBool(type)) { + return packBools(sources[offset]); + } else if (DataType.isUtf8(type) || DataType.isLargeUtf8(type)) { + return encodeUtf8(sources[offset].join("")); + } else if (DataType.isInterval(type)) { + switch (type.unit) { + case IntervalUnit.DAY_TIME: + return toIntervalDayTimeInt32Array(sources[offset]); + case IntervalUnit.MONTH_DAY_NANO: + return toIntervalMonthDayNanoInt32Array(sources[offset]); + default: + break; + } } - }, - requestBody: Parameters.keyInfo, - queryParameters: [ - Parameters.restype, - Parameters.timeoutInSeconds, - Parameters.comp3 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.contentType, - Parameters.accept, - Parameters.version, - Parameters.requestId - ], - isXML: true, - contentType: "application/xml; charset=utf-8", - mediaType: "xml", - serializer: xmlSerializer - }; - var getAccountInfoOperationSpec = { - path: "/", - httpMethod: "GET", - responses: { - 200: { - headersMapper: Mappers.ServiceGetAccountInfoHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ServiceGetAccountInfoExceptionHeaders + return toArrayBufferView(Uint8Array, toArrayBufferView(type.ArrayType, sources[offset].map((x) => +x))); + } + readVariadicBuffers(length) { + const buffers = []; + for (let i = 0; i < length; i++) { + const { offset } = this.nextBufferRange(); + const hexString = this.sources[offset]; + buffers.push(hexStringToBytes(hexString)); } - }, - queryParameters: [ - Parameters.comp, - Parameters.timeoutInSeconds, - Parameters.restype1 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1 - ], - isXML: true, - serializer: xmlSerializer + return buffers; + } }; - var submitBatchOperationSpec = { - path: "/", - httpMethod: "POST", - responses: { - 202: { - bodyMapper: { - type: { name: "Stream" }, - serializedName: "parsedResponse" - }, - headersMapper: Mappers.ServiceSubmitBatchHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ServiceSubmitBatchExceptionHeaders - } - }, - requestBody: Parameters.body, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp4], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.accept, - Parameters.version, - Parameters.requestId, - Parameters.contentLength, - Parameters.multipartContentType - ], - isXML: true, - contentType: "application/xml; charset=utf-8", - mediaType: "xml", - serializer: xmlSerializer + CompressedVectorLoader = class extends VectorLoader { + constructor(bodyChunks, nodes, buffers, dictionaries, metadataVersion, variadicBufferCounts = []) { + super(new Uint8Array(0), nodes, buffers, dictionaries, metadataVersion, variadicBufferCounts); + this.bodyChunks = bodyChunks; + } + readData(_type, _buffer = this.nextBufferRange()) { + return this.bodyChunks[this.buffersIndex]; + } }; - var filterBlobsOperationSpec = { - path: "/", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.FilterBlobSegment, - headersMapper: Mappers.ServiceFilterBlobsHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ServiceFilterBlobsExceptionHeaders + } +}); + +// node_modules/apache-arrow/builder/binary.mjs +var BinaryBuilder; +var init_binary2 = __esm({ + "node_modules/apache-arrow/builder/binary.mjs"() { + init_buffer3(); + init_builder(); + init_buffer(); + BinaryBuilder = class extends VariableWidthBuilder { + constructor(opts) { + super(opts); + this._values = new BufferBuilder(Uint8Array); + } + get byteLength() { + let size = this._pendingLength + this.length * 4; + this._offsets && (size += this._offsets.byteLength); + this._values && (size += this._values.byteLength); + this._nulls && (size += this._nulls.byteLength); + return size; + } + setValue(index2, value) { + return super.setValue(index2, toUint8Array(value)); + } + _flushPending(pending, pendingLength) { + const offsets = this._offsets; + const data = this._values.reserve(pendingLength).buffer; + let offset = 0; + for (const [index2, value] of pending) { + if (value === void 0) { + offsets.set(index2, 0); + } else { + const length = value.length; + data.set(value, offset); + offsets.set(index2, length); + offset += length; + } } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.marker, - Parameters.maxPageSize, - Parameters.comp5, - Parameters.where - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1 - ], - isXML: true, - serializer: xmlSerializer + } }; } }); -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/container.js -var require_container = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/container.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ContainerImpl = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var coreClient = tslib_1.__importStar(require_commonjs8()); - var Mappers = tslib_1.__importStar(require_mappers()); - var Parameters = tslib_1.__importStar(require_parameters()); - var ContainerImpl = class { - client; - /** - * Initialize a new instance of the class Container class. - * @param client Reference to the service client - */ - constructor(client) { - this.client = client; +// node_modules/apache-arrow/builder/largebinary.mjs +var LargeBinaryBuilder; +var init_largebinary = __esm({ + "node_modules/apache-arrow/builder/largebinary.mjs"() { + init_buffer(); + init_buffer3(); + init_builder(); + LargeBinaryBuilder = class extends VariableWidthBuilder { + constructor(opts) { + super(opts); + this._values = new BufferBuilder(Uint8Array); } - /** - * creates a new container under the specified account. If the container with the same name already - * exists, the operation fails - * @param options The options parameters. - */ - create(options) { - return this.client.sendOperationRequest({ options }, createOperationSpec); + get byteLength() { + let size = this._pendingLength + this.length * 4; + this._offsets && (size += this._offsets.byteLength); + this._values && (size += this._values.byteLength); + this._nulls && (size += this._nulls.byteLength); + return size; } - /** - * returns all user-defined metadata and system properties for the specified container. The data - * returned does not include the container's list of blobs - * @param options The options parameters. - */ - getProperties(options) { - return this.client.sendOperationRequest({ options }, getPropertiesOperationSpec); + setValue(index2, value) { + return super.setValue(index2, toUint8Array(value)); } - /** - * operation marks the specified container for deletion. The container and any blobs contained within - * it are later deleted during garbage collection - * @param options The options parameters. - */ - delete(options) { - return this.client.sendOperationRequest({ options }, deleteOperationSpec); + _flushPending(pending, pendingLength) { + const offsets = this._offsets; + const data = this._values.reserve(pendingLength).buffer; + let offset = 0; + for (const [index2, value] of pending) { + if (value === void 0) { + offsets.set(index2, BigInt(0)); + } else { + const length = value.length; + data.set(value, offset); + offsets.set(index2, BigInt(length)); + offset += length; + } + } } - /** - * operation sets one or more user-defined name-value pairs for the specified container. - * @param options The options parameters. - */ - setMetadata(options) { - return this.client.sendOperationRequest({ options }, setMetadataOperationSpec); + }; + } +}); + +// node_modules/apache-arrow/builder/bool.mjs +var BoolBuilder; +var init_bool2 = __esm({ + "node_modules/apache-arrow/builder/bool.mjs"() { + init_buffer3(); + init_builder(); + BoolBuilder = class extends Builder { + constructor(options) { + super(options); + this._values = new BitmapBufferBuilder(); } - /** - * gets the permissions for the specified container. The permissions indicate whether container data - * may be accessed publicly. - * @param options The options parameters. - */ - getAccessPolicy(options) { - return this.client.sendOperationRequest({ options }, getAccessPolicyOperationSpec); + setValue(index2, value) { + this._values.set(index2, +value); } - /** - * sets the permissions for the specified container. The permissions indicate whether blobs in a - * container may be accessed publicly. - * @param options The options parameters. - */ - setAccessPolicy(options) { - return this.client.sendOperationRequest({ options }, setAccessPolicyOperationSpec); + }; + } +}); + +// node_modules/apache-arrow/builder/date.mjs +var DateBuilder, DateDayBuilder, DateMillisecondBuilder; +var init_date2 = __esm({ + "node_modules/apache-arrow/builder/date.mjs"() { + init_builder(); + init_set(); + DateBuilder = class extends FixedWidthBuilder { + }; + DateBuilder.prototype._setValue = setDate; + DateDayBuilder = class extends DateBuilder { + }; + DateDayBuilder.prototype._setValue = setDateDay; + DateMillisecondBuilder = class extends DateBuilder { + }; + DateMillisecondBuilder.prototype._setValue = setDateMillisecond; + } +}); + +// node_modules/apache-arrow/builder/decimal.mjs +var DecimalBuilder; +var init_decimal2 = __esm({ + "node_modules/apache-arrow/builder/decimal.mjs"() { + init_builder(); + init_set(); + DecimalBuilder = class extends FixedWidthBuilder { + }; + DecimalBuilder.prototype._setValue = setDecimal; + } +}); + +// node_modules/apache-arrow/builder/dictionary.mjs +var DictionaryBuilder; +var init_dictionary = __esm({ + "node_modules/apache-arrow/builder/dictionary.mjs"() { + init_type2(); + init_builder(); + init_factories(); + DictionaryBuilder = class extends Builder { + constructor({ "type": type, "nullValues": nulls, "dictionaryHashFunction": hashFn }) { + super({ type: new Dictionary(type.dictionary, type.indices, type.id, type.isOrdered) }); + this._nulls = null; + this._dictionaryOffset = 0; + this._keysToIndices = /* @__PURE__ */ Object.create(null); + this.indices = makeBuilder({ "type": this.type.indices, "nullValues": nulls }); + this.dictionary = makeBuilder({ "type": this.type.dictionary, "nullValues": null }); + if (typeof hashFn === "function") { + this.valueToKey = hashFn; + } } - /** - * Restores a previously-deleted container. - * @param options The options parameters. - */ - restore(options) { - return this.client.sendOperationRequest({ options }, restoreOperationSpec); + get values() { + return this.indices.values; } - /** - * Renames an existing container. - * @param sourceContainerName Required. Specifies the name of the container to rename. - * @param options The options parameters. - */ - rename(sourceContainerName, options) { - return this.client.sendOperationRequest({ sourceContainerName, options }, renameOperationSpec); + get nullCount() { + return this.indices.nullCount; } - /** - * The Batch operation allows multiple API calls to be embedded into a single HTTP request. - * @param contentLength The length of the request. - * @param multipartContentType Required. The value of this header must be multipart/mixed with a batch - * boundary. Example header value: multipart/mixed; boundary=batch_ - * @param body Initial data - * @param options The options parameters. - */ - submitBatch(contentLength, multipartContentType, body, options) { - return this.client.sendOperationRequest({ contentLength, multipartContentType, body, options }, submitBatchOperationSpec); + get nullBitmap() { + return this.indices.nullBitmap; } - /** - * The Filter Blobs operation enables callers to list blobs in a container whose tags match a given - * search expression. Filter blobs searches within the given container. - * @param options The options parameters. - */ - filterBlobs(options) { - return this.client.sendOperationRequest({ options }, filterBlobsOperationSpec); + get byteLength() { + return this.indices.byteLength + this.dictionary.byteLength; } - /** - * [Update] establishes and manages a lock on a container for delete operations. The lock duration can - * be 15 to 60 seconds, or can be infinite - * @param options The options parameters. - */ - acquireLease(options) { - return this.client.sendOperationRequest({ options }, acquireLeaseOperationSpec); + get reservedLength() { + return this.indices.reservedLength + this.dictionary.reservedLength; } - /** - * [Update] establishes and manages a lock on a container for delete operations. The lock duration can - * be 15 to 60 seconds, or can be infinite - * @param leaseId Specifies the current lease ID on the resource. - * @param options The options parameters. - */ - releaseLease(leaseId, options) { - return this.client.sendOperationRequest({ leaseId, options }, releaseLeaseOperationSpec); + get reservedByteLength() { + return this.indices.reservedByteLength + this.dictionary.reservedByteLength; } - /** - * [Update] establishes and manages a lock on a container for delete operations. The lock duration can - * be 15 to 60 seconds, or can be infinite - * @param leaseId Specifies the current lease ID on the resource. - * @param options The options parameters. - */ - renewLease(leaseId, options) { - return this.client.sendOperationRequest({ leaseId, options }, renewLeaseOperationSpec); + isValid(value) { + return this.indices.isValid(value); } - /** - * [Update] establishes and manages a lock on a container for delete operations. The lock duration can - * be 15 to 60 seconds, or can be infinite - * @param options The options parameters. - */ - breakLease(options) { - return this.client.sendOperationRequest({ options }, breakLeaseOperationSpec); + setValid(index2, valid4) { + const indices = this.indices; + valid4 = indices.setValid(index2, valid4); + this.length = indices.length; + return valid4; } - /** - * [Update] establishes and manages a lock on a container for delete operations. The lock duration can - * be 15 to 60 seconds, or can be infinite - * @param leaseId Specifies the current lease ID on the resource. - * @param proposedLeaseId Proposed lease ID, in a GUID string format. The Blob service returns 400 - * (Invalid request) if the proposed lease ID is not in the correct format. See Guid Constructor - * (String) for a list of valid GUID string formats. - * @param options The options parameters. - */ - changeLease(leaseId, proposedLeaseId, options) { - return this.client.sendOperationRequest({ leaseId, proposedLeaseId, options }, changeLeaseOperationSpec); + setValue(index2, value) { + const keysToIndices = this._keysToIndices; + const key = this.valueToKey(value); + let idx = keysToIndices[key]; + if (idx === void 0) { + keysToIndices[key] = idx = this._dictionaryOffset + this.dictionary.append(value).length - 1; + } + return this.indices.setValue(index2, idx); } - /** - * [Update] The List Blobs operation returns a list of the blobs under the specified container - * @param options The options parameters. - */ - listBlobFlatSegment(options) { - return this.client.sendOperationRequest({ options }, listBlobFlatSegmentOperationSpec); + flush() { + const type = this.type; + const prev = this._dictionary; + const curr = this.dictionary.toVector(); + const data = this.indices.flush().clone(type); + data.dictionary = prev ? prev.concat(curr) : curr; + this.finished || (this._dictionaryOffset += curr.length); + this._dictionary = data.dictionary; + this.clear(); + return data; } - /** - * [Update] The List Blobs operation returns a list of the blobs under the specified container - * @param delimiter When the request includes this parameter, the operation returns a BlobPrefix - * element in the response body that acts as a placeholder for all blobs whose names begin with the - * same substring up to the appearance of the delimiter character. The delimiter may be a single - * character or a string. - * @param options The options parameters. - */ - listBlobHierarchySegment(delimiter, options) { - return this.client.sendOperationRequest({ delimiter, options }, listBlobHierarchySegmentOperationSpec); + finish() { + this.indices.finish(); + this.dictionary.finish(); + this._dictionaryOffset = 0; + this._keysToIndices = /* @__PURE__ */ Object.create(null); + return super.finish(); } - /** - * Returns the sku name and account kind - * @param options The options parameters. - */ - getAccountInfo(options) { - return this.client.sendOperationRequest({ options }, getAccountInfoOperationSpec); + clear() { + this.indices.clear(); + this.dictionary.clear(); + return super.clear(); + } + valueToKey(val) { + return typeof val === "string" ? val : `${val}`; } }; - exports2.ContainerImpl = ContainerImpl; - var xmlSerializer = coreClient.createSerializer( - Mappers, - /* isXml */ - true - ); - var createOperationSpec = { - path: "/{containerName}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.ContainerCreateHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerCreateExceptionHeaders - } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.restype2], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.metadata, - Parameters.access, - Parameters.defaultEncryptionScope, - Parameters.preventEncryptionScopeOverride - ], - isXML: true, - serializer: xmlSerializer + } +}); + +// node_modules/apache-arrow/builder/fixedsizebinary.mjs +var FixedSizeBinaryBuilder; +var init_fixedsizebinary = __esm({ + "node_modules/apache-arrow/builder/fixedsizebinary.mjs"() { + init_builder(); + init_set(); + FixedSizeBinaryBuilder = class extends FixedWidthBuilder { }; - var getPropertiesOperationSpec = { - path: "/{containerName}", - httpMethod: "GET", - responses: { - 200: { - headersMapper: Mappers.ContainerGetPropertiesHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerGetPropertiesExceptionHeaders + FixedSizeBinaryBuilder.prototype._setValue = setFixedSizeBinary; + } +}); + +// node_modules/apache-arrow/builder/fixedsizelist.mjs +var FixedSizeListBuilder; +var init_fixedsizelist = __esm({ + "node_modules/apache-arrow/builder/fixedsizelist.mjs"() { + init_schema2(); + init_builder(); + init_type2(); + FixedSizeListBuilder = class extends Builder { + setValue(index2, value) { + const [child] = this.children; + const start = index2 * this.stride; + for (let i = -1, n = this.stride; ++i < n; ) { + child.set(start + i, value[i]); } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.restype2], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId - ], - isXML: true, - serializer: xmlSerializer - }; - var deleteOperationSpec = { - path: "/{containerName}", - httpMethod: "DELETE", - responses: { - 202: { - headersMapper: Mappers.ContainerDeleteHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerDeleteExceptionHeaders + } + setValid(index2, valid4) { + if (!super.setValid(index2, valid4)) { + this.children[0].setValid((index2 + 1) * this.stride - 1, false); } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.restype2], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince - ], - isXML: true, - serializer: xmlSerializer - }; - var setMetadataOperationSpec = { - path: "/{containerName}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.ContainerSetMetadataHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerSetMetadataExceptionHeaders + return valid4; + } + addChild(child, name = "0") { + if (this.numChildren > 0) { + throw new Error("FixedSizeListBuilder can only have one child."); } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.restype2, - Parameters.comp6 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.metadata, - Parameters.leaseId, - Parameters.ifModifiedSince - ], - isXML: true, - serializer: xmlSerializer + const childIndex = this.children.push(child); + this.type = new FixedSizeList2(this.type.listSize, new Field2(name, child.type, true)); + return childIndex; + } }; - var getAccessPolicyOperationSpec = { - path: "/{containerName}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: { - type: { - name: "Sequence", - element: { - type: { name: "Composite", className: "SignedIdentifier" } - } - }, - serializedName: "SignedIdentifiers", - xmlName: "SignedIdentifiers", - xmlIsWrapped: true, - xmlElementName: "SignedIdentifier" - }, - headersMapper: Mappers.ContainerGetAccessPolicyHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerGetAccessPolicyExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.restype2, - Parameters.comp7 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId - ], - isXML: true, - serializer: xmlSerializer + } +}); + +// node_modules/apache-arrow/builder/float.mjs +var FloatBuilder, Float16Builder, Float32Builder, Float64Builder; +var init_float = __esm({ + "node_modules/apache-arrow/builder/float.mjs"() { + init_math(); + init_builder(); + FloatBuilder = class extends FixedWidthBuilder { + setValue(index2, value) { + this._values.set(index2, value); + } }; - var setAccessPolicyOperationSpec = { - path: "/{containerName}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.ContainerSetAccessPolicyHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerSetAccessPolicyExceptionHeaders - } - }, - requestBody: Parameters.containerAcl, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.restype2, - Parameters.comp7 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.contentType, - Parameters.accept, - Parameters.version, - Parameters.requestId, - Parameters.access, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince - ], - isXML: true, - contentType: "application/xml; charset=utf-8", - mediaType: "xml", - serializer: xmlSerializer + Float16Builder = class extends FloatBuilder { + setValue(index2, value) { + super.setValue(index2, float64ToUint16(value)); + } }; - var restoreOperationSpec = { - path: "/{containerName}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.ContainerRestoreHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerRestoreExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.restype2, - Parameters.comp8 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.deletedContainerName, - Parameters.deletedContainerVersion - ], - isXML: true, - serializer: xmlSerializer + Float32Builder = class extends FloatBuilder { }; - var renameOperationSpec = { - path: "/{containerName}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.ContainerRenameHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerRenameExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.restype2, - Parameters.comp9 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.sourceContainerName, - Parameters.sourceLeaseId - ], - isXML: true, - serializer: xmlSerializer + Float64Builder = class extends FloatBuilder { }; - var submitBatchOperationSpec = { - path: "/{containerName}", - httpMethod: "POST", - responses: { - 202: { - bodyMapper: { - type: { name: "Stream" }, - serializedName: "parsedResponse" - }, - headersMapper: Mappers.ContainerSubmitBatchHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerSubmitBatchExceptionHeaders - } - }, - requestBody: Parameters.body, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.comp4, - Parameters.restype2 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.accept, - Parameters.version, - Parameters.requestId, - Parameters.contentLength, - Parameters.multipartContentType - ], - isXML: true, - contentType: "application/xml; charset=utf-8", - mediaType: "xml", - serializer: xmlSerializer + } +}); + +// node_modules/apache-arrow/builder/interval.mjs +var IntervalBuilder, IntervalDayTimeBuilder, IntervalYearMonthBuilder, IntervalMonthDayNanoBuilder; +var init_interval3 = __esm({ + "node_modules/apache-arrow/builder/interval.mjs"() { + init_builder(); + init_set(); + IntervalBuilder = class extends FixedWidthBuilder { }; - var filterBlobsOperationSpec = { - path: "/{containerName}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.FilterBlobSegment, - headersMapper: Mappers.ContainerFilterBlobsHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerFilterBlobsExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.marker, - Parameters.maxPageSize, - Parameters.comp5, - Parameters.where, - Parameters.restype2 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1 - ], - isXML: true, - serializer: xmlSerializer + IntervalBuilder.prototype._setValue = setIntervalValue; + IntervalDayTimeBuilder = class extends IntervalBuilder { }; - var acquireLeaseOperationSpec = { - path: "/{containerName}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.ContainerAcquireLeaseHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerAcquireLeaseExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.restype2, - Parameters.comp10 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.action, - Parameters.duration, - Parameters.proposedLeaseId - ], - isXML: true, - serializer: xmlSerializer + IntervalDayTimeBuilder.prototype._setValue = setIntervalDayTime; + IntervalYearMonthBuilder = class extends IntervalBuilder { }; - var releaseLeaseOperationSpec = { - path: "/{containerName}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.ContainerReleaseLeaseHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerReleaseLeaseExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.restype2, - Parameters.comp10 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.action1, - Parameters.leaseId1 - ], - isXML: true, - serializer: xmlSerializer + IntervalYearMonthBuilder.prototype._setValue = setIntervalYearMonth; + IntervalMonthDayNanoBuilder = class extends IntervalBuilder { }; - var renewLeaseOperationSpec = { - path: "/{containerName}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.ContainerRenewLeaseHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerRenewLeaseExceptionHeaders + IntervalMonthDayNanoBuilder.prototype._setValue = setIntervalMonthDayNano; + } +}); + +// node_modules/apache-arrow/builder/duration.mjs +var DurationBuilder, DurationSecondBuilder, DurationMillisecondBuilder, DurationMicrosecondBuilder, DurationNanosecondBuilder; +var init_duration2 = __esm({ + "node_modules/apache-arrow/builder/duration.mjs"() { + init_builder(); + init_set(); + DurationBuilder = class extends FixedWidthBuilder { + }; + DurationBuilder.prototype._setValue = setDuration; + DurationSecondBuilder = class extends DurationBuilder { + }; + DurationSecondBuilder.prototype._setValue = setDurationSecond; + DurationMillisecondBuilder = class extends DurationBuilder { + }; + DurationMillisecondBuilder.prototype._setValue = setDurationMillisecond; + DurationMicrosecondBuilder = class extends DurationBuilder { + }; + DurationMicrosecondBuilder.prototype._setValue = setDurationMicrosecond; + DurationNanosecondBuilder = class extends DurationBuilder { + }; + DurationNanosecondBuilder.prototype._setValue = setDurationNanosecond; + } +}); + +// node_modules/apache-arrow/builder/int.mjs +var IntBuilder, Int8Builder, Int16Builder, Int32Builder, Int64Builder, Uint8Builder, Uint16Builder, Uint32Builder, Uint64Builder; +var init_int3 = __esm({ + "node_modules/apache-arrow/builder/int.mjs"() { + init_builder(); + IntBuilder = class extends FixedWidthBuilder { + setValue(index2, value) { + this._values.set(index2, value); + } + }; + Int8Builder = class extends IntBuilder { + }; + Int16Builder = class extends IntBuilder { + }; + Int32Builder = class extends IntBuilder { + }; + Int64Builder = class extends IntBuilder { + }; + Uint8Builder = class extends IntBuilder { + }; + Uint16Builder = class extends IntBuilder { + }; + Uint32Builder = class extends IntBuilder { + }; + Uint64Builder = class extends IntBuilder { + }; + } +}); + +// node_modules/apache-arrow/builder/list.mjs +var ListBuilder; +var init_list2 = __esm({ + "node_modules/apache-arrow/builder/list.mjs"() { + init_schema2(); + init_type2(); + init_buffer3(); + init_builder(); + ListBuilder = class extends VariableWidthBuilder { + constructor(opts) { + super(opts); + this._offsets = new OffsetsBufferBuilder(opts.type); + } + addChild(child, name = "0") { + if (this.numChildren > 0) { + throw new Error("ListBuilder can only have one child."); + } + this.children[this.numChildren] = child; + this.type = new List2(new Field2(name, child.type, true)); + return this.numChildren - 1; + } + _flushPending(pending) { + const offsets = this._offsets; + const [child] = this.children; + for (const [index2, value] of pending) { + if (typeof value === "undefined") { + offsets.set(index2, 0); + } else { + const v = value; + const n = v.length; + const start = offsets.set(index2, n).buffer[index2]; + for (let i = -1; ++i < n; ) { + child.set(start + i, v[i]); + } + } } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.restype2, - Parameters.comp10 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.leaseId1, - Parameters.action2 - ], - isXML: true, - serializer: xmlSerializer + } }; - var breakLeaseOperationSpec = { - path: "/{containerName}", - httpMethod: "PUT", - responses: { - 202: { - headersMapper: Mappers.ContainerBreakLeaseHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerBreakLeaseExceptionHeaders + } +}); + +// node_modules/apache-arrow/builder/largelist.mjs +var LargeListBuilder; +var init_largelist = __esm({ + "node_modules/apache-arrow/builder/largelist.mjs"() { + init_schema2(); + init_type2(); + init_buffer3(); + init_bigint(); + init_builder(); + LargeListBuilder = class extends VariableWidthBuilder { + constructor(opts) { + super(opts); + this._offsets = new OffsetsBufferBuilder(opts.type); + } + addChild(child, name = "0") { + if (this.numChildren > 0) { + throw new Error("LargeListBuilder can only have one child."); + } + this.children[this.numChildren] = child; + this.type = new LargeList2(new Field2(name, child.type, true)); + return this.numChildren - 1; + } + _flushPending(pending) { + const offsets = this._offsets; + const [child] = this.children; + for (const [index2, value] of pending) { + if (typeof value === "undefined") { + offsets.set(index2, BigInt(0)); + } else { + const v = value; + const n = v.length; + const start = bigIntToNumber(offsets.set(index2, BigInt(n)).buffer[index2]); + for (let i = -1; ++i < n; ) { + child.set(start + i, v[i]); + } + } } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.restype2, - Parameters.comp10 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.action3, - Parameters.breakPeriod - ], - isXML: true, - serializer: xmlSerializer + } }; - var changeLeaseOperationSpec = { - path: "/{containerName}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.ContainerChangeLeaseHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerChangeLeaseExceptionHeaders + } +}); + +// node_modules/apache-arrow/builder/map.mjs +var MapBuilder; +var init_map3 = __esm({ + "node_modules/apache-arrow/builder/map.mjs"() { + init_schema2(); + init_type2(); + init_builder(); + MapBuilder = class extends VariableWidthBuilder { + set(index2, value) { + return super.set(index2, value); + } + setValue(index2, value) { + const row = value instanceof Map ? value : new Map(Object.entries(value)); + const pending = this._pending || (this._pending = /* @__PURE__ */ new Map()); + const current = pending.get(index2); + current && (this._pendingLength -= current.size); + this._pendingLength += row.size; + pending.set(index2, row); + } + addChild(child, name = `${this.numChildren}`) { + if (this.numChildren > 0) { + throw new Error("ListBuilder can only have one child."); } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.restype2, - Parameters.comp10 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.leaseId1, - Parameters.action4, - Parameters.proposedLeaseId1 - ], - isXML: true, - serializer: xmlSerializer + this.children[this.numChildren] = child; + this.type = new Map_(new Field2(name, child.type, true), this.type.keysSorted); + return this.numChildren - 1; + } + _flushPending(pending) { + const offsets = this._offsets; + const [child] = this.children; + for (const [index2, value] of pending) { + if (value === void 0) { + offsets.set(index2, 0); + } else { + let { [index2]: idx, [index2 + 1]: end } = offsets.set(index2, value.size).buffer; + for (const val of value.entries()) { + child.set(idx, val); + if (++idx >= end) + break; + } + } + } + } }; - var listBlobFlatSegmentOperationSpec = { - path: "/{containerName}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.ListBlobsFlatSegmentResponse, - headersMapper: Mappers.ContainerListBlobFlatSegmentHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerListBlobFlatSegmentExceptionHeaders + } +}); + +// node_modules/apache-arrow/builder/null.mjs +var NullBuilder; +var init_null2 = __esm({ + "node_modules/apache-arrow/builder/null.mjs"() { + init_builder(); + NullBuilder = class extends Builder { + // @ts-ignore + setValue(index2, value) { + } + setValid(index2, valid4) { + this.length = Math.max(index2 + 1, this.length); + return valid4; + } + }; + } +}); + +// node_modules/apache-arrow/builder/struct.mjs +var StructBuilder; +var init_struct3 = __esm({ + "node_modules/apache-arrow/builder/struct.mjs"() { + init_schema2(); + init_builder(); + init_type2(); + StructBuilder = class extends Builder { + setValue(index2, value) { + const { children, type } = this; + switch (Array.isArray(value) || value.constructor) { + case true: + return type.children.forEach((_2, i) => children[i].set(index2, value[i])); + case Map: + return type.children.forEach((f, i) => children[i].set(index2, value.get(f.name))); + default: + return type.children.forEach((f, i) => children[i].set(index2, value[f.name])); } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.comp2, - Parameters.prefix, - Parameters.marker, - Parameters.maxPageSize, - Parameters.restype2, - Parameters.include1 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1 - ], - isXML: true, - serializer: xmlSerializer + } + /** @inheritdoc */ + setValid(index2, valid4) { + if (!super.setValid(index2, valid4)) { + this.children.forEach((child) => child.setValid(index2, valid4)); + } + return valid4; + } + addChild(child, name = `${this.numChildren}`) { + const childIndex = this.children.push(child); + this.type = new Struct([...this.type.children, new Field2(name, child.type, true)]); + return childIndex; + } }; - var listBlobHierarchySegmentOperationSpec = { - path: "/{containerName}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.ListBlobsHierarchySegmentResponse, - headersMapper: Mappers.ContainerListBlobHierarchySegmentHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerListBlobHierarchySegmentExceptionHeaders + } +}); + +// node_modules/apache-arrow/builder/timestamp.mjs +var TimestampBuilder, TimestampSecondBuilder, TimestampMillisecondBuilder, TimestampMicrosecondBuilder, TimestampNanosecondBuilder; +var init_timestamp2 = __esm({ + "node_modules/apache-arrow/builder/timestamp.mjs"() { + init_builder(); + init_set(); + TimestampBuilder = class extends FixedWidthBuilder { + }; + TimestampBuilder.prototype._setValue = setTimestamp; + TimestampSecondBuilder = class extends TimestampBuilder { + }; + TimestampSecondBuilder.prototype._setValue = setTimestampSecond; + TimestampMillisecondBuilder = class extends TimestampBuilder { + }; + TimestampMillisecondBuilder.prototype._setValue = setTimestampMillisecond; + TimestampMicrosecondBuilder = class extends TimestampBuilder { + }; + TimestampMicrosecondBuilder.prototype._setValue = setTimestampMicrosecond; + TimestampNanosecondBuilder = class extends TimestampBuilder { + }; + TimestampNanosecondBuilder.prototype._setValue = setTimestampNanosecond; + } +}); + +// node_modules/apache-arrow/builder/time.mjs +var TimeBuilder, TimeSecondBuilder, TimeMillisecondBuilder, TimeMicrosecondBuilder, TimeNanosecondBuilder; +var init_time2 = __esm({ + "node_modules/apache-arrow/builder/time.mjs"() { + init_builder(); + init_set(); + TimeBuilder = class extends FixedWidthBuilder { + }; + TimeBuilder.prototype._setValue = setTime; + TimeSecondBuilder = class extends TimeBuilder { + }; + TimeSecondBuilder.prototype._setValue = setTimeSecond; + TimeMillisecondBuilder = class extends TimeBuilder { + }; + TimeMillisecondBuilder.prototype._setValue = setTimeMillisecond; + TimeMicrosecondBuilder = class extends TimeBuilder { + }; + TimeMicrosecondBuilder.prototype._setValue = setTimeMicrosecond; + TimeNanosecondBuilder = class extends TimeBuilder { + }; + TimeNanosecondBuilder.prototype._setValue = setTimeNanosecond; + } +}); + +// node_modules/apache-arrow/builder/union.mjs +var UnionBuilder, SparseUnionBuilder, DenseUnionBuilder; +var init_union2 = __esm({ + "node_modules/apache-arrow/builder/union.mjs"() { + init_schema2(); + init_buffer3(); + init_builder(); + init_type2(); + UnionBuilder = class extends Builder { + constructor(options) { + super(options); + this._typeIds = new DataBufferBuilder(Int8Array, 0, 1); + if (typeof options["valueToChildTypeId"] === "function") { + this._valueToChildTypeId = options["valueToChildTypeId"]; } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.comp2, - Parameters.prefix, - Parameters.marker, - Parameters.maxPageSize, - Parameters.restype2, - Parameters.include1, - Parameters.delimiter - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1 - ], - isXML: true, - serializer: xmlSerializer + } + get typeIdToChildIndex() { + return this.type.typeIdToChildIndex; + } + append(value, childTypeId) { + return this.set(this.length, value, childTypeId); + } + set(index2, value, childTypeId) { + if (childTypeId === void 0) { + childTypeId = this._valueToChildTypeId(this, value, index2); + } + this.setValue(index2, value, childTypeId); + return this; + } + setValue(index2, value, childTypeId) { + this._typeIds.set(index2, childTypeId); + const childIndex = this.type.typeIdToChildIndex[childTypeId]; + const child = this.children[childIndex]; + child === null || child === void 0 ? void 0 : child.set(index2, value); + this.length = Math.max(index2 + 1, this.length); + } + addChild(child, name = `${this.children.length}`) { + const childTypeId = this.children.push(child); + const { type: { children, mode, typeIds } } = this; + const fields = [...children, new Field2(name, child.type)]; + this.type = new Union_(mode, [...typeIds, childTypeId], fields); + return childTypeId; + } + /** @ignore */ + // @ts-ignore + _valueToChildTypeId(builder, value, offset) { + throw new Error(`Cannot map UnionBuilder value to child typeId. Pass the \`childTypeId\` as the second argument to unionBuilder.append(), or supply a \`valueToChildTypeId\` function as part of the UnionBuilder constructor options.`); + } }; - var getAccountInfoOperationSpec = { - path: "/{containerName}", - httpMethod: "GET", - responses: { - 200: { - headersMapper: Mappers.ContainerGetAccountInfoHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.ContainerGetAccountInfoExceptionHeaders + SparseUnionBuilder = class extends UnionBuilder { + }; + DenseUnionBuilder = class extends UnionBuilder { + constructor(options) { + super(options); + this._offsets = new DataBufferBuilder(Int32Array); + } + /** @ignore */ + setValue(index2, value, childTypeId) { + const id = this._typeIds.set(index2, childTypeId).buffer[index2]; + const child = this.getChildAt(this.type.typeIdToChildIndex[id]); + const denseIndex = this._offsets.set(index2, child.length).buffer[index2]; + child === null || child === void 0 ? void 0 : child.set(denseIndex, value); + this.length = Math.max(index2 + 1, this.length); + } + }; + } +}); + +// node_modules/apache-arrow/builder/utf8.mjs +var Utf8Builder; +var init_utf83 = __esm({ + "node_modules/apache-arrow/builder/utf8.mjs"() { + init_utf8(); + init_binary2(); + init_buffer3(); + init_builder(); + Utf8Builder = class extends VariableWidthBuilder { + constructor(opts) { + super(opts); + this._values = new BufferBuilder(Uint8Array); + } + get byteLength() { + let size = this._pendingLength + this.length * 4; + this._offsets && (size += this._offsets.byteLength); + this._values && (size += this._values.byteLength); + this._nulls && (size += this._nulls.byteLength); + return size; + } + setValue(index2, value) { + return super.setValue(index2, encodeUtf8(value)); + } + // @ts-ignore + _flushPending(pending, pendingLength) { + } + }; + Utf8Builder.prototype._flushPending = BinaryBuilder.prototype._flushPending; + } +}); + +// node_modules/apache-arrow/builder/largeutf8.mjs +var LargeUtf8Builder; +var init_largeutf8 = __esm({ + "node_modules/apache-arrow/builder/largeutf8.mjs"() { + init_utf8(); + init_buffer3(); + init_builder(); + init_largebinary(); + LargeUtf8Builder = class extends VariableWidthBuilder { + constructor(opts) { + super(opts); + this._values = new BufferBuilder(Uint8Array); + } + get byteLength() { + let size = this._pendingLength + this.length * 4; + this._offsets && (size += this._offsets.byteLength); + this._values && (size += this._values.byteLength); + this._nulls && (size += this._nulls.byteLength); + return size; + } + setValue(index2, value) { + return super.setValue(index2, encodeUtf8(value)); + } + // @ts-ignore + _flushPending(pending, pendingLength) { + } + }; + LargeUtf8Builder.prototype._flushPending = LargeBinaryBuilder.prototype._flushPending; + } +}); + +// node_modules/apache-arrow/builder/binaryview.mjs +var BinaryViewBuilder; +var init_binaryview = __esm({ + "node_modules/apache-arrow/builder/binaryview.mjs"() { + init_type2(); + init_builder(); + init_buffer3(); + init_buffer(); + init_data(); + BinaryViewBuilder = class extends Builder { + constructor(opts) { + super(opts); + this._variadicBuffers = []; + this._currentBuffer = null; + this._currentBufferIndex = 0; + this._currentBufferOffset = 0; + this._bufferSize = 32 * 1024 * 1024; + this._views = new BufferBuilder(Uint8Array); + } + get byteLength() { + let size = 0; + this._views && (size += this._views.byteLength); + this._nulls && (size += this._nulls.byteLength); + for (const buffer of this._variadicBuffers) { + size += buffer.byteLength; + } + this._currentBuffer && (size += this._currentBuffer.byteLength); + return size; + } + setValue(index2, value) { + return this.writeBinaryValue(index2, this.encodeValue(value)); + } + writeBinaryValue(index2, data) { + const length = data.length; + const bytesNeeded = (index2 + 1) * BinaryView2.ELEMENT_WIDTH; + const currentBytes = this._views.length; + if (bytesNeeded > currentBytes) { + this._views.reserve(bytesNeeded - currentBytes); + } + const viewBuffer = this._views.buffer; + const viewOffset = index2 * BinaryView2.ELEMENT_WIDTH; + const view = new DataView(viewBuffer.buffer, viewBuffer.byteOffset + viewOffset, BinaryView2.ELEMENT_WIDTH); + view.setInt32(BinaryView2.LENGTH_OFFSET, length, true); + if (length <= BinaryView2.INLINE_CAPACITY) { + viewBuffer.set(data, viewOffset + BinaryView2.INLINE_OFFSET); + for (let i = length; i < BinaryView2.INLINE_CAPACITY; i++) { + viewBuffer[viewOffset + BinaryView2.INLINE_OFFSET + i] = 0; + } + } else { + const prefix = new DataView(data.buffer, data.byteOffset, Math.min(4, length)); + view.setUint32(BinaryView2.INLINE_OFFSET, prefix.getUint32(0, true), true); + if (!this._currentBuffer || this._currentBufferOffset + length > this._bufferSize) { + if (this._currentBuffer) { + this._variadicBuffers.push(this._currentBuffer.buffer.slice(0, this._currentBufferOffset)); + } + this._currentBuffer = new BufferBuilder(Uint8Array); + this._currentBufferIndex = this._variadicBuffers.length; + this._currentBufferOffset = 0; + } + const bufferData = this._currentBuffer.reserve(length).buffer; + bufferData.set(data, this._currentBufferOffset); + view.setInt32(BinaryView2.BUFFER_INDEX_OFFSET, this._currentBufferIndex, true); + view.setInt32(BinaryView2.BUFFER_OFFSET_OFFSET, this._currentBufferOffset, true); + this._currentBufferOffset += length; } - }, - queryParameters: [ - Parameters.comp, - Parameters.timeoutInSeconds, - Parameters.restype1 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1 - ], - isXML: true, - serializer: xmlSerializer + return this; + } + encodeValue(value) { + return toUint8Array(value); + } + setValid(index2, isValid) { + const bytesNeeded = (index2 + 1) * BinaryView2.ELEMENT_WIDTH; + const currentBytes = this._views.length; + if (bytesNeeded > currentBytes) { + this._views.reserve(bytesNeeded - currentBytes); + } + const result = super.setValid(index2, isValid); + if (!result) { + const viewBuffer = this._views.buffer; + const viewOffset = index2 * BinaryView2.ELEMENT_WIDTH; + for (let i = 0; i < BinaryView2.ELEMENT_WIDTH; i++) { + viewBuffer[viewOffset + i] = 0; + } + } + return result; + } + clear() { + this._variadicBuffers = []; + this._currentBuffer = null; + this._currentBufferIndex = 0; + this._currentBufferOffset = 0; + this._views.clear(); + return super.clear(); + } + flush() { + const { type, length, nullCount, _views, _nulls } = this; + if (this._currentBuffer && this._currentBufferOffset > 0) { + this._variadicBuffers.push(this._currentBuffer.buffer.slice(0, this._currentBufferOffset)); + this._currentBuffer = null; + this._currentBufferOffset = 0; + } + const views = _views.flush(length * BinaryView2.ELEMENT_WIDTH); + const nullBitmap = nullCount > 0 ? _nulls.flush(length) : void 0; + const variadicBuffers = this._variadicBuffers.slice(); + this._variadicBuffers = []; + this._currentBufferIndex = 0; + this.clear(); + const props = { + type, + length, + nullCount, + nullBitmap, + ["views"]: views, + ["variadicBuffers"]: variadicBuffers + }; + return makeData(props); + } + finish() { + this.finished = true; + return this; + } }; } }); -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/blob.js -var require_blob = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/blob.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BlobImpl = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var coreClient = tslib_1.__importStar(require_commonjs8()); - var Mappers = tslib_1.__importStar(require_mappers()); - var Parameters = tslib_1.__importStar(require_parameters()); - var BlobImpl = class { - client; - /** - * Initialize a new instance of the class Blob class. - * @param client Reference to the service client - */ - constructor(client) { - this.client = client; +// node_modules/apache-arrow/builder/utf8view.mjs +var Utf8ViewBuilder; +var init_utf8view = __esm({ + "node_modules/apache-arrow/builder/utf8view.mjs"() { + init_binaryview(); + init_utf8(); + Utf8ViewBuilder = class extends BinaryViewBuilder { + constructor(opts) { + super(opts); + } + setValue(index2, value) { + return this.writeBinaryValue(index2, encodeUtf8(value)); + } + }; + } +}); + +// node_modules/apache-arrow/visitor/builderctor.mjs +var GetBuilderCtor, instance6; +var init_builderctor = __esm({ + "node_modules/apache-arrow/visitor/builderctor.mjs"() { + init_visitor(); + init_binary2(); + init_largebinary(); + init_bool2(); + init_date2(); + init_decimal2(); + init_dictionary(); + init_fixedsizebinary(); + init_fixedsizelist(); + init_float(); + init_interval3(); + init_duration2(); + init_int3(); + init_list2(); + init_largelist(); + init_map3(); + init_null2(); + init_struct3(); + init_timestamp2(); + init_time2(); + init_union2(); + init_utf83(); + init_largeutf8(); + init_binaryview(); + init_utf8view(); + GetBuilderCtor = class extends Visitor { + visitNull() { + return NullBuilder; + } + visitBool() { + return BoolBuilder; + } + visitInt() { + return IntBuilder; + } + visitInt8() { + return Int8Builder; + } + visitInt16() { + return Int16Builder; + } + visitInt32() { + return Int32Builder; + } + visitInt64() { + return Int64Builder; + } + visitUint8() { + return Uint8Builder; + } + visitUint16() { + return Uint16Builder; + } + visitUint32() { + return Uint32Builder; + } + visitUint64() { + return Uint64Builder; + } + visitFloat() { + return FloatBuilder; + } + visitFloat16() { + return Float16Builder; + } + visitFloat32() { + return Float32Builder; + } + visitFloat64() { + return Float64Builder; + } + visitUtf8() { + return Utf8Builder; + } + visitLargeUtf8() { + return LargeUtf8Builder; + } + visitBinary() { + return BinaryBuilder; + } + visitLargeBinary() { + return LargeBinaryBuilder; + } + visitFixedSizeBinary() { + return FixedSizeBinaryBuilder; + } + visitDate() { + return DateBuilder; + } + visitDateDay() { + return DateDayBuilder; } - /** - * The Download operation reads or downloads a blob from the system, including its metadata and - * properties. You can also call Download to read a snapshot. - * @param options The options parameters. - */ - download(options) { - return this.client.sendOperationRequest({ options }, downloadOperationSpec); + visitDateMillisecond() { + return DateMillisecondBuilder; } - /** - * The Get Properties operation returns all user-defined metadata, standard HTTP properties, and system - * properties for the blob. It does not return the content of the blob. - * @param options The options parameters. - */ - getProperties(options) { - return this.client.sendOperationRequest({ options }, getPropertiesOperationSpec); + visitTimestamp() { + return TimestampBuilder; } - /** - * If the storage account's soft delete feature is disabled then, when a blob is deleted, it is - * permanently removed from the storage account. If the storage account's soft delete feature is - * enabled, then, when a blob is deleted, it is marked for deletion and becomes inaccessible - * immediately. However, the blob service retains the blob or snapshot for the number of days specified - * by the DeleteRetentionPolicy section of [Storage service properties] - * (Set-Blob-Service-Properties.md). After the specified number of days has passed, the blob's data is - * permanently removed from the storage account. Note that you continue to be charged for the - * soft-deleted blob's storage until it is permanently removed. Use the List Blobs API and specify the - * "include=deleted" query parameter to discover which blobs and snapshots have been soft deleted. You - * can then use the Undelete Blob API to restore a soft-deleted blob. All other operations on a - * soft-deleted blob or snapshot causes the service to return an HTTP status code of 404 - * (ResourceNotFound). - * @param options The options parameters. - */ - delete(options) { - return this.client.sendOperationRequest({ options }, deleteOperationSpec); + visitTimestampSecond() { + return TimestampSecondBuilder; } - /** - * Undelete a blob that was previously soft deleted - * @param options The options parameters. - */ - undelete(options) { - return this.client.sendOperationRequest({ options }, undeleteOperationSpec); + visitTimestampMillisecond() { + return TimestampMillisecondBuilder; } - /** - * Sets the time a blob will expire and be deleted. - * @param expiryOptions Required. Indicates mode of the expiry time - * @param options The options parameters. - */ - setExpiry(expiryOptions, options) { - return this.client.sendOperationRequest({ expiryOptions, options }, setExpiryOperationSpec); + visitTimestampMicrosecond() { + return TimestampMicrosecondBuilder; } - /** - * The Set HTTP Headers operation sets system properties on the blob - * @param options The options parameters. - */ - setHttpHeaders(options) { - return this.client.sendOperationRequest({ options }, setHttpHeadersOperationSpec); + visitTimestampNanosecond() { + return TimestampNanosecondBuilder; } - /** - * The Set Immutability Policy operation sets the immutability policy on the blob - * @param options The options parameters. - */ - setImmutabilityPolicy(options) { - return this.client.sendOperationRequest({ options }, setImmutabilityPolicyOperationSpec); + visitTime() { + return TimeBuilder; } - /** - * The Delete Immutability Policy operation deletes the immutability policy on the blob - * @param options The options parameters. - */ - deleteImmutabilityPolicy(options) { - return this.client.sendOperationRequest({ options }, deleteImmutabilityPolicyOperationSpec); + visitTimeSecond() { + return TimeSecondBuilder; } - /** - * The Set Legal Hold operation sets a legal hold on the blob. - * @param legalHold Specified if a legal hold should be set on the blob. - * @param options The options parameters. - */ - setLegalHold(legalHold, options) { - return this.client.sendOperationRequest({ legalHold, options }, setLegalHoldOperationSpec); + visitTimeMillisecond() { + return TimeMillisecondBuilder; } - /** - * The Set Blob Metadata operation sets user-defined metadata for the specified blob as one or more - * name-value pairs - * @param options The options parameters. - */ - setMetadata(options) { - return this.client.sendOperationRequest({ options }, setMetadataOperationSpec); + visitTimeMicrosecond() { + return TimeMicrosecondBuilder; } - /** - * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete - * operations - * @param options The options parameters. - */ - acquireLease(options) { - return this.client.sendOperationRequest({ options }, acquireLeaseOperationSpec); + visitTimeNanosecond() { + return TimeNanosecondBuilder; } - /** - * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete - * operations - * @param leaseId Specifies the current lease ID on the resource. - * @param options The options parameters. - */ - releaseLease(leaseId, options) { - return this.client.sendOperationRequest({ leaseId, options }, releaseLeaseOperationSpec); + visitDecimal() { + return DecimalBuilder; } - /** - * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete - * operations - * @param leaseId Specifies the current lease ID on the resource. - * @param options The options parameters. - */ - renewLease(leaseId, options) { - return this.client.sendOperationRequest({ leaseId, options }, renewLeaseOperationSpec); + visitList() { + return ListBuilder; } - /** - * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete - * operations - * @param leaseId Specifies the current lease ID on the resource. - * @param proposedLeaseId Proposed lease ID, in a GUID string format. The Blob service returns 400 - * (Invalid request) if the proposed lease ID is not in the correct format. See Guid Constructor - * (String) for a list of valid GUID string formats. - * @param options The options parameters. - */ - changeLease(leaseId, proposedLeaseId, options) { - return this.client.sendOperationRequest({ leaseId, proposedLeaseId, options }, changeLeaseOperationSpec); + visitLargeList() { + return LargeListBuilder; } - /** - * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete - * operations - * @param options The options parameters. - */ - breakLease(options) { - return this.client.sendOperationRequest({ options }, breakLeaseOperationSpec); + visitStruct() { + return StructBuilder; + } + visitUnion() { + return UnionBuilder; + } + visitDenseUnion() { + return DenseUnionBuilder; + } + visitSparseUnion() { + return SparseUnionBuilder; + } + visitDictionary() { + return DictionaryBuilder; + } + visitInterval() { + return IntervalBuilder; + } + visitIntervalDayTime() { + return IntervalDayTimeBuilder; + } + visitIntervalYearMonth() { + return IntervalYearMonthBuilder; + } + visitIntervalMonthDayNano() { + return IntervalMonthDayNanoBuilder; + } + visitDuration() { + return DurationBuilder; + } + visitDurationSecond() { + return DurationSecondBuilder; + } + visitDurationMillisecond() { + return DurationMillisecondBuilder; + } + visitDurationMicrosecond() { + return DurationMicrosecondBuilder; + } + visitDurationNanosecond() { + return DurationNanosecondBuilder; + } + visitFixedSizeList() { + return FixedSizeListBuilder; + } + visitMap() { + return MapBuilder; + } + visitBinaryView() { + return BinaryViewBuilder; + } + visitUtf8View() { + return Utf8ViewBuilder; + } + }; + instance6 = new GetBuilderCtor(); + } +}); + +// node_modules/apache-arrow/visitor/typecomparator.mjs +function compareConstructor(type, other) { + return other instanceof type.constructor; +} +function compareAny(type, other) { + return type === other || compareConstructor(type, other); +} +function compareInt(type, other) { + return type === other || compareConstructor(type, other) && type.bitWidth === other.bitWidth && type.isSigned === other.isSigned; +} +function compareFloat(type, other) { + return type === other || compareConstructor(type, other) && type.precision === other.precision; +} +function compareFixedSizeBinary(type, other) { + return type === other || compareConstructor(type, other) && type.byteWidth === other.byteWidth; +} +function compareDate(type, other) { + return type === other || compareConstructor(type, other) && type.unit === other.unit; +} +function compareTimestamp(type, other) { + return type === other || compareConstructor(type, other) && type.unit === other.unit && type.timezone === other.timezone; +} +function compareTime(type, other) { + return type === other || compareConstructor(type, other) && type.unit === other.unit && type.bitWidth === other.bitWidth; +} +function compareList(type, other) { + return type === other || compareConstructor(type, other) && type.children.length === other.children.length && instance7.compareManyFields(type.children, other.children); +} +function compareStruct(type, other) { + return type === other || compareConstructor(type, other) && type.children.length === other.children.length && instance7.compareManyFields(type.children, other.children); +} +function compareUnion(type, other) { + return type === other || compareConstructor(type, other) && type.mode === other.mode && type.typeIds.every((x, i) => x === other.typeIds[i]) && instance7.compareManyFields(type.children, other.children); +} +function compareDictionary(type, other) { + return type === other || compareConstructor(type, other) && type.id === other.id && type.isOrdered === other.isOrdered && instance7.visit(type.indices, other.indices) && instance7.visit(type.dictionary, other.dictionary); +} +function compareInterval(type, other) { + return type === other || compareConstructor(type, other) && type.unit === other.unit; +} +function compareDuration(type, other) { + return type === other || compareConstructor(type, other) && type.unit === other.unit; +} +function compareFixedSizeList(type, other) { + return type === other || compareConstructor(type, other) && type.listSize === other.listSize && type.children.length === other.children.length && instance7.compareManyFields(type.children, other.children); +} +function compareMap(type, other) { + return type === other || compareConstructor(type, other) && type.keysSorted === other.keysSorted && type.children.length === other.children.length && instance7.compareManyFields(type.children, other.children); +} +function compareSchemas(schema, other) { + return instance7.compareSchemas(schema, other); +} +function compareFields(field, other) { + return instance7.compareFields(field, other); +} +function compareTypes(type, other) { + return instance7.visit(type, other); +} +var TypeComparator, instance7; +var init_typecomparator = __esm({ + "node_modules/apache-arrow/visitor/typecomparator.mjs"() { + init_visitor(); + TypeComparator = class extends Visitor { + compareSchemas(schema, other) { + return schema === other || other instanceof schema.constructor && this.compareManyFields(schema.fields, other.fields); + } + compareManyFields(fields, others) { + return fields === others || Array.isArray(fields) && Array.isArray(others) && fields.length === others.length && fields.every((f, i) => this.compareFields(f, others[i])); + } + compareFields(field, other) { + return field === other || other instanceof field.constructor && field.name === other.name && field.nullable === other.nullable && this.visit(field.type, other.type); + } + }; + TypeComparator.prototype.visitNull = compareAny; + TypeComparator.prototype.visitBool = compareAny; + TypeComparator.prototype.visitInt = compareInt; + TypeComparator.prototype.visitInt8 = compareInt; + TypeComparator.prototype.visitInt16 = compareInt; + TypeComparator.prototype.visitInt32 = compareInt; + TypeComparator.prototype.visitInt64 = compareInt; + TypeComparator.prototype.visitUint8 = compareInt; + TypeComparator.prototype.visitUint16 = compareInt; + TypeComparator.prototype.visitUint32 = compareInt; + TypeComparator.prototype.visitUint64 = compareInt; + TypeComparator.prototype.visitFloat = compareFloat; + TypeComparator.prototype.visitFloat16 = compareFloat; + TypeComparator.prototype.visitFloat32 = compareFloat; + TypeComparator.prototype.visitFloat64 = compareFloat; + TypeComparator.prototype.visitUtf8 = compareAny; + TypeComparator.prototype.visitLargeUtf8 = compareAny; + TypeComparator.prototype.visitUtf8View = compareAny; + TypeComparator.prototype.visitBinary = compareAny; + TypeComparator.prototype.visitLargeBinary = compareAny; + TypeComparator.prototype.visitBinaryView = compareAny; + TypeComparator.prototype.visitFixedSizeBinary = compareFixedSizeBinary; + TypeComparator.prototype.visitDate = compareDate; + TypeComparator.prototype.visitDateDay = compareDate; + TypeComparator.prototype.visitDateMillisecond = compareDate; + TypeComparator.prototype.visitTimestamp = compareTimestamp; + TypeComparator.prototype.visitTimestampSecond = compareTimestamp; + TypeComparator.prototype.visitTimestampMillisecond = compareTimestamp; + TypeComparator.prototype.visitTimestampMicrosecond = compareTimestamp; + TypeComparator.prototype.visitTimestampNanosecond = compareTimestamp; + TypeComparator.prototype.visitTime = compareTime; + TypeComparator.prototype.visitTimeSecond = compareTime; + TypeComparator.prototype.visitTimeMillisecond = compareTime; + TypeComparator.prototype.visitTimeMicrosecond = compareTime; + TypeComparator.prototype.visitTimeNanosecond = compareTime; + TypeComparator.prototype.visitDecimal = compareAny; + TypeComparator.prototype.visitList = compareList; + TypeComparator.prototype.visitLargeList = compareList; + TypeComparator.prototype.visitStruct = compareStruct; + TypeComparator.prototype.visitUnion = compareUnion; + TypeComparator.prototype.visitDenseUnion = compareUnion; + TypeComparator.prototype.visitSparseUnion = compareUnion; + TypeComparator.prototype.visitDictionary = compareDictionary; + TypeComparator.prototype.visitInterval = compareInterval; + TypeComparator.prototype.visitIntervalDayTime = compareInterval; + TypeComparator.prototype.visitIntervalYearMonth = compareInterval; + TypeComparator.prototype.visitIntervalMonthDayNano = compareInterval; + TypeComparator.prototype.visitDuration = compareDuration; + TypeComparator.prototype.visitDurationSecond = compareDuration; + TypeComparator.prototype.visitDurationMillisecond = compareDuration; + TypeComparator.prototype.visitDurationMicrosecond = compareDuration; + TypeComparator.prototype.visitDurationNanosecond = compareDuration; + TypeComparator.prototype.visitFixedSizeList = compareFixedSizeList; + TypeComparator.prototype.visitMap = compareMap; + instance7 = new TypeComparator(); + } +}); + +// node_modules/apache-arrow/factories.mjs +function makeBuilder(options) { + const type = options.type; + const builder = new (instance6.getVisitFn(type)())(options); + if (type.children && type.children.length > 0) { + const children = options["children"] || []; + const defaultOptions = { "nullValues": options["nullValues"] }; + const getChildOptions = Array.isArray(children) ? ((_2, i) => children[i] || defaultOptions) : (({ name }) => children[name] || defaultOptions); + for (const [index2, field] of type.children.entries()) { + const { type: type2 } = field; + const opts = getChildOptions(field, index2); + builder.children.push(makeBuilder(Object.assign(Object.assign({}, opts), { type: type2 }))); + } + } + return builder; +} +function vectorFromArray(init2, type) { + if (init2 instanceof Data || init2 instanceof Vector || init2.type instanceof DataType || ArrayBuffer.isView(init2)) { + return makeVector(init2); + } + const options = { type: type !== null && type !== void 0 ? type : inferType(init2), nullValues: [null] }; + const chunks = [...builderThroughIterable(options)(init2)]; + const vector = chunks.length === 1 ? chunks[0] : chunks.reduce((a, b) => a.concat(b)); + if (DataType.isDictionary(vector.type)) { + return vector.memoize(); + } + return vector; +} +function tableFromJSON(array2) { + const vector = vectorFromArray(array2); + const batch = new RecordBatch3(new Schema4(vector.type.children), vector.data[0]); + return new Table(batch); +} +function inferType(value) { + if (value.length === 0) { + return new Null2(); + } + let nullsCount = 0; + let arraysCount = 0; + let objectsCount = 0; + let numbersCount = 0; + let stringsCount = 0; + let bigintsCount = 0; + let booleansCount = 0; + let datesCount = 0; + for (const val of value) { + if (val == null) { + ++nullsCount; + continue; + } + switch (typeof val) { + case "bigint": + ++bigintsCount; + continue; + case "boolean": + ++booleansCount; + continue; + case "number": + ++numbersCount; + continue; + case "string": + ++stringsCount; + continue; + case "object": + if (Array.isArray(val)) { + ++arraysCount; + } else if (Object.prototype.toString.call(val) === "[object Date]") { + ++datesCount; + } else { + ++objectsCount; + } + continue; + } + throw new TypeError("Unable to infer Vector type from input values, explicit type declaration expected."); + } + if (numbersCount + nullsCount === value.length) { + return new Float64(); + } else if (stringsCount + nullsCount === value.length) { + return new Dictionary(new Utf82(), new Int32()); + } else if (bigintsCount + nullsCount === value.length) { + return new Int64(); + } else if (booleansCount + nullsCount === value.length) { + return new Bool2(); + } else if (datesCount + nullsCount === value.length) { + return new TimestampMillisecond(); + } else if (arraysCount + nullsCount === value.length) { + const array2 = value; + const childType = inferType(array2[array2.findIndex((ary) => ary != null)]); + if (array2.every((ary) => ary == null || compareTypes(childType, inferType(ary)))) { + return new List2(new Field2("", childType, true)); + } + } else if (objectsCount + nullsCount === value.length) { + const fields = /* @__PURE__ */ new Map(); + for (const row of value) { + for (const key of Object.keys(row)) { + if (!fields.has(key) && row[key] != null) { + fields.set(key, new Field2(key, inferType([row[key]]), true)); + } + } + } + return new Struct([...fields.values()]); + } + throw new TypeError("Unable to infer Vector type from input values, explicit type declaration expected."); +} +function builderThroughIterable(options) { + const { ["queueingStrategy"]: queueingStrategy = "count" } = options; + const { ["highWaterMark"]: highWaterMark = queueingStrategy !== "bytes" ? Number.POSITIVE_INFINITY : Math.pow(2, 14) } = options; + const sizeProperty = queueingStrategy !== "bytes" ? "length" : "byteLength"; + return function* (source) { + let numChunks = 0; + const builder = makeBuilder(options); + for (const value of source) { + if (builder.append(value)[sizeProperty] >= highWaterMark) { + ++numChunks && (yield builder.toVector()); + } + } + if (builder.finish().length > 0 || numChunks === 0) { + yield builder.toVector(); + } + }; +} +function builderThroughAsyncIterable(options) { + const { ["queueingStrategy"]: queueingStrategy = "count" } = options; + const { ["highWaterMark"]: highWaterMark = queueingStrategy !== "bytes" ? Number.POSITIVE_INFINITY : Math.pow(2, 14) } = options; + const sizeProperty = queueingStrategy !== "bytes" ? "length" : "byteLength"; + return function(source) { + return __asyncGenerator(this, arguments, function* () { + var _a6, e_1, _b2, _c2; + let numChunks = 0; + const builder = makeBuilder(options); + try { + for (var _d2 = true, source_1 = __asyncValues(source), source_1_1; source_1_1 = yield __await(source_1.next()), _a6 = source_1_1.done, !_a6; _d2 = true) { + _c2 = source_1_1.value; + _d2 = false; + const value = _c2; + if (builder.append(value)[sizeProperty] >= highWaterMark) { + ++numChunks && (yield yield __await(builder.toVector())); + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d2 && !_a6 && (_b2 = source_1.return)) yield __await(_b2.call(source_1)); + } finally { + if (e_1) throw e_1.error; + } + } + if (builder.finish().length > 0 || numChunks === 0) { + yield yield __await(builder.toVector()); + } + }); + }; +} +var init_factories = __esm({ + "node_modules/apache-arrow/factories.mjs"() { + init_tslib_es6(); + init_schema2(); + init_type2(); + init_data(); + init_vector2(); + init_builderctor(); + init_table(); + init_recordbatch2(); + init_typecomparator(); + } +}); + +// node_modules/apache-arrow/util/recordbatch.mjs +function distributeVectorsIntoRecordBatches(schema, vecs) { + return uniformlyDistributeChunksAcrossRecordBatches(schema, vecs.map((v) => v.data.concat())); +} +function uniformlyDistributeChunksAcrossRecordBatches(schema, cols) { + const fields = [...schema.fields]; + const batches = []; + const memo = { numBatches: cols.reduce((n, c) => Math.max(n, c.length), 0) }; + let numBatches = 0, batchLength = 0; + let i = -1; + const numColumns = cols.length; + let child, children = []; + while (memo.numBatches-- > 0) { + for (batchLength = Number.POSITIVE_INFINITY, i = -1; ++i < numColumns; ) { + children[i] = child = cols[i].shift(); + batchLength = Math.min(batchLength, child ? child.length : batchLength); + } + if (Number.isFinite(batchLength)) { + children = distributeChildren(fields, batchLength, children, cols, memo); + if (batchLength > 0) { + batches[numBatches++] = makeData({ + type: new Struct(fields), + length: batchLength, + nullCount: 0, + children: children.slice() + }); + } + } + } + return [ + schema = schema.assign(fields), + batches.map((data) => new RecordBatch3(schema, data)) + ]; +} +function distributeChildren(fields, batchLength, children, columns, memo) { + var _a6; + const nullBitmapSize = (batchLength + 63 & ~63) >> 3; + for (let i = -1, n = columns.length; ++i < n; ) { + const child = children[i]; + const length = child === null || child === void 0 ? void 0 : child.length; + if (length >= batchLength) { + if (length === batchLength) { + children[i] = child; + } else { + children[i] = child.slice(0, batchLength); + memo.numBatches = Math.max(memo.numBatches, columns[i].unshift(child.slice(batchLength, length - batchLength))); + } + } else { + const field = fields[i]; + fields[i] = field.clone({ nullable: true }); + children[i] = (_a6 = child === null || child === void 0 ? void 0 : child._changeLengthAndBackfillNullBitmap(batchLength)) !== null && _a6 !== void 0 ? _a6 : makeData({ + type: field.type, + length: batchLength, + nullCount: batchLength, + nullBitmap: new Uint8Array(nullBitmapSize) + }); + } + } + return children; +} +var init_recordbatch = __esm({ + "node_modules/apache-arrow/util/recordbatch.mjs"() { + init_data(); + init_type2(); + init_recordbatch2(); + } +}); + +// node_modules/apache-arrow/table.mjs +function makeTable(input) { + const vecs = {}; + const inputs = Object.entries(input); + for (const [key, col] of inputs) { + vecs[key] = makeVector(col); + } + return new Table(vecs); +} +function tableFromArrays(input) { + const vecs = {}; + const inputs = Object.entries(input); + for (const [key, col] of inputs) { + vecs[key] = vectorFromArray(col); + } + return new Table(vecs); +} +var _a3, kTableSymbol, Table; +var init_table = __esm({ + "node_modules/apache-arrow/table.mjs"() { + init_enum(); + init_data(); + init_factories(); + init_vector2(); + init_schema2(); + init_type2(); + init_typecomparator(); + init_recordbatch(); + init_chunk(); + init_get(); + init_set(); + init_indexof(); + init_iterator(); + init_vector(); + init_recordbatch2(); + kTableSymbol = /* @__PURE__ */ Symbol.for("apache-arrow/Table"); + Table = class _Table { + /** + * Check if an object is an instance of Table. + * This works across different instances of the Arrow library. + */ + /** @nocollapse */ + static isTable(x) { + return (x === null || x === void 0 ? void 0 : x[kTableSymbol]) === true; + } + constructor(...args) { + var _b2, _c2; + if (args.length === 0) { + this.batches = []; + this.schema = new Schema4([]); + this._offsets = [0]; + return this; + } + let schema; + let offsets; + if (args[0] instanceof Schema4) { + schema = args.shift(); + } + if (args.at(-1) instanceof Uint32Array) { + offsets = args.pop(); + } + const unwrap = (x) => { + if (x) { + if (x instanceof RecordBatch3) { + return [x]; + } else if (x instanceof _Table) { + return x.batches; + } else if (x instanceof Data) { + if (x.type instanceof Struct) { + return [new RecordBatch3(new Schema4(x.type.children), x)]; + } + } else if (Array.isArray(x)) { + return x.flatMap((v) => unwrap(v)); + } else if (typeof x[Symbol.iterator] === "function") { + return [...x].flatMap((v) => unwrap(v)); + } else if (typeof x === "object") { + const keys = Object.keys(x); + const vecs = keys.map((k) => new Vector([x[k]])); + const batchSchema = schema !== null && schema !== void 0 ? schema : new Schema4(keys.map((k, i) => new Field2(String(k), vecs[i].type, vecs[i].nullable))); + const [, batches2] = distributeVectorsIntoRecordBatches(batchSchema, vecs); + return batches2.length === 0 ? [new RecordBatch3(x)] : batches2; + } + } + return []; + }; + const batches = args.flatMap((v) => unwrap(v)); + schema = (_c2 = schema !== null && schema !== void 0 ? schema : (_b2 = batches[0]) === null || _b2 === void 0 ? void 0 : _b2.schema) !== null && _c2 !== void 0 ? _c2 : new Schema4([]); + if (!(schema instanceof Schema4)) { + throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair."); + } + for (const batch of batches) { + if (!(batch instanceof RecordBatch3)) { + throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair."); + } + if (!compareSchemas(schema, batch.schema)) { + throw new TypeError("Table and inner RecordBatch schemas must be equivalent."); + } + } + this.schema = schema; + this.batches = batches; + this._offsets = offsets !== null && offsets !== void 0 ? offsets : computeChunkOffsets(this.data); } /** - * The Create Snapshot operation creates a read-only snapshot of a blob - * @param options The options parameters. + * The contiguous {@link RecordBatch `RecordBatch`} chunks of the Table rows. */ - createSnapshot(options) { - return this.client.sendOperationRequest({ options }, createSnapshotOperationSpec); + get data() { + return this.batches.map(({ data }) => data); } /** - * The Start Copy From URL operation copies a blob or an internet resource to a new blob. - * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to - * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would - * appear in a request URI. The source blob must either be public or must be authenticated via a shared - * access signature. - * @param options The options parameters. + * The number of columns in this Table. */ - startCopyFromURL(copySource, options) { - return this.client.sendOperationRequest({ copySource, options }, startCopyFromURLOperationSpec); + get numCols() { + return this.schema.fields.length; } /** - * The Copy From URL operation copies a blob or an internet resource to a new blob. It will not return - * a response until the copy is complete. - * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to - * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would - * appear in a request URI. The source blob must either be public or must be authenticated via a shared - * access signature. - * @param options The options parameters. + * The number of rows in this Table. */ - copyFromURL(copySource, options) { - return this.client.sendOperationRequest({ copySource, options }, copyFromURLOperationSpec); + get numRows() { + return this.data.reduce((numRows, data) => numRows + data.length, 0); } /** - * The Abort Copy From URL operation aborts a pending Copy From URL operation, and leaves a destination - * blob with zero length and full metadata. - * @param copyId The copy identifier provided in the x-ms-copy-id header of the original Copy Blob - * operation. - * @param options The options parameters. + * The number of null rows in this Table. */ - abortCopyFromURL(copyId, options) { - return this.client.sendOperationRequest({ copyId, options }, abortCopyFromURLOperationSpec); + get nullCount() { + if (this._nullCount === -1) { + this._nullCount = computeChunkNullCounts(this.data); + } + return this._nullCount; } /** - * The Set Tier operation sets the tier on a blob. The operation is allowed on a page blob in a premium - * storage account and on a block blob in a blob storage account (locally redundant storage only). A - * premium page blob's tier determines the allowed size, IOPS, and bandwidth of the blob. A block - * blob's tier determines Hot/Cool/Archive storage type. This operation does not update the blob's - * ETag. - * @param tier Indicates the tier to be set on the blob. - * @param options The options parameters. + * Check whether an element is null. + * + * @param index The index at which to read the validity bitmap. */ - setTier(tier, options) { - return this.client.sendOperationRequest({ tier, options }, setTierOperationSpec); + // @ts-ignore + isValid(index2) { + return false; } /** - * Returns the sku name and account kind - * @param options The options parameters. + * Get an element value by position. + * + * @param index The index of the element to read. */ - getAccountInfo(options) { - return this.client.sendOperationRequest({ options }, getAccountInfoOperationSpec); + // @ts-ignore + get(index2) { + return null; } /** - * The Query operation enables users to select/project on blob data by providing simple query - * expressions. - * @param options The options parameters. - */ - query(options) { - return this.client.sendOperationRequest({ options }, queryOperationSpec); + * Get an element value by position. + * @param index The index of the element to read. A negative index will count back from the last element. + */ + // @ts-ignore + at(index2) { + return this.get(wrapIndex(index2, this.numRows)); } /** - * The Get Tags operation enables users to get the tags associated with a blob. - * @param options The options parameters. + * Set an element value by position. + * + * @param index The index of the element to write. + * @param value The value to set. */ - getTags(options) { - return this.client.sendOperationRequest({ options }, getTagsOperationSpec); + // @ts-ignore + set(index2, value) { + return; } /** - * The Set Tags operation enables users to set tags on a blob. - * @param options The options parameters. + * Retrieve the index of the first occurrence of a value in an Vector. + * + * @param element The value to locate in the Vector. + * @param offset The index at which to begin the search. If offset is omitted, the search starts at index 0. */ - setTags(options) { - return this.client.sendOperationRequest({ options }, setTagsOperationSpec); - } - }; - exports2.BlobImpl = BlobImpl; - var xmlSerializer = coreClient.createSerializer( - Mappers, - /* isXml */ - true - ); - var downloadOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: { - type: { name: "Stream" }, - serializedName: "parsedResponse" - }, - headersMapper: Mappers.BlobDownloadHeaders - }, - 206: { - bodyMapper: { - type: { name: "Stream" }, - serializedName: "parsedResponse" - }, - headersMapper: Mappers.BlobDownloadHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobDownloadExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.snapshot, - Parameters.versionId - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.range, - Parameters.rangeGetContentMD5, - Parameters.rangeGetContentCRC64, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags - ], - isXML: true, - serializer: xmlSerializer - }; - var getPropertiesOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "HEAD", - responses: { - 200: { - headersMapper: Mappers.BlobGetPropertiesHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobGetPropertiesExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.snapshot, - Parameters.versionId - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags - ], - isXML: true, - serializer: xmlSerializer - }; - var deleteOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "DELETE", - responses: { - 202: { - headersMapper: Mappers.BlobDeleteHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobDeleteExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.snapshot, - Parameters.versionId, - Parameters.blobDeleteType - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.deleteSnapshots - ], - isXML: true, - serializer: xmlSerializer - }; - var undeleteOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.BlobUndeleteHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobUndeleteExceptionHeaders - } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp8], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1 - ], - isXML: true, - serializer: xmlSerializer - }; - var setExpiryOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.BlobSetExpiryHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobSetExpiryExceptionHeaders - } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp11], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.expiryOptions, - Parameters.expiresOn - ], - isXML: true, - serializer: xmlSerializer - }; - var setHttpHeadersOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.BlobSetHttpHeadersHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobSetHttpHeadersExceptionHeaders - } - }, - queryParameters: [Parameters.comp, Parameters.timeoutInSeconds], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.blobCacheControl, - Parameters.blobContentType, - Parameters.blobContentMD5, - Parameters.blobContentEncoding, - Parameters.blobContentLanguage, - Parameters.blobContentDisposition - ], - isXML: true, - serializer: xmlSerializer - }; - var setImmutabilityPolicyOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.BlobSetImmutabilityPolicyHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobSetImmutabilityPolicyExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.snapshot, - Parameters.versionId, - Parameters.comp12 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.ifUnmodifiedSince, - Parameters.immutabilityPolicyExpiry, - Parameters.immutabilityPolicyMode - ], - isXML: true, - serializer: xmlSerializer - }; - var deleteImmutabilityPolicyOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "DELETE", - responses: { - 200: { - headersMapper: Mappers.BlobDeleteImmutabilityPolicyHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobDeleteImmutabilityPolicyExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.snapshot, - Parameters.versionId, - Parameters.comp12 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1 - ], - isXML: true, - serializer: xmlSerializer - }; - var setLegalHoldOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.BlobSetLegalHoldHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobSetLegalHoldExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.snapshot, - Parameters.versionId, - Parameters.comp13 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.legalHold - ], - isXML: true, - serializer: xmlSerializer - }; - var setMetadataOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.BlobSetMetadataHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobSetMetadataExceptionHeaders - } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp6], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.metadata, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.encryptionScope - ], - isXML: true, - serializer: xmlSerializer - }; - var acquireLeaseOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.BlobAcquireLeaseHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobAcquireLeaseExceptionHeaders - } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp10], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.action, - Parameters.duration, - Parameters.proposedLeaseId, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags - ], - isXML: true, - serializer: xmlSerializer - }; - var releaseLeaseOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.BlobReleaseLeaseHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobReleaseLeaseExceptionHeaders - } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp10], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.action1, - Parameters.leaseId1, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags - ], - isXML: true, - serializer: xmlSerializer - }; - var renewLeaseOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.BlobRenewLeaseHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobRenewLeaseExceptionHeaders - } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp10], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.leaseId1, - Parameters.action2, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags - ], - isXML: true, - serializer: xmlSerializer - }; - var changeLeaseOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.BlobChangeLeaseHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobChangeLeaseExceptionHeaders - } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp10], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.leaseId1, - Parameters.action4, - Parameters.proposedLeaseId1, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags - ], - isXML: true, - serializer: xmlSerializer - }; - var breakLeaseOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 202: { - headersMapper: Mappers.BlobBreakLeaseHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobBreakLeaseExceptionHeaders - } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp10], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.action3, - Parameters.breakPeriod, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags - ], - isXML: true, - serializer: xmlSerializer - }; - var createSnapshotOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.BlobCreateSnapshotHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobCreateSnapshotExceptionHeaders - } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp14], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.metadata, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.encryptionScope - ], - isXML: true, - serializer: xmlSerializer - }; - var startCopyFromURLOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 202: { - headersMapper: Mappers.BlobStartCopyFromURLHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobStartCopyFromURLExceptionHeaders - } - }, - queryParameters: [Parameters.timeoutInSeconds], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.metadata, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.immutabilityPolicyExpiry, - Parameters.immutabilityPolicyMode, - Parameters.tier, - Parameters.rehydratePriority, - Parameters.sourceIfModifiedSince, - Parameters.sourceIfUnmodifiedSince, - Parameters.sourceIfMatch, - Parameters.sourceIfNoneMatch, - Parameters.sourceIfTags, - Parameters.copySource, - Parameters.blobTagsString, - Parameters.sealBlob, - Parameters.legalHold1 - ], - isXML: true, - serializer: xmlSerializer - }; - var copyFromURLOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 202: { - headersMapper: Mappers.BlobCopyFromURLHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobCopyFromURLExceptionHeaders - } - }, - queryParameters: [Parameters.timeoutInSeconds], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.metadata, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.immutabilityPolicyExpiry, - Parameters.immutabilityPolicyMode, - Parameters.encryptionScope, - Parameters.tier, - Parameters.sourceIfModifiedSince, - Parameters.sourceIfUnmodifiedSince, - Parameters.sourceIfMatch, - Parameters.sourceIfNoneMatch, - Parameters.copySource, - Parameters.blobTagsString, - Parameters.legalHold1, - Parameters.xMsRequiresSync, - Parameters.sourceContentMD5, - Parameters.copySourceAuthorization, - Parameters.copySourceTags, - Parameters.fileRequestIntent - ], - isXML: true, - serializer: xmlSerializer - }; - var abortCopyFromURLOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 204: { - headersMapper: Mappers.BlobAbortCopyFromURLHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobAbortCopyFromURLExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.comp15, - Parameters.copyId - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.copyActionAbortConstant - ], - isXML: true, - serializer: xmlSerializer - }; - var setTierOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.BlobSetTierHeaders - }, - 202: { - headersMapper: Mappers.BlobSetTierHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobSetTierExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.snapshot, - Parameters.versionId, - Parameters.comp16 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.ifTags, - Parameters.rehydratePriority, - Parameters.tier1 - ], - isXML: true, - serializer: xmlSerializer - }; - var getAccountInfoOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "GET", - responses: { - 200: { - headersMapper: Mappers.BlobGetAccountInfoHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobGetAccountInfoExceptionHeaders - } - }, - queryParameters: [ - Parameters.comp, - Parameters.timeoutInSeconds, - Parameters.restype1 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1 - ], - isXML: true, - serializer: xmlSerializer - }; - var queryOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "POST", - responses: { - 200: { - bodyMapper: { - type: { name: "Stream" }, - serializedName: "parsedResponse" - }, - headersMapper: Mappers.BlobQueryHeaders - }, - 206: { - bodyMapper: { - type: { name: "Stream" }, - serializedName: "parsedResponse" - }, - headersMapper: Mappers.BlobQueryHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobQueryExceptionHeaders - } - }, - requestBody: Parameters.queryRequest, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.snapshot, - Parameters.comp17 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.contentType, - Parameters.accept, - Parameters.version, - Parameters.requestId, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags - ], - isXML: true, - contentType: "application/xml; charset=utf-8", - mediaType: "xml", - serializer: xmlSerializer - }; - var getTagsOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.BlobTags, - headersMapper: Mappers.BlobGetTagsHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobGetTagsExceptionHeaders - } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.snapshot, - Parameters.versionId, - Parameters.comp18 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.ifTags - ], - isXML: true, - serializer: xmlSerializer - }; - var setTagsOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 204: { - headersMapper: Mappers.BlobSetTagsHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlobSetTagsExceptionHeaders + // @ts-ignore + indexOf(element, offset) { + return -1; + } + /** + * Iterator for rows in this Table. + */ + [Symbol.iterator]() { + if (this.batches.length > 0) { + return instance4.visit(new Vector(this.data)); } - }, - requestBody: Parameters.tags, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.versionId, - Parameters.comp18 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.contentType, - Parameters.accept, - Parameters.version, - Parameters.requestId, - Parameters.leaseId, - Parameters.ifTags, - Parameters.transactionalContentMD5, - Parameters.transactionalContentCrc64 - ], - isXML: true, - contentType: "application/xml; charset=utf-8", - mediaType: "xml", - serializer: xmlSerializer - }; + return new Array(0)[Symbol.iterator](); + } + /** + * Return a JavaScript Array of the Table rows. + * + * @returns An Array of Table rows. + */ + toArray() { + return [...this]; + } + /** + * Returns a string representation of the Table rows. + * + * @returns A string representation of the Table rows. + */ + toString() { + return `[ + ${this.toArray().join(",\n ")} +]`; + } + /** + * Combines two or more Tables of the same schema. + * + * @param others Additional Tables to add to the end of this Tables. + */ + concat(...others) { + const schema = this.schema; + const data = this.data.concat(others.flatMap(({ data: data2 }) => data2)); + return new _Table(schema, data.map((data2) => new RecordBatch3(schema, data2))); + } + /** + * Return a zero-copy sub-section of this Table. + * + * @param begin The beginning of the specified portion of the Table. + * @param end The end of the specified portion of the Table. This is exclusive of the element at the index 'end'. + */ + slice(begin, end) { + const schema = this.schema; + [begin, end] = clampRange({ length: this.numRows }, begin, end); + const data = sliceChunks(this.data, this._offsets, begin, end); + return new _Table(schema, data.map((chunk) => new RecordBatch3(schema, chunk))); + } + /** + * Returns a child Vector by name, or null if this Vector has no child with the given name. + * + * @param name The name of the child to retrieve. + */ + getChild(name) { + return this.getChildAt(this.schema.fields.findIndex((f) => f.name === name)); + } + /** + * Returns a child Vector by index, or null if this Vector has no child at the supplied index. + * + * @param index The index of the child to retrieve. + */ + getChildAt(index2) { + if (index2 > -1 && index2 < this.schema.fields.length) { + const data = this.data.map((data2) => data2.children[index2]); + if (data.length === 0) { + const { type } = this.schema.fields[index2]; + const empty = makeData({ type, length: 0, nullCount: 0 }); + data.push(empty._changeLengthAndBackfillNullBitmap(this.numRows)); + } + return new Vector(data); + } + return null; + } + /** + * Sets a child Vector by name. + * + * @param name The name of the child to overwrite. + * @returns A new Table with the supplied child for the specified name. + */ + setChild(name, child) { + var _b2; + return this.setChildAt((_b2 = this.schema.fields) === null || _b2 === void 0 ? void 0 : _b2.findIndex((f) => f.name === name), child); + } + setChildAt(index2, child) { + let schema = this.schema; + let batches = [...this.batches]; + if (index2 > -1 && index2 < this.numCols) { + if (!child) { + child = new Vector([makeData({ type: new Null2(), length: this.numRows })]); + } + const fields = schema.fields.slice(); + const field = fields[index2].clone({ type: child.type }); + const children = this.schema.fields.map((_2, i) => this.getChildAt(i)); + [fields[index2], children[index2]] = [field, child]; + [schema, batches] = distributeVectorsIntoRecordBatches(schema, children); + } + return new _Table(schema, batches); + } + /** + * Construct a new Table containing only specified columns. + * + * @param columnNames Names of columns to keep. + * @returns A new Table of columns matching the specified names. + */ + select(columnNames) { + const nameToIndex = this.schema.fields.reduce((m, f, i) => m.set(f.name, i), /* @__PURE__ */ new Map()); + return this.selectAt(columnNames.map((columnName) => nameToIndex.get(columnName)).filter((x) => x > -1)); + } + /** + * Construct a new Table containing only columns at the specified indices. + * + * @param columnIndices Indices of columns to keep. + * @returns A new Table of columns at the specified indices. + */ + selectAt(columnIndices) { + const schema = this.schema.selectAt(columnIndices); + const data = this.batches.map((batch) => batch.selectAt(columnIndices)); + return new _Table(schema, data); + } + assign(other) { + const fields = this.schema.fields; + const [indices, oldToNew] = other.schema.fields.reduce((memo, f2, newIdx) => { + const [indices2, oldToNew2] = memo; + const i = fields.findIndex((f) => f.name === f2.name); + ~i ? oldToNew2[i] = newIdx : indices2.push(newIdx); + return memo; + }, [[], []]); + const schema = this.schema.assign(other.schema); + const columns = [ + ...fields.map((_2, i) => [i, oldToNew[i]]).map(([i, j]) => j === void 0 ? this.getChildAt(i) : other.getChildAt(j)), + ...indices.map((i) => other.getChildAt(i)) + ].filter(Boolean); + return new _Table(...distributeVectorsIntoRecordBatches(schema, columns)); + } + }; + _a3 = Symbol.toStringTag; + Table[_a3] = ((proto) => { + proto.schema = null; + proto.batches = []; + proto._offsets = new Uint32Array([0]); + proto._nullCount = -1; + proto[Symbol.isConcatSpreadable] = true; + proto[kTableSymbol] = true; + proto["isValid"] = wrapChunkedCall1(isChunkedValid); + proto["get"] = wrapChunkedCall1(instance2.getVisitFn(Type2.Struct)); + proto["set"] = wrapChunkedCall2(instance.getVisitFn(Type2.Struct)); + proto["indexOf"] = wrapChunkedIndexOf(instance3.getVisitFn(Type2.Struct)); + return "Table"; + })(Table.prototype); + Object.defineProperty(Table, Symbol.hasInstance, { + value: function isTableInstance(instance8) { + return Function.prototype[Symbol.hasInstance].call(this, instance8) || this === Table && Table.isTable(instance8); + } + }); } }); -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/pageBlob.js -var require_pageBlob = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/pageBlob.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PageBlobImpl = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var coreClient = tslib_1.__importStar(require_commonjs8()); - var Mappers = tslib_1.__importStar(require_mappers()); - var Parameters = tslib_1.__importStar(require_parameters()); - var PageBlobImpl = class { - client; +// node_modules/apache-arrow/recordbatch.mjs +function ensureSameLengthData(schema, chunks, maxLength = chunks.reduce((max, col) => Math.max(max, col.length), 0)) { + var _b2; + const fields = [...schema.fields]; + const children = [...chunks]; + const nullBitmapSize = (maxLength + 63 & ~63) >> 3; + for (const [idx, field] of schema.fields.entries()) { + const chunk = chunks[idx]; + if (!chunk || chunk.length !== maxLength) { + fields[idx] = field.clone({ nullable: true }); + children[idx] = (_b2 = chunk === null || chunk === void 0 ? void 0 : chunk._changeLengthAndBackfillNullBitmap(maxLength)) !== null && _b2 !== void 0 ? _b2 : makeData({ + type: field.type, + length: maxLength, + nullCount: maxLength, + nullBitmap: new Uint8Array(nullBitmapSize) + }); + } + } + return [ + schema.assign(fields), + makeData({ type: new Struct(fields), length: maxLength, children }) + ]; +} +function collectDictionaries(fields, children, dictionaries = /* @__PURE__ */ new Map()) { + var _b2, _c2; + if (((_b2 = fields === null || fields === void 0 ? void 0 : fields.length) !== null && _b2 !== void 0 ? _b2 : 0) > 0 && (fields === null || fields === void 0 ? void 0 : fields.length) === (children === null || children === void 0 ? void 0 : children.length)) { + for (let i = -1, n = fields.length; ++i < n; ) { + const { type } = fields[i]; + const data = children[i]; + for (const next of [data, ...((_c2 = data === null || data === void 0 ? void 0 : data.dictionary) === null || _c2 === void 0 ? void 0 : _c2.data) || []]) { + collectDictionaries(type.children, next === null || next === void 0 ? void 0 : next.children, dictionaries); + } + if (DataType.isDictionary(type)) { + const { id } = type; + if (!dictionaries.has(id)) { + if (data === null || data === void 0 ? void 0 : data.dictionary) { + dictionaries.set(id, data.dictionary); + } + } else if (dictionaries.get(id) !== data.dictionary) { + throw new Error(`Cannot create Schema containing two different dictionaries with the same Id`); + } + } + } + } + return dictionaries; +} +var _a4, kRecordBatchSymbol, RecordBatch3, _InternalEmptyPlaceholderRecordBatch; +var init_recordbatch2 = __esm({ + "node_modules/apache-arrow/recordbatch.mjs"() { + init_data(); + init_table(); + init_vector2(); + init_schema2(); + init_type2(); + init_vector(); + init_get(); + init_set(); + init_indexof(); + init_iterator(); + kRecordBatchSymbol = /* @__PURE__ */ Symbol.for("apache-arrow/RecordBatch"); + RecordBatch3 = class _RecordBatch { + /** + * Check if an object is an instance of RecordBatch. + * This works across different instances of the Arrow library. + */ + /** @nocollapse */ + static isRecordBatch(x) { + return (x === null || x === void 0 ? void 0 : x[kRecordBatchSymbol]) === true; + } + constructor(...args) { + switch (args.length) { + case 3: + case 2: { + [this.schema] = args; + if (!(this.schema instanceof Schema4)) { + throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair."); + } + [ + , + this.data = makeData({ + nullCount: 0, + type: new Struct(this.schema.fields), + children: this.schema.fields.map((f) => makeData({ type: f.type, nullCount: 0 })) + }), + this._metadata = /* @__PURE__ */ new Map() + ] = args; + if (!(this.data instanceof Data)) { + throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair."); + } + [this.schema, this.data] = ensureSameLengthData(this.schema, this.data.children, this.data.length); + break; + } + case 1: { + const [obj] = args; + const { fields, children, length } = Object.keys(obj).reduce((memo, name, i) => { + memo.children[i] = obj[name]; + memo.length = Math.max(memo.length, obj[name].length); + memo.fields[i] = Field2.new({ name, type: obj[name].type, nullable: true }); + return memo; + }, { + length: 0, + fields: new Array(), + children: new Array() + }); + const schema = new Schema4(fields); + const data = makeData({ type: new Struct(fields), length, children, nullCount: 0 }); + [this.schema, this.data] = ensureSameLengthData(schema, data.children, length); + this._metadata = /* @__PURE__ */ new Map(); + break; + } + default: + throw new TypeError("RecordBatch constructor expects an Object mapping names to child Data, or a [Schema, Data] pair."); + } + } /** - * Initialize a new instance of the class PageBlob class. - * @param client Reference to the service client + * Custom metadata for this RecordBatch. */ - constructor(client) { - this.client = client; + get metadata() { + return this._metadata; + } + get dictionaries() { + return this._dictionaries || (this._dictionaries = collectDictionaries(this.schema.fields, this.data.children)); } /** - * The Create operation creates a new page blob. - * @param contentLength The length of the request. - * @param blobContentLength This header specifies the maximum size for the page blob, up to 1 TB. The - * page blob size must be aligned to a 512-byte boundary. - * @param options The options parameters. + * The number of columns in this RecordBatch. */ - create(contentLength, blobContentLength, options) { - return this.client.sendOperationRequest({ contentLength, blobContentLength, options }, createOperationSpec); + get numCols() { + return this.schema.fields.length; } /** - * The Upload Pages operation writes a range of pages to a page blob - * @param contentLength The length of the request. - * @param body Initial data - * @param options The options parameters. + * The number of rows in this RecordBatch. */ - uploadPages(contentLength, body, options) { - return this.client.sendOperationRequest({ contentLength, body, options }, uploadPagesOperationSpec); + get numRows() { + return this.data.length; } /** - * The Clear Pages operation clears a set of pages from a page blob - * @param contentLength The length of the request. - * @param options The options parameters. + * The number of null rows in this RecordBatch. */ - clearPages(contentLength, options) { - return this.client.sendOperationRequest({ contentLength, options }, clearPagesOperationSpec); + get nullCount() { + return this.data.nullCount; } /** - * The Upload Pages operation writes a range of pages to a page blob where the contents are read from a - * URL - * @param sourceUrl Specify a URL to the copy source. - * @param sourceRange Bytes of source data in the specified range. The length of this range should - * match the ContentLength header and x-ms-range/Range destination range header. - * @param contentLength The length of the request. - * @param range The range of bytes to which the source range would be written. The range should be 512 - * aligned and range-end is required. - * @param options The options parameters. + * Check whether an row is null. + * @param index The index at which to read the validity bitmap. */ - uploadPagesFromURL(sourceUrl, sourceRange, contentLength, range2, options) { - return this.client.sendOperationRequest({ sourceUrl, sourceRange, contentLength, range: range2, options }, uploadPagesFromURLOperationSpec); + isValid(index2) { + return this.data.getValid(index2); } /** - * The Get Page Ranges operation returns the list of valid page ranges for a page blob or snapshot of a - * page blob - * @param options The options parameters. + * Get a row by position. + * @param index The index of the row to read. */ - getPageRanges(options) { - return this.client.sendOperationRequest({ options }, getPageRangesOperationSpec); + get(index2) { + return instance2.visit(this.data, index2); } /** - * The Get Page Ranges Diff operation returns the list of valid page ranges for a page blob that were - * changed between target blob and previous snapshot. - * @param options The options parameters. + * Get a row value by position. + * @param index The index of the row to read. A negative index will count back from the last row. + */ + at(index2) { + return this.get(wrapIndex(index2, this.numRows)); + } + /** + * Set a row by position. + * @param index The index of the row to write. + * @param value The value to set. */ - getPageRangesDiff(options) { - return this.client.sendOperationRequest({ options }, getPageRangesDiffOperationSpec); + set(index2, value) { + return instance.visit(this.data, index2, value); } /** - * Resize the Blob - * @param blobContentLength This header specifies the maximum size for the page blob, up to 1 TB. The - * page blob size must be aligned to a 512-byte boundary. - * @param options The options parameters. + * Retrieve the index of the first occurrence of a row in an RecordBatch. + * @param element The row to locate in the RecordBatch. + * @param offset The index at which to begin the search. If offset is omitted, the search starts at index 0. */ - resize(blobContentLength, options) { - return this.client.sendOperationRequest({ blobContentLength, options }, resizeOperationSpec); + indexOf(element, offset) { + return instance3.visit(this.data, element, offset); } /** - * Update the sequence number of the blob - * @param sequenceNumberAction Required if the x-ms-blob-sequence-number header is set for the request. - * This property applies to page blobs only. This property indicates how the service should modify the - * blob's sequence number - * @param options The options parameters. + * Iterator for rows in this RecordBatch. */ - updateSequenceNumber(sequenceNumberAction, options) { - return this.client.sendOperationRequest({ sequenceNumberAction, options }, updateSequenceNumberOperationSpec); + [Symbol.iterator]() { + return instance4.visit(new Vector([this.data])); } /** - * The Copy Incremental operation copies a snapshot of the source page blob to a destination page blob. - * The snapshot is copied such that only the differential changes between the previously copied - * snapshot are transferred to the destination. The copied snapshots are complete copies of the - * original snapshot and can be read or copied from as usual. This API is supported since REST version - * 2016-05-31. - * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to - * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would - * appear in a request URI. The source blob must either be public or must be authenticated via a shared - * access signature. - * @param options The options parameters. + * Return a JavaScript Array of the RecordBatch rows. + * @returns An Array of RecordBatch rows. */ - copyIncremental(copySource, options) { - return this.client.sendOperationRequest({ copySource, options }, copyIncrementalOperationSpec); + toArray() { + return [...this]; } - }; - exports2.PageBlobImpl = PageBlobImpl; - var xmlSerializer = coreClient.createSerializer( - Mappers, - /* isXml */ - true - ); - var createOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.PageBlobCreateHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.PageBlobCreateExceptionHeaders + /** + * Combines two or more RecordBatch of the same schema. + * @param others Additional RecordBatch to add to the end of this RecordBatch. + */ + concat(...others) { + return new Table(this.schema, [this, ...others]); + } + /** + * Return a zero-copy sub-section of this RecordBatch. + * @param start The beginning of the specified portion of the RecordBatch. + * @param end The end of the specified portion of the RecordBatch. This is exclusive of the row at the index 'end'. + */ + slice(begin, end) { + const [slice] = new Vector([this.data]).slice(begin, end).data; + return new _RecordBatch(this.schema, slice, this._metadata); + } + /** + * Returns a child Vector by name, or null if this Vector has no child with the given name. + * @param name The name of the child to retrieve. + */ + getChild(name) { + var _b2; + return this.getChildAt((_b2 = this.schema.fields) === null || _b2 === void 0 ? void 0 : _b2.findIndex((f) => f.name === name)); + } + /** + * Returns a child Vector by index, or null if this Vector has no child at the supplied index. + * @param index The index of the child to retrieve. + */ + getChildAt(index2) { + if (index2 > -1 && index2 < this.schema.fields.length) { + return new Vector([this.data.children[index2]]); } - }, - queryParameters: [Parameters.timeoutInSeconds], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.contentLength, - Parameters.metadata, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.blobCacheControl, - Parameters.blobContentType, - Parameters.blobContentMD5, - Parameters.blobContentEncoding, - Parameters.blobContentLanguage, - Parameters.blobContentDisposition, - Parameters.immutabilityPolicyExpiry, - Parameters.immutabilityPolicyMode, - Parameters.encryptionScope, - Parameters.tier, - Parameters.blobTagsString, - Parameters.legalHold1, - Parameters.blobType, - Parameters.blobContentLength, - Parameters.blobSequenceNumber - ], - isXML: true, - serializer: xmlSerializer - }; - var uploadPagesOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.PageBlobUploadPagesHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.PageBlobUploadPagesExceptionHeaders + return null; + } + /** + * Sets a child Vector by name. + * @param name The name of the child to overwrite. + * @returns A new RecordBatch with the new child for the specified name. + */ + setChild(name, child) { + var _b2; + return this.setChildAt((_b2 = this.schema.fields) === null || _b2 === void 0 ? void 0 : _b2.findIndex((f) => f.name === name), child); + } + setChildAt(index2, child) { + let schema = this.schema; + let data = this.data; + if (index2 > -1 && index2 < this.numCols) { + if (!child) { + child = new Vector([makeData({ type: new Null2(), length: this.numRows })]); + } + const fields = schema.fields.slice(); + const children = data.children.slice(); + const field = fields[index2].clone({ type: child.type }); + [fields[index2], children[index2]] = [field, child.data[0]]; + schema = new Schema4(fields, new Map(this.schema.metadata)); + data = makeData({ type: new Struct(fields), length: data.length, children }); } - }, - requestBody: Parameters.body1, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp19], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.contentLength, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.range, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.encryptionScope, - Parameters.transactionalContentMD5, - Parameters.transactionalContentCrc64, - Parameters.contentType1, - Parameters.accept2, - Parameters.pageWrite, - Parameters.ifSequenceNumberLessThanOrEqualTo, - Parameters.ifSequenceNumberLessThan, - Parameters.ifSequenceNumberEqualTo - ], - isXML: true, - contentType: "application/xml; charset=utf-8", - mediaType: "binary", - serializer: xmlSerializer - }; - var clearPagesOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.PageBlobClearPagesHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.PageBlobClearPagesExceptionHeaders + return new _RecordBatch(schema, data, this._metadata); + } + /** + * Construct a new RecordBatch containing only specified columns. + * + * @param columnNames Names of columns to keep. + * @returns A new RecordBatch of columns matching the specified names. + */ + select(columnNames) { + const schema = this.schema.select(columnNames); + const type = new Struct(schema.fields); + const children = []; + for (const name of columnNames) { + const index2 = this.schema.fields.findIndex((f) => f.name === name); + if (~index2) { + children[index2] = this.data.children[index2]; + } } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp19], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.contentLength, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.range, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.encryptionScope, - Parameters.ifSequenceNumberLessThanOrEqualTo, - Parameters.ifSequenceNumberLessThan, - Parameters.ifSequenceNumberEqualTo, - Parameters.pageWrite1 - ], - isXML: true, - serializer: xmlSerializer + return new _RecordBatch(schema, makeData({ type, length: this.numRows, children }), this._metadata); + } + /** + * Construct a new RecordBatch containing only columns at the specified indices. + * + * @param columnIndices Indices of columns to keep. + * @returns A new RecordBatch of columns matching at the specified indices. + */ + selectAt(columnIndices) { + const schema = this.schema.selectAt(columnIndices); + const children = columnIndices.map((i) => this.data.children[i]).filter(Boolean); + const subset = makeData({ type: new Struct(schema.fields), length: this.numRows, children }); + return new _RecordBatch(schema, subset, this._metadata); + } }; - var uploadPagesFromURLOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.PageBlobUploadPagesFromURLHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.PageBlobUploadPagesFromURLExceptionHeaders - } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp19], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.contentLength, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.encryptionScope, - Parameters.sourceIfModifiedSince, - Parameters.sourceIfUnmodifiedSince, - Parameters.sourceIfMatch, - Parameters.sourceIfNoneMatch, - Parameters.sourceContentMD5, - Parameters.copySourceAuthorization, - Parameters.fileRequestIntent, - Parameters.pageWrite, - Parameters.ifSequenceNumberLessThanOrEqualTo, - Parameters.ifSequenceNumberLessThan, - Parameters.ifSequenceNumberEqualTo, - Parameters.sourceUrl, - Parameters.sourceRange, - Parameters.sourceContentCrc64, - Parameters.range1 - ], - isXML: true, - serializer: xmlSerializer + _a4 = Symbol.toStringTag; + RecordBatch3[_a4] = ((proto) => { + proto._nullCount = -1; + proto[Symbol.isConcatSpreadable] = true; + proto[kRecordBatchSymbol] = true; + return "RecordBatch"; + })(RecordBatch3.prototype); + Object.defineProperty(RecordBatch3, Symbol.hasInstance, { + value: function isRecordBatchInstance(instance8) { + return Function.prototype[Symbol.hasInstance].call(this, instance8) || this === RecordBatch3 && RecordBatch3.isRecordBatch(instance8); + } + }); + _InternalEmptyPlaceholderRecordBatch = class extends RecordBatch3 { + constructor(schema, metadata) { + const children = schema.fields.map((f) => makeData({ type: f.type })); + const data = makeData({ type: new Struct(schema.fields), length: 0, nullCount: 0, children }); + super(schema, data, metadata || /* @__PURE__ */ new Map()); + } }; - var getPageRangesOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.PageList, - headersMapper: Mappers.PageBlobGetPageRangesHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.PageBlobGetPageRangesExceptionHeaders + } +}); + +// node_modules/apache-arrow/ipc/message.mjs +function checkForMagicArrowString(buffer, index2 = 0) { + for (let i = -1, n = MAGIC.length; ++i < n; ) { + if (MAGIC[i] !== buffer[index2 + i]) { + return false; + } + } + return true; +} +var import_flatbuffers, invalidMessageType, nullMessage, invalidMessageMetadata, invalidMessageBodyLength, MessageReader, AsyncMessageReader, JSONMessageReader, PADDING, MAGIC_STR, MAGIC, magicLength, magicAndPadding, magicX2AndPadding; +var init_message3 = __esm({ + "node_modules/apache-arrow/ipc/message.mjs"() { + init_tslib_es6(); + init_enum(); + import_flatbuffers = __toESM(require_flatbuffers(), 1); + init_message2(); + init_compat(); + init_file2(); + init_buffer(); + init_stream(); + init_interfaces(); + invalidMessageType = (type) => `Expected ${MessageHeader[type]} Message in stream, but was null or length 0.`; + nullMessage = (type) => `Header pointer of flatbuffer-encoded ${MessageHeader[type]} Message is null or length 0.`; + invalidMessageMetadata = (expected, actual) => `Expected to read ${expected} metadata bytes, but only read ${actual}.`; + invalidMessageBodyLength = (expected, actual) => `Expected to read ${expected} bytes for message body, but only read ${actual}.`; + MessageReader = class { + constructor(source) { + this.source = source instanceof ByteStream ? source : new ByteStream(source); + } + [Symbol.iterator]() { + return this; + } + next() { + let r; + if ((r = this.readMetadataLength()).done) { + return ITERATOR_DONE; } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.marker, - Parameters.maxPageSize, - Parameters.snapshot, - Parameters.comp20 - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.range, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags - ], - isXML: true, - serializer: xmlSerializer - }; - var getPageRangesDiffOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.PageList, - headersMapper: Mappers.PageBlobGetPageRangesDiffHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.PageBlobGetPageRangesDiffExceptionHeaders + if (r.value === -1 && (r = this.readMetadataLength()).done) { + return ITERATOR_DONE; } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.marker, - Parameters.maxPageSize, - Parameters.snapshot, - Parameters.comp20, - Parameters.prevsnapshot - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.range, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.prevSnapshotUrl - ], - isXML: true, - serializer: xmlSerializer - }; - var resizeOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.PageBlobResizeHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.PageBlobResizeExceptionHeaders + if ((r = this.readMetadata(r.value)).done) { + return ITERATOR_DONE; } - }, - queryParameters: [Parameters.comp, Parameters.timeoutInSeconds], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.encryptionScope, - Parameters.blobContentLength - ], - isXML: true, - serializer: xmlSerializer + return r; + } + throw(value) { + return this.source.throw(value); + } + return(value) { + return this.source.return(value); + } + readMessage(type) { + let r; + if ((r = this.next()).done) { + return null; + } + if (type != null && r.value.headerType !== type) { + throw new Error(invalidMessageType(type)); + } + return r.value; + } + readMessageBody(bodyLength) { + if (bodyLength <= 0) { + return new Uint8Array(0); + } + const buf = toUint8Array(this.source.read(bodyLength)); + if (buf.byteLength < bodyLength) { + throw new Error(invalidMessageBodyLength(bodyLength, buf.byteLength)); + } + return ( + /* 1. */ + buf.byteOffset % 8 === 0 && /* 2. */ + buf.byteOffset + buf.byteLength <= buf.buffer.byteLength ? buf : buf.slice() + ); + } + readSchema(throwIfNull = false) { + const type = MessageHeader.Schema; + const message = this.readMessage(type); + const schema = message === null || message === void 0 ? void 0 : message.header(); + if (throwIfNull && !schema) { + throw new Error(nullMessage(type)); + } + return schema; + } + readMetadataLength() { + const buf = this.source.read(PADDING); + const bb = buf && new import_flatbuffers.ByteBuffer(buf); + const len = (bb === null || bb === void 0 ? void 0 : bb.readInt32(0)) || 0; + return { done: len === 0, value: len }; + } + readMetadata(metadataLength) { + const buf = this.source.read(metadataLength); + if (!buf) { + return ITERATOR_DONE; + } + if (buf.byteLength < metadataLength) { + throw new Error(invalidMessageMetadata(metadataLength, buf.byteLength)); + } + return { done: false, value: Message2.decode(buf) }; + } }; - var updateSequenceNumberOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.PageBlobUpdateSequenceNumberHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.PageBlobUpdateSequenceNumberExceptionHeaders + AsyncMessageReader = class { + constructor(source, byteLength) { + this.source = source instanceof AsyncByteStream ? source : isFileHandle(source) ? new AsyncRandomAccessFile(source, byteLength) : new AsyncByteStream(source); + } + [Symbol.asyncIterator]() { + return this; + } + next() { + return __awaiter(this, void 0, void 0, function* () { + let r; + if ((r = yield this.readMetadataLength()).done) { + return ITERATOR_DONE; + } + if (r.value === -1 && (r = yield this.readMetadataLength()).done) { + return ITERATOR_DONE; + } + if ((r = yield this.readMetadata(r.value)).done) { + return ITERATOR_DONE; + } + return r; + }); + } + throw(value) { + return __awaiter(this, void 0, void 0, function* () { + return yield this.source.throw(value); + }); + } + return(value) { + return __awaiter(this, void 0, void 0, function* () { + return yield this.source.return(value); + }); + } + readMessage(type) { + return __awaiter(this, void 0, void 0, function* () { + let r; + if ((r = yield this.next()).done) { + return null; + } + if (type != null && r.value.headerType !== type) { + throw new Error(invalidMessageType(type)); + } + return r.value; + }); + } + readMessageBody(bodyLength) { + return __awaiter(this, void 0, void 0, function* () { + if (bodyLength <= 0) { + return new Uint8Array(0); + } + const buf = toUint8Array(yield this.source.read(bodyLength)); + if (buf.byteLength < bodyLength) { + throw new Error(invalidMessageBodyLength(bodyLength, buf.byteLength)); + } + return ( + /* 1. */ + buf.byteOffset % 8 === 0 && /* 2. */ + buf.byteOffset + buf.byteLength <= buf.buffer.byteLength ? buf : buf.slice() + ); + }); + } + readSchema() { + return __awaiter(this, arguments, void 0, function* (throwIfNull = false) { + const type = MessageHeader.Schema; + const message = yield this.readMessage(type); + const schema = message === null || message === void 0 ? void 0 : message.header(); + if (throwIfNull && !schema) { + throw new Error(nullMessage(type)); + } + return schema; + }); + } + readMetadataLength() { + return __awaiter(this, void 0, void 0, function* () { + const buf = yield this.source.read(PADDING); + const bb = buf && new import_flatbuffers.ByteBuffer(buf); + const len = (bb === null || bb === void 0 ? void 0 : bb.readInt32(0)) || 0; + return { done: len === 0, value: len }; + }); + } + readMetadata(metadataLength) { + return __awaiter(this, void 0, void 0, function* () { + const buf = yield this.source.read(metadataLength); + if (!buf) { + return ITERATOR_DONE; + } + if (buf.byteLength < metadataLength) { + throw new Error(invalidMessageMetadata(metadataLength, buf.byteLength)); + } + return { done: false, value: Message2.decode(buf) }; + }); + } + }; + JSONMessageReader = class extends MessageReader { + constructor(source) { + super(new Uint8Array(0)); + this._schema = false; + this._body = []; + this._batchIndex = 0; + this._dictionaryIndex = 0; + this._json = source instanceof ArrowJSON ? source : new ArrowJSON(source); + } + next() { + const { _json } = this; + if (!this._schema) { + this._schema = true; + const message = Message2.fromJSON(_json.schema, MessageHeader.Schema); + return { done: false, value: message }; + } + if (this._dictionaryIndex < _json.dictionaries.length) { + const batch = _json.dictionaries[this._dictionaryIndex++]; + this._body = batch["data"]["columns"]; + const message = Message2.fromJSON(batch, MessageHeader.DictionaryBatch); + return { done: false, value: message }; + } + if (this._batchIndex < _json.batches.length) { + const batch = _json.batches[this._batchIndex++]; + this._body = batch["columns"]; + const message = Message2.fromJSON(batch, MessageHeader.RecordBatch); + return { done: false, value: message }; + } + this._body = []; + return ITERATOR_DONE; + } + readMessageBody(_bodyLength) { + return flattenDataSources(this._body); + function flattenDataSources(xs) { + return (xs || []).reduce((buffers, column) => [ + ...buffers, + ...column["VALIDITY"] && [column["VALIDITY"]] || [], + ...column["TYPE_ID"] && [column["TYPE_ID"]] || [], + ...column["OFFSET"] && [column["OFFSET"]] || [], + ...column["DATA"] && [column["DATA"]] || [], + ...column["VIEWS"] && [column["VIEWS"]] || [], + ...column["VARIADIC_DATA_BUFFERS"] || [], + ...flattenDataSources(column["children"]) + ], []); + } + } + readMessage(type) { + let r; + if ((r = this.next()).done) { + return null; } - }, - queryParameters: [Parameters.comp, Parameters.timeoutInSeconds], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.blobSequenceNumber, - Parameters.sequenceNumberAction - ], - isXML: true, - serializer: xmlSerializer + if (type != null && r.value.headerType !== type) { + throw new Error(invalidMessageType(type)); + } + return r.value; + } + readSchema() { + const type = MessageHeader.Schema; + const message = this.readMessage(type); + const schema = message === null || message === void 0 ? void 0 : message.header(); + if (!message || !schema) { + throw new Error(nullMessage(type)); + } + return schema; + } }; - var copyIncrementalOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 202: { - headersMapper: Mappers.PageBlobCopyIncrementalHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.PageBlobCopyIncrementalExceptionHeaders + PADDING = 4; + MAGIC_STR = "ARROW1"; + MAGIC = new Uint8Array(MAGIC_STR.length); + for (let i = 0; i < MAGIC_STR.length; i += 1) { + MAGIC[i] = MAGIC_STR.codePointAt(i); + } + magicLength = MAGIC.length; + magicAndPadding = magicLength + PADDING; + magicX2AndPadding = magicLength * 2 + PADDING; + } +}); + +// node_modules/apache-arrow/ipc/compression/validators.mjs +var Lz4FrameValidator, ZstdValidator, compressionValidators; +var init_validators = __esm({ + "node_modules/apache-arrow/ipc/compression/validators.mjs"() { + init_compression_type(); + Lz4FrameValidator = class { + constructor() { + this.LZ4_FRAME_MAGIC = new Uint8Array([4, 34, 77, 24]); + this.MIN_HEADER_LENGTH = 7; + } + isValidCodecEncode(codec) { + const testData = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); + const compressed = codec.encode(testData); + return this._isValidCompressed(compressed); + } + _isValidCompressed(buffer) { + return this._hasMinimumLength(buffer) && this._hasValidMagicNumber(buffer) && this._hasValidVersion(buffer); + } + _hasMinimumLength(buffer) { + return buffer.length >= this.MIN_HEADER_LENGTH; + } + _hasValidMagicNumber(buffer) { + return this.LZ4_FRAME_MAGIC.every((byte, i) => buffer[i] === byte); + } + _hasValidVersion(buffer) { + const flg = buffer[4]; + const versionBits = (flg & 192) >> 6; + return versionBits === 1; + } + }; + ZstdValidator = class { + constructor() { + this.ZSTD_MAGIC = new Uint8Array([40, 181, 47, 253]); + this.MIN_HEADER_LENGTH = 6; + } + isValidCodecEncode(codec) { + const testData = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); + const compressed = codec.encode(testData); + return this._isValidCompressed(compressed); + } + _isValidCompressed(buffer) { + return this._hasMinimumLength(buffer) && this._hasValidMagicNumber(buffer); + } + _hasMinimumLength(buffer) { + return buffer.length >= this.MIN_HEADER_LENGTH; + } + _hasValidMagicNumber(buffer) { + return this.ZSTD_MAGIC.every((byte, i) => buffer[i] === byte); + } + }; + compressionValidators = { + [CompressionType.LZ4_FRAME]: new Lz4FrameValidator(), + [CompressionType.ZSTD]: new ZstdValidator() + }; + } +}); + +// node_modules/apache-arrow/ipc/compression/registry.mjs +var _CompressionRegistry, compressionRegistry; +var init_registry = __esm({ + "node_modules/apache-arrow/ipc/compression/registry.mjs"() { + init_compression_type(); + init_validators(); + _CompressionRegistry = class { + constructor() { + this.registry = {}; + } + set(compression, codec) { + if ((codec === null || codec === void 0 ? void 0 : codec.encode) && typeof codec.encode === "function" && !compressionValidators[compression].isValidCodecEncode(codec)) { + throw new Error(`Encoder for ${CompressionType[compression]} is not valid.`); } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp21], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.copySource - ], - isXML: true, - serializer: xmlSerializer + this.registry[compression] = codec; + } + get(compression) { + var _a6; + return ((_a6 = this.registry) === null || _a6 === void 0 ? void 0 : _a6[compression]) || null; + } }; + compressionRegistry = new _CompressionRegistry(); } }); -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/appendBlob.js -var require_appendBlob = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/appendBlob.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AppendBlobImpl = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var coreClient = tslib_1.__importStar(require_commonjs8()); - var Mappers = tslib_1.__importStar(require_mappers()); - var Parameters = tslib_1.__importStar(require_parameters()); - var AppendBlobImpl = class { - client; - /** - * Initialize a new instance of the class AppendBlob class. - * @param client Reference to the service client - */ - constructor(client) { - this.client = client; +// node_modules/apache-arrow/ipc/compression/constants.mjs +var LENGTH_NO_COMPRESSED_DATA, COMPRESS_LENGTH_PREFIX; +var init_constants = __esm({ + "node_modules/apache-arrow/ipc/compression/constants.mjs"() { + LENGTH_NO_COMPRESSED_DATA = -1; + COMPRESS_LENGTH_PREFIX = 8; + } +}); + +// node_modules/apache-arrow/ipc/reader.mjs +function shouldAutoDestroy(self2, options) { + return options && typeof options["autoDestroy"] === "boolean" ? options["autoDestroy"] : self2["autoDestroy"]; +} +function* readAllSync(source) { + const reader = RecordBatchReader.from(source); + try { + if (!reader.open({ autoDestroy: false }).closed) { + do { + yield reader; + } while (!reader.reset().open().closed); + } + } finally { + reader.cancel(); + } +} +function readAllAsync(source) { + return __asyncGenerator(this, arguments, function* readAllAsync_1() { + const reader = yield __await(RecordBatchReader.from(source)); + try { + if (!(yield __await(reader.open({ autoDestroy: false }))).closed) { + do { + yield yield __await(reader); + } while (!(yield __await(reader.reset().open())).closed); } - /** - * The Create Append Blob operation creates a new append blob. - * @param contentLength The length of the request. - * @param options The options parameters. - */ - create(contentLength, options) { - return this.client.sendOperationRequest({ contentLength, options }, createOperationSpec); + } finally { + yield __await(reader.cancel()); + } + }); +} +function fromArrowJSON(source) { + return new RecordBatchStreamReader(new RecordBatchJSONReaderImpl(source)); +} +function fromByteStream(source) { + const bytes = source.peek(magicLength + 7 & ~7); + return bytes && bytes.byteLength >= 4 ? !checkForMagicArrowString(bytes) ? new RecordBatchStreamReader(new RecordBatchStreamReaderImpl(source)) : new RecordBatchFileReader(new RecordBatchFileReaderImpl(source.read())) : new RecordBatchStreamReader(new RecordBatchStreamReaderImpl((function* () { + })())); +} +function fromAsyncByteStream(source) { + return __awaiter(this, void 0, void 0, function* () { + const bytes = yield source.peek(magicLength + 7 & ~7); + return bytes && bytes.byteLength >= 4 ? !checkForMagicArrowString(bytes) ? new AsyncRecordBatchStreamReader(new AsyncRecordBatchStreamReaderImpl(source)) : new RecordBatchFileReader(new RecordBatchFileReaderImpl(yield source.read())) : new AsyncRecordBatchStreamReader(new AsyncRecordBatchStreamReaderImpl((function() { + return __asyncGenerator(this, arguments, function* () { + }); + })())); + }); +} +function fromFileHandle(source) { + return __awaiter(this, void 0, void 0, function* () { + const { size } = yield source.stat(); + const file = new AsyncRandomAccessFile(source, size); + if (size >= magicX2AndPadding && checkForMagicArrowString(yield file.readAt(0, magicLength + 7 & ~7))) { + return new AsyncRecordBatchFileReader(new AsyncRecordBatchFileReaderImpl(file)); + } + return new AsyncRecordBatchStreamReader(new AsyncRecordBatchStreamReaderImpl(file)); + }); +} +var flatbuffers35, RecordBatchReader, RecordBatchStreamReader, AsyncRecordBatchStreamReader, RecordBatchFileReader, AsyncRecordBatchFileReader, RecordBatchReaderImpl, RecordBatchStreamReaderImpl, AsyncRecordBatchStreamReaderImpl, RecordBatchFileReaderImpl, AsyncRecordBatchFileReaderImpl, RecordBatchJSONReaderImpl; +var init_reader = __esm({ + "node_modules/apache-arrow/ipc/reader.mjs"() { + init_tslib_es6(); + init_data(); + init_vector2(); + init_type2(); + init_enum(); + init_file(); + init_adapters(); + init_message2(); + init_stream(); + init_file2(); + init_vectorloader(); + init_recordbatch2(); + init_interfaces(); + init_message3(); + init_compat(); + init_registry(); + init_bigint(); + flatbuffers35 = __toESM(require_flatbuffers(), 1); + init_constants(); + RecordBatchReader = class _RecordBatchReader extends ReadableInterop { + constructor(impl) { + super(); + this._impl = impl; } - /** - * The Append Block operation commits a new block of data to the end of an existing append blob. The - * Append Block operation is permitted only if the blob was created with x-ms-blob-type set to - * AppendBlob. Append Block is supported only on version 2015-02-21 version or later. - * @param contentLength The length of the request. - * @param body Initial data - * @param options The options parameters. - */ - appendBlock(contentLength, body, options) { - return this.client.sendOperationRequest({ contentLength, body, options }, appendBlockOperationSpec); + get closed() { + return this._impl.closed; } - /** - * The Append Block operation commits a new block of data to the end of an existing append blob where - * the contents are read from a source url. The Append Block operation is permitted only if the blob - * was created with x-ms-blob-type set to AppendBlob. Append Block is supported only on version - * 2015-02-21 version or later. - * @param sourceUrl Specify a URL to the copy source. - * @param contentLength The length of the request. - * @param options The options parameters. - */ - appendBlockFromUrl(sourceUrl, contentLength, options) { - return this.client.sendOperationRequest({ sourceUrl, contentLength, options }, appendBlockFromUrlOperationSpec); + get schema() { + return this._impl.schema; } - /** - * The Seal operation seals the Append Blob to make it read-only. Seal is supported only on version - * 2019-12-12 version or later. - * @param options The options parameters. - */ - seal(options) { - return this.client.sendOperationRequest({ options }, sealOperationSpec); + get autoDestroy() { + return this._impl.autoDestroy; + } + get dictionaries() { + return this._impl.dictionaries; + } + get numDictionaries() { + return this._impl.numDictionaries; + } + get numRecordBatches() { + return this._impl.numRecordBatches; + } + get footer() { + return this._impl.isFile() ? this._impl.footer : null; + } + isSync() { + return this._impl.isSync(); + } + isAsync() { + return this._impl.isAsync(); + } + isFile() { + return this._impl.isFile(); + } + isStream() { + return this._impl.isStream(); + } + next() { + return this._impl.next(); + } + throw(value) { + return this._impl.throw(value); + } + return(value) { + return this._impl.return(value); + } + cancel() { + return this._impl.cancel(); + } + reset(schema) { + this._impl.reset(schema); + this._DOMStream = void 0; + this._nodeStream = void 0; + return this; + } + open(options) { + const opening = this._impl.open(options); + return isPromise(opening) ? opening.then(() => this) : this; + } + readRecordBatch(index2) { + return this._impl.isFile() ? this._impl.readRecordBatch(index2) : null; + } + [Symbol.iterator]() { + return this._impl[Symbol.iterator](); + } + [Symbol.asyncIterator]() { + return this._impl[Symbol.asyncIterator](); + } + toDOMStream() { + return adapters_default.toDOMStream(this.isSync() ? { [Symbol.iterator]: () => this } : { [Symbol.asyncIterator]: () => this }); + } + toNodeStream() { + return adapters_default.toNodeStream(this.isSync() ? { [Symbol.iterator]: () => this } : { [Symbol.asyncIterator]: () => this }, { objectMode: true }); + } + /** @nocollapse */ + // @ts-ignore + static throughNode(options) { + throw new Error(`"throughNode" not available in this environment`); + } + /** @nocollapse */ + static throughDOM(writableStrategy, readableStrategy) { + throw new Error(`"throughDOM" not available in this environment`); + } + /** @nocollapse */ + static from(source) { + if (source instanceof _RecordBatchReader) { + return source; + } else if (isArrowJSON(source)) { + return fromArrowJSON(source); + } else if (isFileHandle(source)) { + return fromFileHandle(source); + } else if (isPromise(source)) { + return (() => __awaiter(this, void 0, void 0, function* () { + return yield _RecordBatchReader.from(yield source); + }))(); + } else if (isFetchResponse(source) || isReadableDOMStream(source) || isReadableNodeStream(source) || isAsyncIterable(source)) { + return fromAsyncByteStream(new AsyncByteStream(source)); + } + return fromByteStream(new ByteStream(source)); + } + /** @nocollapse */ + static readAll(source) { + if (source instanceof _RecordBatchReader) { + return source.isSync() ? readAllSync(source) : readAllAsync(source); + } else if (isArrowJSON(source) || ArrayBuffer.isView(source) || isIterable(source) || isIteratorResult(source)) { + return readAllSync(source); + } + return readAllAsync(source); + } + }; + RecordBatchStreamReader = class extends RecordBatchReader { + constructor(_impl) { + super(_impl); + this._impl = _impl; + } + readAll() { + return [...this]; + } + [Symbol.iterator]() { + return this._impl[Symbol.iterator](); + } + [Symbol.asyncIterator]() { + return __asyncGenerator(this, arguments, function* _a6() { + yield __await(yield* __asyncDelegator(__asyncValues(this[Symbol.iterator]()))); + }); } }; - exports2.AppendBlobImpl = AppendBlobImpl; - var xmlSerializer = coreClient.createSerializer( - Mappers, - /* isXml */ - true - ); - var createOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.AppendBlobCreateHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.AppendBlobCreateExceptionHeaders + AsyncRecordBatchStreamReader = class extends RecordBatchReader { + constructor(_impl) { + super(_impl); + this._impl = _impl; + } + readAll() { + return __awaiter(this, void 0, void 0, function* () { + var _a6, e_1, _b2, _c2; + const batches = new Array(); + try { + for (var _d2 = true, _e2 = __asyncValues(this), _f2; _f2 = yield _e2.next(), _a6 = _f2.done, !_a6; _d2 = true) { + _c2 = _f2.value; + _d2 = false; + const batch = _c2; + batches.push(batch); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d2 && !_a6 && (_b2 = _e2.return)) yield _b2.call(_e2); + } finally { + if (e_1) throw e_1.error; + } + } + return batches; + }); + } + [Symbol.iterator]() { + throw new Error(`AsyncRecordBatchStreamReader is not Iterable`); + } + [Symbol.asyncIterator]() { + return this._impl[Symbol.asyncIterator](); + } + }; + RecordBatchFileReader = class extends RecordBatchStreamReader { + constructor(_impl) { + super(_impl); + this._impl = _impl; + } + }; + AsyncRecordBatchFileReader = class extends AsyncRecordBatchStreamReader { + constructor(_impl) { + super(_impl); + this._impl = _impl; + } + }; + RecordBatchReaderImpl = class { + get numDictionaries() { + return this._dictionaryIndex; + } + get numRecordBatches() { + return this._recordBatchIndex; + } + constructor(dictionaries = /* @__PURE__ */ new Map()) { + this.closed = false; + this.autoDestroy = true; + this._dictionaryIndex = 0; + this._recordBatchIndex = 0; + this.dictionaries = dictionaries; + } + isSync() { + return false; + } + isAsync() { + return false; + } + isFile() { + return false; + } + isStream() { + return false; + } + reset(schema) { + this._dictionaryIndex = 0; + this._recordBatchIndex = 0; + this.schema = schema; + this.dictionaries = /* @__PURE__ */ new Map(); + return this; + } + _loadRecordBatch(header, body, messageMetadata) { + let children; + if (header.compression != null) { + const codec = compressionRegistry.get(header.compression.type); + if ((codec === null || codec === void 0 ? void 0 : codec.decode) && typeof codec.decode === "function") { + const { decommpressedBody, buffers } = this._decompressBuffers(header, body, codec); + children = this._loadCompressedVectors(header, decommpressedBody, this.schema.fields); + header = new RecordBatch2(header.length, header.nodes, buffers, null); + } else { + throw new Error("Record batch is compressed but codec not found"); + } + } else { + children = this._loadVectors(header, body, this.schema.fields); + } + const data = makeData({ type: new Struct(this.schema.fields), length: header.length, children }); + return new RecordBatch3(this.schema, data, messageMetadata); + } + _loadDictionaryBatch(header, body) { + const { id, isDelta } = header; + const { dictionaries, schema } = this; + const dictionary = dictionaries.get(id); + const type = schema.dictionaries.get(id); + let data; + if (header.data.compression != null) { + const codec = compressionRegistry.get(header.data.compression.type); + if ((codec === null || codec === void 0 ? void 0 : codec.decode) && typeof codec.decode === "function") { + const { decommpressedBody, buffers } = this._decompressBuffers(header.data, body, codec); + data = this._loadCompressedVectors(header.data, decommpressedBody, [type]); + header = new DictionaryBatch2(new RecordBatch2(header.data.length, header.data.nodes, buffers, null, header.data.variadicBufferCounts), id, isDelta); + } else { + throw new Error("Dictionary batch is compressed but codec not found"); + } + } else { + data = this._loadVectors(header.data, body, [type]); } - }, - queryParameters: [Parameters.timeoutInSeconds], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.contentLength, - Parameters.metadata, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.blobCacheControl, - Parameters.blobContentType, - Parameters.blobContentMD5, - Parameters.blobContentEncoding, - Parameters.blobContentLanguage, - Parameters.blobContentDisposition, - Parameters.immutabilityPolicyExpiry, - Parameters.immutabilityPolicyMode, - Parameters.encryptionScope, - Parameters.blobTagsString, - Parameters.legalHold1, - Parameters.blobType1 - ], - isXML: true, - serializer: xmlSerializer + return (dictionary && isDelta ? dictionary.concat(new Vector(data)) : new Vector(data)).memoize(); + } + _loadVectors(header, body, types2) { + return new VectorLoader(body, header.nodes, header.buffers, this.dictionaries, this.schema.metadataVersion, header.variadicBufferCounts).visitMany(types2); + } + _loadCompressedVectors(header, body, types2) { + return new CompressedVectorLoader(body, header.nodes, header.buffers, this.dictionaries, this.schema.metadataVersion, header.variadicBufferCounts).visitMany(types2); + } + _decompressBuffers(header, body, codec) { + const decompressedBuffers = []; + const newBufferRegions = []; + let currentOffset = 0; + for (const { offset, length } of header.buffers) { + if (length === 0) { + decompressedBuffers.push(new Uint8Array(0)); + newBufferRegions.push(new BufferRegion(currentOffset, 0)); + continue; + } + const byteBuf = new flatbuffers35.ByteBuffer(body.subarray(offset, offset + length)); + const uncompressedLenth = bigIntToNumber(byteBuf.readInt64(0)); + const bytes = byteBuf.bytes().subarray(COMPRESS_LENGTH_PREFIX); + const decompressed = uncompressedLenth === LENGTH_NO_COMPRESSED_DATA ? bytes : codec.decode(bytes); + decompressedBuffers.push(decompressed); + const padding = (currentOffset + 7 & ~7) - currentOffset; + currentOffset += padding; + newBufferRegions.push(new BufferRegion(currentOffset, decompressed.length)); + currentOffset += decompressed.length; + } + return { + decommpressedBody: decompressedBuffers, + buffers: newBufferRegions + }; + } }; - var appendBlockOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.AppendBlobAppendBlockHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.AppendBlobAppendBlockExceptionHeaders + RecordBatchStreamReaderImpl = class extends RecordBatchReaderImpl { + constructor(source, dictionaries) { + super(dictionaries); + this._reader = !isArrowJSON(source) ? new MessageReader(this._handle = source) : new JSONMessageReader(this._handle = source); + } + isSync() { + return true; + } + isStream() { + return true; + } + [Symbol.iterator]() { + return this; + } + cancel() { + if (!this.closed && (this.closed = true)) { + this.reset()._reader.return(); + this._reader = null; + this.dictionaries = null; } - }, - requestBody: Parameters.body1, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp22], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.contentLength, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.encryptionScope, - Parameters.transactionalContentMD5, - Parameters.transactionalContentCrc64, - Parameters.contentType1, - Parameters.accept2, - Parameters.maxSize, - Parameters.appendPosition - ], - isXML: true, - contentType: "application/xml; charset=utf-8", - mediaType: "binary", - serializer: xmlSerializer + } + open(options) { + if (!this.closed) { + this.autoDestroy = shouldAutoDestroy(this, options); + if (!(this.schema || (this.schema = this._reader.readSchema()))) { + this.cancel(); + } + } + return this; + } + throw(value) { + if (!this.closed && this.autoDestroy && (this.closed = true)) { + return this.reset()._reader.throw(value); + } + return ITERATOR_DONE; + } + return(value) { + if (!this.closed && this.autoDestroy && (this.closed = true)) { + return this.reset()._reader.return(value); + } + return ITERATOR_DONE; + } + next() { + if (this.closed) { + return ITERATOR_DONE; + } + let message; + const { _reader: reader } = this; + while (message = this._readNextMessageAndValidate()) { + if (message.isSchema()) { + this.reset(message.header()); + } else if (message.isRecordBatch()) { + this._recordBatchIndex++; + const header = message.header(); + const buffer = reader.readMessageBody(message.bodyLength); + const recordBatch = this._loadRecordBatch(header, buffer, message.metadata); + return { done: false, value: recordBatch }; + } else if (message.isDictionaryBatch()) { + this._dictionaryIndex++; + const header = message.header(); + const buffer = reader.readMessageBody(message.bodyLength); + const vector = this._loadDictionaryBatch(header, buffer); + this.dictionaries.set(header.id, vector); + } + } + if (this.schema && this._recordBatchIndex === 0) { + this._recordBatchIndex++; + return { done: false, value: new _InternalEmptyPlaceholderRecordBatch(this.schema) }; + } + return this.return(); + } + _readNextMessageAndValidate(type) { + return this._reader.readMessage(type); + } }; - var appendBlockFromUrlOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.AppendBlobAppendBlockFromUrlHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.AppendBlobAppendBlockFromUrlExceptionHeaders + AsyncRecordBatchStreamReaderImpl = class extends RecordBatchReaderImpl { + constructor(source, dictionaries) { + super(dictionaries); + this._reader = new AsyncMessageReader(this._handle = source); + } + isAsync() { + return true; + } + isStream() { + return true; + } + [Symbol.asyncIterator]() { + return this; + } + cancel() { + return __awaiter(this, void 0, void 0, function* () { + if (!this.closed && (this.closed = true)) { + yield this.reset()._reader.return(); + this._reader = null; + this.dictionaries = null; + } + }); + } + open(options) { + return __awaiter(this, void 0, void 0, function* () { + if (!this.closed) { + this.autoDestroy = shouldAutoDestroy(this, options); + if (!(this.schema || (this.schema = yield this._reader.readSchema()))) { + yield this.cancel(); + } + } + return this; + }); + } + throw(value) { + return __awaiter(this, void 0, void 0, function* () { + if (!this.closed && this.autoDestroy && (this.closed = true)) { + return yield this.reset()._reader.throw(value); + } + return ITERATOR_DONE; + }); + } + return(value) { + return __awaiter(this, void 0, void 0, function* () { + if (!this.closed && this.autoDestroy && (this.closed = true)) { + return yield this.reset()._reader.return(value); + } + return ITERATOR_DONE; + }); + } + next() { + return __awaiter(this, void 0, void 0, function* () { + if (this.closed) { + return ITERATOR_DONE; + } + let message; + const { _reader: reader } = this; + while (message = yield this._readNextMessageAndValidate()) { + if (message.isSchema()) { + yield this.reset(message.header()); + } else if (message.isRecordBatch()) { + this._recordBatchIndex++; + const header = message.header(); + const buffer = yield reader.readMessageBody(message.bodyLength); + const recordBatch = this._loadRecordBatch(header, buffer, message.metadata); + return { done: false, value: recordBatch }; + } else if (message.isDictionaryBatch()) { + this._dictionaryIndex++; + const header = message.header(); + const buffer = yield reader.readMessageBody(message.bodyLength); + const vector = this._loadDictionaryBatch(header, buffer); + this.dictionaries.set(header.id, vector); + } + } + if (this.schema && this._recordBatchIndex === 0) { + this._recordBatchIndex++; + return { done: false, value: new _InternalEmptyPlaceholderRecordBatch(this.schema) }; + } + return yield this.return(); + }); + } + _readNextMessageAndValidate(type) { + return __awaiter(this, void 0, void 0, function* () { + return yield this._reader.readMessage(type); + }); + } + }; + RecordBatchFileReaderImpl = class extends RecordBatchStreamReaderImpl { + get footer() { + return this._footer; + } + get numDictionaries() { + return this._footer ? this._footer.numDictionaries : 0; + } + get numRecordBatches() { + return this._footer ? this._footer.numRecordBatches : 0; + } + constructor(source, dictionaries) { + super(source instanceof RandomAccessFile ? source : new RandomAccessFile(source), dictionaries); + } + isSync() { + return true; + } + isFile() { + return true; + } + open(options) { + if (!this.closed && !this._footer) { + this.schema = (this._footer = this._readFooter()).schema; + for (const block of this._footer.dictionaryBatches()) { + block && this._readDictionaryBatch(this._dictionaryIndex++); + } } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp22], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.contentLength, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.encryptionScope, - Parameters.sourceIfModifiedSince, - Parameters.sourceIfUnmodifiedSince, - Parameters.sourceIfMatch, - Parameters.sourceIfNoneMatch, - Parameters.sourceContentMD5, - Parameters.copySourceAuthorization, - Parameters.fileRequestIntent, - Parameters.transactionalContentMD5, - Parameters.sourceUrl, - Parameters.sourceContentCrc64, - Parameters.maxSize, - Parameters.appendPosition, - Parameters.sourceRange1 - ], - isXML: true, - serializer: xmlSerializer + return super.open(options); + } + readRecordBatch(index2) { + var _a6; + if (this.closed) { + return null; + } + if (!this._footer) { + this.open(); + } + const block = (_a6 = this._footer) === null || _a6 === void 0 ? void 0 : _a6.getRecordBatch(index2); + if (block && this._handle.seek(block.offset)) { + const message = this._reader.readMessage(MessageHeader.RecordBatch); + if (message === null || message === void 0 ? void 0 : message.isRecordBatch()) { + const header = message.header(); + const buffer = this._reader.readMessageBody(message.bodyLength); + const recordBatch = this._loadRecordBatch(header, buffer, message.metadata); + return recordBatch; + } + } + return null; + } + _readDictionaryBatch(index2) { + var _a6; + const block = (_a6 = this._footer) === null || _a6 === void 0 ? void 0 : _a6.getDictionaryBatch(index2); + if (block && this._handle.seek(block.offset)) { + const message = this._reader.readMessage(MessageHeader.DictionaryBatch); + if (message === null || message === void 0 ? void 0 : message.isDictionaryBatch()) { + const header = message.header(); + const buffer = this._reader.readMessageBody(message.bodyLength); + const vector = this._loadDictionaryBatch(header, buffer); + this.dictionaries.set(header.id, vector); + } + } + } + _readFooter() { + const { _handle } = this; + const offset = _handle.size - magicAndPadding; + const length = _handle.readInt32(offset); + const buffer = _handle.readAt(offset - length, length); + return Footer_.decode(buffer); + } + _readNextMessageAndValidate(type) { + var _a6; + if (!this._footer) { + this.open(); + } + if (this._footer && this._recordBatchIndex < this.numRecordBatches) { + const block = (_a6 = this._footer) === null || _a6 === void 0 ? void 0 : _a6.getRecordBatch(this._recordBatchIndex); + if (block && this._handle.seek(block.offset)) { + return this._reader.readMessage(type); + } + } + return null; + } }; - var sealOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 200: { - headersMapper: Mappers.AppendBlobSealHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.AppendBlobSealExceptionHeaders + AsyncRecordBatchFileReaderImpl = class extends AsyncRecordBatchStreamReaderImpl { + get footer() { + return this._footer; + } + get numDictionaries() { + return this._footer ? this._footer.numDictionaries : 0; + } + get numRecordBatches() { + return this._footer ? this._footer.numRecordBatches : 0; + } + constructor(source, ...rest) { + const byteLength = typeof rest[0] !== "number" ? rest.shift() : void 0; + const dictionaries = rest[0] instanceof Map ? rest.shift() : void 0; + super(source instanceof AsyncRandomAccessFile ? source : new AsyncRandomAccessFile(source, byteLength), dictionaries); + } + isFile() { + return true; + } + isAsync() { + return true; + } + open(options) { + const _super = Object.create(null, { + open: { get: () => super.open } + }); + return __awaiter(this, void 0, void 0, function* () { + if (!this.closed && !this._footer) { + this.schema = (this._footer = yield this._readFooter()).schema; + for (const block of this._footer.dictionaryBatches()) { + block && (yield this._readDictionaryBatch(this._dictionaryIndex++)); + } + } + return yield _super.open.call(this, options); + }); + } + readRecordBatch(index2) { + return __awaiter(this, void 0, void 0, function* () { + var _a6; + if (this.closed) { + return null; + } + if (!this._footer) { + yield this.open(); + } + const block = (_a6 = this._footer) === null || _a6 === void 0 ? void 0 : _a6.getRecordBatch(index2); + if (block && (yield this._handle.seek(block.offset))) { + const message = yield this._reader.readMessage(MessageHeader.RecordBatch); + if (message === null || message === void 0 ? void 0 : message.isRecordBatch()) { + const header = message.header(); + const buffer = yield this._reader.readMessageBody(message.bodyLength); + const recordBatch = this._loadRecordBatch(header, buffer, message.metadata); + return recordBatch; + } + } + return null; + }); + } + _readDictionaryBatch(index2) { + return __awaiter(this, void 0, void 0, function* () { + var _a6; + const block = (_a6 = this._footer) === null || _a6 === void 0 ? void 0 : _a6.getDictionaryBatch(index2); + if (block && (yield this._handle.seek(block.offset))) { + const message = yield this._reader.readMessage(MessageHeader.DictionaryBatch); + if (message === null || message === void 0 ? void 0 : message.isDictionaryBatch()) { + const header = message.header(); + const buffer = yield this._reader.readMessageBody(message.bodyLength); + const vector = this._loadDictionaryBatch(header, buffer); + this.dictionaries.set(header.id, vector); + } + } + }); + } + _readFooter() { + return __awaiter(this, void 0, void 0, function* () { + const { _handle } = this; + _handle._pending && (yield _handle._pending); + const offset = _handle.size - magicAndPadding; + const length = yield _handle.readInt32(offset); + const buffer = yield _handle.readAt(offset - length, length); + return Footer_.decode(buffer); + }); + } + _readNextMessageAndValidate(type) { + return __awaiter(this, void 0, void 0, function* () { + if (!this._footer) { + yield this.open(); + } + if (this._footer && this._recordBatchIndex < this.numRecordBatches) { + const block = this._footer.getRecordBatch(this._recordBatchIndex); + if (block && (yield this._handle.seek(block.offset))) { + return yield this._reader.readMessage(type); + } + } + return null; + }); + } + }; + RecordBatchJSONReaderImpl = class extends RecordBatchStreamReaderImpl { + constructor(source, dictionaries) { + super(source, dictionaries); + } + _loadVectors(header, body, types2) { + return new JSONVectorLoader(body, header.nodes, header.buffers, this.dictionaries, this.schema.metadataVersion, header.variadicBufferCounts).visitMany(types2); + } + }; + } +}); + +// node_modules/apache-arrow/visitor/vectorassembler.mjs +function addBuffer(values) { + const byteLength = values.byteLength + 7 & ~7; + this.buffers.push(values); + this.bufferRegions.push(new BufferRegion(this._byteLength, byteLength)); + this._byteLength += byteLength; + return this; +} +function assembleUnion(data) { + var _a6; + const { type, length, typeIds, valueOffsets } = data; + addBuffer.call(this, typeIds); + if (type.mode === UnionMode.Sparse) { + return assembleNestedVector.call(this, data); + } else if (type.mode === UnionMode.Dense) { + if (data.offset <= 0) { + addBuffer.call(this, valueOffsets); + return assembleNestedVector.call(this, data); + } else { + const shiftedOffsets = new Int32Array(length); + const childOffsets = /* @__PURE__ */ Object.create(null); + const childLengths = /* @__PURE__ */ Object.create(null); + for (let typeId, shift, index2 = -1; ++index2 < length; ) { + if ((typeId = typeIds[index2]) === void 0) { + continue; + } + if ((shift = childOffsets[typeId]) === void 0) { + shift = childOffsets[typeId] = valueOffsets[index2]; + } + shiftedOffsets[index2] = valueOffsets[index2] - shift; + childLengths[typeId] = ((_a6 = childLengths[typeId]) !== null && _a6 !== void 0 ? _a6 : 0) + 1; + } + addBuffer.call(this, shiftedOffsets); + this.visitMany(data.children.map((child, childIndex) => { + const typeId = type.typeIds[childIndex]; + const childOffset = childOffsets[typeId]; + const childLength = childLengths[typeId]; + return child.slice(childOffset, Math.min(length, childLength)); + })); + } + } + return this; +} +function assembleBoolVector(data) { + let values; + if (data.nullCount >= data.length) { + return addBuffer.call(this, new Uint8Array(data.length + 7 >> 3)); + } else if ((values = data.values) instanceof Uint8Array) { + return addBuffer.call(this, truncateBitmap(data.offset, data.length, values)); + } + return addBuffer.call(this, packBools(data.values)); +} +function assembleFlatVector(data) { + return addBuffer.call(this, data.values.subarray(0, data.length * data.stride)); +} +function assembleFlatListVector(data) { + const { length, values, valueOffsets } = data; + const begin = bigIntToNumber(valueOffsets[0]); + const end = bigIntToNumber(valueOffsets[length]); + const byteLength = Math.min(end - begin, values.byteLength - begin); + addBuffer.call(this, rebaseValueOffsets(-begin, length + 1, valueOffsets)); + addBuffer.call(this, values.subarray(begin, begin + byteLength)); + return this; +} +function assembleBinaryViewVector(data) { + const { offset, length, stride, values, variadicBuffers = [] } = data; + if (!values) { + throw new Error("BinaryView data is missing view buffer"); + } + const start = offset * stride; + const end = start + length * stride; + addBuffer.call(this, values.subarray(start, end)); + for (const buffer of variadicBuffers) { + addBuffer.call(this, buffer); + } + this._variadicBufferCounts.push(variadicBuffers.length); + return this; +} +function assembleListVector(data) { + const { length, valueOffsets } = data; + if (valueOffsets) { + const begin = bigIntToNumber(valueOffsets[0]); + const end = bigIntToNumber(valueOffsets[length]); + addBuffer.call(this, rebaseValueOffsets(-begin, length + 1, valueOffsets)); + return this.visit(data.children[0].slice(begin, end - begin)); + } + return this.visit(data.children[0]); +} +function assembleNestedVector(data) { + return this.visitMany(data.type.children.map((_2, i) => data.children[i]).filter(Boolean))[0]; +} +var VectorAssembler; +var init_vectorassembler = __esm({ + "node_modules/apache-arrow/visitor/vectorassembler.mjs"() { + init_vector2(); + init_visitor(); + init_enum(); + init_recordbatch2(); + init_buffer(); + init_bit(); + init_message2(); + init_type2(); + init_bigint(); + VectorAssembler = class _VectorAssembler extends Visitor { + /** @nocollapse */ + static assemble(...args) { + const unwrap = (nodes) => nodes.flatMap((node) => Array.isArray(node) ? unwrap(node) : node instanceof RecordBatch3 ? node.data.children : node.data); + const assembler = new _VectorAssembler(); + assembler.visitMany(unwrap(args)); + return assembler; + } + constructor() { + super(); + this._byteLength = 0; + this._nodes = []; + this._buffers = []; + this._bufferRegions = []; + this._variadicBufferCounts = []; + } + visit(data) { + if (data instanceof Vector) { + this.visitMany(data.data); + return this; + } + const { type } = data; + if (!DataType.isDictionary(type)) { + const { length } = data; + if (length > 2147483647) { + throw new RangeError("Cannot write arrays larger than 2^31 - 1 in length"); + } + if (DataType.isUnion(type)) { + this.nodes.push(new FieldNode2(length, 0)); + } else { + const { nullCount } = data; + if (!DataType.isNull(type)) { + addBuffer.call(this, nullCount <= 0 ? new Uint8Array(0) : truncateBitmap(data.offset, length, data.nullBitmap)); + } + this.nodes.push(new FieldNode2(length, nullCount)); + } } - }, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp23], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.appendPosition - ], - isXML: true, - serializer: xmlSerializer + return super.visit(data); + } + visitNull(_null) { + return this; + } + visitDictionary(data) { + return this.visit(data.clone(data.type.indices)); + } + get nodes() { + return this._nodes; + } + get buffers() { + return this._buffers; + } + get byteLength() { + return this._byteLength; + } + get bufferRegions() { + return this._bufferRegions; + } + get variadicBufferCounts() { + return this._variadicBufferCounts; + } }; + VectorAssembler.prototype.visitBool = assembleBoolVector; + VectorAssembler.prototype.visitInt = assembleFlatVector; + VectorAssembler.prototype.visitFloat = assembleFlatVector; + VectorAssembler.prototype.visitUtf8 = assembleFlatListVector; + VectorAssembler.prototype.visitLargeUtf8 = assembleFlatListVector; + VectorAssembler.prototype.visitUtf8View = assembleBinaryViewVector; + VectorAssembler.prototype.visitBinary = assembleFlatListVector; + VectorAssembler.prototype.visitLargeBinary = assembleFlatListVector; + VectorAssembler.prototype.visitBinaryView = assembleBinaryViewVector; + VectorAssembler.prototype.visitFixedSizeBinary = assembleFlatVector; + VectorAssembler.prototype.visitDate = assembleFlatVector; + VectorAssembler.prototype.visitTimestamp = assembleFlatVector; + VectorAssembler.prototype.visitTime = assembleFlatVector; + VectorAssembler.prototype.visitDecimal = assembleFlatVector; + VectorAssembler.prototype.visitList = assembleListVector; + VectorAssembler.prototype.visitLargeList = assembleListVector; + VectorAssembler.prototype.visitStruct = assembleNestedVector; + VectorAssembler.prototype.visitUnion = assembleUnion; + VectorAssembler.prototype.visitInterval = assembleFlatVector; + VectorAssembler.prototype.visitDuration = assembleFlatVector; + VectorAssembler.prototype.visitFixedSizeList = assembleListVector; + VectorAssembler.prototype.visitMap = assembleListVector; } }); -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/blockBlob.js -var require_blockBlob = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/blockBlob.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BlockBlobImpl = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var coreClient = tslib_1.__importStar(require_commonjs8()); - var Mappers = tslib_1.__importStar(require_mappers()); - var Parameters = tslib_1.__importStar(require_parameters()); - var BlockBlobImpl = class { - client; - /** - * Initialize a new instance of the class BlockBlob class. - * @param client Reference to the service client - */ - constructor(client) { - this.client = client; +// node_modules/apache-arrow/visitor/jsontypeassembler.mjs +var JSONTypeAssembler; +var init_jsontypeassembler = __esm({ + "node_modules/apache-arrow/visitor/jsontypeassembler.mjs"() { + init_visitor(); + init_type(); + init_enum(); + JSONTypeAssembler = class extends Visitor { + visit(node) { + return node == null ? void 0 : super.visit(node); } - /** - * The Upload Block Blob operation updates the content of an existing block blob. Updating an existing - * block blob overwrites any existing metadata on the blob. Partial updates are not supported with Put - * Blob; the content of the existing blob is overwritten with the content of the new blob. To perform a - * partial update of the content of a block blob, use the Put Block List operation. - * @param contentLength The length of the request. - * @param body Initial data - * @param options The options parameters. - */ - upload(contentLength, body, options) { - return this.client.sendOperationRequest({ contentLength, body, options }, uploadOperationSpec); + visitNull({ typeId }) { + return { "name": Type[typeId].toLowerCase() }; } - /** - * The Put Blob from URL operation creates a new Block Blob where the contents of the blob are read - * from a given URL. This API is supported beginning with the 2020-04-08 version. Partial updates are - * not supported with Put Blob from URL; the content of an existing blob is overwritten with the - * content of the new blob. To perform partial updates to a block blob’s contents using a source URL, - * use the Put Block from URL API in conjunction with Put Block List. - * @param contentLength The length of the request. - * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to - * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would - * appear in a request URI. The source blob must either be public or must be authenticated via a shared - * access signature. - * @param options The options parameters. - */ - putBlobFromUrl(contentLength, copySource, options) { - return this.client.sendOperationRequest({ contentLength, copySource, options }, putBlobFromUrlOperationSpec); + visitInt({ typeId, bitWidth, isSigned }) { + return { "name": Type[typeId].toLowerCase(), "bitWidth": bitWidth, "isSigned": isSigned }; } - /** - * The Stage Block operation creates a new block to be committed as part of a blob - * @param blockId A valid Base64 string value that identifies the block. Prior to encoding, the string - * must be less than or equal to 64 bytes in size. For a given blob, the length of the value specified - * for the blockid parameter must be the same size for each block. - * @param contentLength The length of the request. - * @param body Initial data - * @param options The options parameters. - */ - stageBlock(blockId, contentLength, body, options) { - return this.client.sendOperationRequest({ blockId, contentLength, body, options }, stageBlockOperationSpec); + visitFloat({ typeId, precision }) { + return { "name": Type[typeId].toLowerCase(), "precision": Precision[precision] }; } - /** - * The Stage Block operation creates a new block to be committed as part of a blob where the contents - * are read from a URL. - * @param blockId A valid Base64 string value that identifies the block. Prior to encoding, the string - * must be less than or equal to 64 bytes in size. For a given blob, the length of the value specified - * for the blockid parameter must be the same size for each block. - * @param contentLength The length of the request. - * @param sourceUrl Specify a URL to the copy source. - * @param options The options parameters. - */ - stageBlockFromURL(blockId, contentLength, sourceUrl, options) { - return this.client.sendOperationRequest({ blockId, contentLength, sourceUrl, options }, stageBlockFromURLOperationSpec); + visitBinary({ typeId }) { + return { "name": Type[typeId].toLowerCase() }; } - /** - * The Commit Block List operation writes a blob by specifying the list of block IDs that make up the - * blob. In order to be written as part of a blob, a block must have been successfully written to the - * server in a prior Put Block operation. You can call Put Block List to update a blob by uploading - * only those blocks that have changed, then committing the new and existing blocks together. You can - * do this by specifying whether to commit a block from the committed block list or from the - * uncommitted block list, or to commit the most recently uploaded version of the block, whichever list - * it may belong to. - * @param blocks Blob Blocks. - * @param options The options parameters. - */ - commitBlockList(blocks, options) { - return this.client.sendOperationRequest({ blocks, options }, commitBlockListOperationSpec); + visitLargeBinary({ typeId }) { + return { "name": Type[typeId].toLowerCase() }; } - /** - * The Get Block List operation retrieves the list of blocks that have been uploaded as part of a block - * blob - * @param listType Specifies whether to return the list of committed blocks, the list of uncommitted - * blocks, or both lists together. - * @param options The options parameters. - */ - getBlockList(listType, options) { - return this.client.sendOperationRequest({ listType, options }, getBlockListOperationSpec); + visitBinaryView({ typeId }) { + return { "name": Type[typeId].toLowerCase() }; + } + visitBool({ typeId }) { + return { "name": Type[typeId].toLowerCase() }; + } + visitUtf8({ typeId }) { + return { "name": Type[typeId].toLowerCase() }; + } + visitLargeUtf8({ typeId }) { + return { "name": Type[typeId].toLowerCase() }; + } + visitUtf8View({ typeId }) { + return { "name": Type[typeId].toLowerCase() }; + } + visitDecimal({ typeId, scale, precision, bitWidth }) { + return { "name": Type[typeId].toLowerCase(), "scale": scale, "precision": precision, "bitWidth": bitWidth }; + } + visitDate({ typeId, unit }) { + return { "name": Type[typeId].toLowerCase(), "unit": DateUnit[unit] }; + } + visitTime({ typeId, unit, bitWidth }) { + return { "name": Type[typeId].toLowerCase(), "unit": TimeUnit[unit], bitWidth }; + } + visitTimestamp({ typeId, timezone, unit }) { + return { "name": Type[typeId].toLowerCase(), "unit": TimeUnit[unit], timezone }; + } + visitInterval({ typeId, unit }) { + return { "name": Type[typeId].toLowerCase(), "unit": IntervalUnit[unit] }; + } + visitDuration({ typeId, unit }) { + return { "name": Type[typeId].toLocaleLowerCase(), "unit": TimeUnit[unit] }; + } + visitList({ typeId }) { + return { "name": Type[typeId].toLowerCase() }; + } + visitLargeList({ typeId }) { + return { "name": Type[typeId].toLowerCase() }; + } + visitStruct({ typeId }) { + return { "name": Type[typeId].toLowerCase() }; + } + visitUnion({ typeId, mode, typeIds }) { + return { + "name": Type[typeId].toLowerCase(), + "mode": UnionMode[mode].toUpperCase(), + "typeIds": [...typeIds] + }; + } + visitDictionary(node) { + return this.visit(node.dictionary); + } + visitFixedSizeBinary({ typeId, byteWidth }) { + return { "name": Type[typeId].toLowerCase(), "byteWidth": byteWidth }; + } + visitFixedSizeList({ typeId, listSize }) { + return { "name": Type[typeId].toLowerCase(), "listSize": listSize }; + } + visitMap({ typeId, keysSorted }) { + return { "name": Type[typeId].toLowerCase(), "keysSorted": keysSorted }; } }; - exports2.BlockBlobImpl = BlockBlobImpl; - var xmlSerializer = coreClient.createSerializer( - Mappers, - /* isXml */ - true - ); - var uploadOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.BlockBlobUploadHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlockBlobUploadExceptionHeaders + } +}); + +// node_modules/apache-arrow/visitor/jsonvectorassembler.mjs +function* binaryToString(vector) { + for (const octets of vector) { + yield octets.reduce((str, byte) => { + return `${str}${("0" + (byte & 255).toString(16)).slice(-2)}`; + }, "").toUpperCase(); + } +} +function* bigNumsToStrings(values, stride) { + const u32s = new Uint32Array(values.buffer, values.byteOffset, values.byteLength / Uint32Array.BYTES_PER_ELEMENT); + for (let i = -1, n = u32s.length / stride; ++i < n; ) { + yield `${BN.new(u32s.subarray((i + 0) * stride, (i + 1) * stride), false)}`; + } +} +function binaryViewDataToJSON(data, formatInlined) { + const INLINE_SIZE = 12; + const viewsData = data.values; + const dataView = new DataView(viewsData.buffer, viewsData.byteOffset, viewsData.byteLength); + const numViews = viewsData.byteLength / 16; + const bytesToHex = (bytes) => Array.from(bytes).map((b) => ("0" + (b & 255).toString(16)).slice(-2)).join("").toUpperCase(); + const parsedViews = Array.from({ length: numViews }, (_2, i) => { + const offset = i * 16; + const size = dataView.getInt32(offset, true); + return [offset, size]; + }).map(([offset, size]) => size > INLINE_SIZE ? { + "SIZE": size, + "PREFIX_HEX": bytesToHex(viewsData.subarray(offset + 4, offset + 8)), + "BUFFER_INDEX": dataView.getInt32(offset + 8, true), + "OFFSET": dataView.getInt32(offset + 12, true) + } : { + "SIZE": size, + "INLINED": formatInlined(viewsData.subarray(offset + 4, offset + 4 + size)) + }); + const uniqueBufferIndices = [...new Set(parsedViews.map((v) => v["BUFFER_INDEX"]).filter((idx) => idx !== void 0))]; + const variadicBuffers = uniqueBufferIndices.map((bufferIndex) => bytesToHex(data.variadicBuffers[bufferIndex])); + const bufferIndexMap = new Map(uniqueBufferIndices.map((bufferIndex, outputIndex) => [bufferIndex, outputIndex])); + const views = parsedViews.map((v) => v["BUFFER_INDEX"] !== void 0 ? Object.assign(Object.assign({}, v), { "BUFFER_INDEX": bufferIndexMap.get(v["BUFFER_INDEX"]) }) : v); + return { "VIEWS": views, "VARIADIC_DATA_BUFFERS": variadicBuffers }; +} +var JSONVectorAssembler; +var init_jsonvectorassembler = __esm({ + "node_modules/apache-arrow/visitor/jsonvectorassembler.mjs"() { + init_bn(); + init_vector2(); + init_visitor(); + init_enum(); + init_enum(); + init_bit(); + init_interval2(); + init_type2(); + JSONVectorAssembler = class _JSONVectorAssembler extends Visitor { + /** @nocollapse */ + static assemble(...batches) { + const assembler = new _JSONVectorAssembler(); + return batches.map(({ schema, data }) => { + return assembler.visitMany(schema.fields, data.children); + }); + } + visit({ name }, data) { + const { length } = data; + const { offset, nullCount, nullBitmap } = data; + const type = DataType.isDictionary(data.type) ? data.type.indices : data.type; + const buffers = Object.assign([], data.buffers, { [BufferType.VALIDITY]: void 0 }); + return Object.assign({ "name": name, "count": length, "VALIDITY": DataType.isNull(type) || DataType.isUnion(type) ? void 0 : nullCount <= 0 ? Array.from({ length }, () => 1) : [...new BitIterator(nullBitmap, offset, length, null, getBit)] }, super.visit(data.clone(type, offset, length, 0, buffers))); + } + visitNull() { + return {}; + } + visitBool({ values, offset, length }) { + return { "DATA": [...new BitIterator(values, offset, length, null, getBool2)] }; + } + visitInt(data) { + return { + "DATA": data.type.bitWidth < 64 ? [...data.values] : [...bigNumsToStrings(data.values, 2)] + }; + } + visitFloat(data) { + return { "DATA": [...data.values] }; + } + visitUtf8(data) { + return { "DATA": [...new Vector([data])], "OFFSET": [...data.valueOffsets] }; + } + visitLargeUtf8(data) { + return { "DATA": [...new Vector([data])], "OFFSET": [...bigNumsToStrings(data.valueOffsets, 2)] }; + } + visitBinary(data) { + return { "DATA": [...binaryToString(new Vector([data]))], "OFFSET": [...data.valueOffsets] }; + } + visitLargeBinary(data) { + return { "DATA": [...binaryToString(new Vector([data]))], "OFFSET": [...bigNumsToStrings(data.valueOffsets, 2)] }; + } + visitBinaryView(data) { + return binaryViewDataToJSON(data, (bytes) => Array.from(bytes).map((b) => ("0" + (b & 255).toString(16)).slice(-2)).join("").toUpperCase()); + } + visitUtf8View(data) { + return binaryViewDataToJSON(data, (bytes) => Array.from(bytes).map((b) => String.fromCodePoint(b)).join("")); + } + visitFixedSizeBinary(data) { + return { "DATA": [...binaryToString(new Vector([data]))] }; + } + visitDate(data) { + return { + "DATA": data.type.unit === DateUnit.DAY ? [...data.values] : [...bigNumsToStrings(data.values, 2)] + }; + } + visitTimestamp(data) { + return { "DATA": [...bigNumsToStrings(data.values, 2)] }; + } + visitTime(data) { + return { + "DATA": data.type.unit < TimeUnit.MICROSECOND ? [...data.values] : [...bigNumsToStrings(data.values, 2)] + }; + } + visitDecimal(data) { + return { "DATA": [...bigNumsToStrings(data.values, 4)] }; + } + visitList(data) { + return { + "OFFSET": [...data.valueOffsets], + "children": this.visitMany(data.type.children, data.children) + }; + } + visitLargeList(data) { + return { + "OFFSET": [...bigNumsToStrings(data.valueOffsets, 2)], + "children": this.visitMany(data.type.children, data.children) + }; + } + visitStruct(data) { + return { + "children": this.visitMany(data.type.children, data.children) + }; + } + visitUnion(data) { + return { + "TYPE_ID": [...data.typeIds], + "OFFSET": data.type.mode === UnionMode.Dense ? [...data.valueOffsets] : void 0, + "children": this.visitMany(data.type.children, data.children) + }; + } + visitInterval(data) { + switch (data.type.unit) { + case IntervalUnit.YEAR_MONTH: + return { "DATA": [...data.values] }; + case IntervalUnit.DAY_TIME: + return { "DATA": toIntervalDayTimeObjects(data.values) }; + case IntervalUnit.MONTH_DAY_NANO: + return { "DATA": toIntervalMonthDayNanoObjects(data.values, true) }; } - }, - requestBody: Parameters.body1, - queryParameters: [Parameters.timeoutInSeconds], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.contentLength, - Parameters.metadata, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.blobCacheControl, - Parameters.blobContentType, - Parameters.blobContentMD5, - Parameters.blobContentEncoding, - Parameters.blobContentLanguage, - Parameters.blobContentDisposition, - Parameters.immutabilityPolicyExpiry, - Parameters.immutabilityPolicyMode, - Parameters.encryptionScope, - Parameters.tier, - Parameters.blobTagsString, - Parameters.legalHold1, - Parameters.transactionalContentMD5, - Parameters.transactionalContentCrc64, - Parameters.contentType1, - Parameters.accept2, - Parameters.blobType2 - ], - isXML: true, - contentType: "application/xml; charset=utf-8", - mediaType: "binary", - serializer: xmlSerializer + } + visitDuration(data) { + return { "DATA": [...bigNumsToStrings(data.values, 2)] }; + } + visitFixedSizeList(data) { + return { + "children": this.visitMany(data.type.children, data.children) + }; + } + visitMap(data) { + return { + "OFFSET": [...data.valueOffsets], + "children": this.visitMany(data.type.children, data.children) + }; + } }; - var putBlobFromUrlOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.BlockBlobPutBlobFromUrlHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlockBlobPutBlobFromUrlExceptionHeaders + } +}); + +// node_modules/apache-arrow/ipc/writer.mjs +function writeAll(writer, input) { + let chunks = input; + if (input instanceof Table) { + chunks = input.batches; + writer.reset(void 0, input.schema); + } + for (const batch of chunks) { + writer.write(batch); + } + return writer.finish(); +} +function writeAllAsync(writer, batches) { + return __awaiter(this, void 0, void 0, function* () { + var _a6, batches_1, batches_1_1; + var _b2, e_1, _c2, _d2; + try { + for (_a6 = true, batches_1 = __asyncValues(batches); batches_1_1 = yield batches_1.next(), _b2 = batches_1_1.done, !_b2; _a6 = true) { + _d2 = batches_1_1.value; + _a6 = false; + const batch = _d2; + writer.write(batch); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_a6 && !_b2 && (_c2 = batches_1.return)) yield _c2.call(batches_1); + } finally { + if (e_1) throw e_1.error; + } + } + return writer.finish(); + }); +} +function fieldToJSON({ name, type, nullable }) { + const assembler = new JSONTypeAssembler(); + return { + "name": name, + "nullable": nullable, + "type": assembler.visit(type), + "children": (type.children || []).map((field) => fieldToJSON(field)), + "dictionary": !DataType.isDictionary(type) ? void 0 : { + "id": type.id, + "isOrdered": type.isOrdered, + "indexType": assembler.visit(type.indices) + } + }; +} +function dictionaryBatchToJSON(dictionary, id, isDelta = false) { + const [columns] = JSONVectorAssembler.assemble(new RecordBatch3({ [id]: dictionary })); + return JSON.stringify({ + "id": id, + "isDelta": isDelta, + "data": { + "count": dictionary.length, + "columns": columns + } + }, null, 2); +} +function recordBatchToJSON(records) { + const [columns] = JSONVectorAssembler.assemble(records); + return JSON.stringify({ + "count": records.numRows, + "columns": columns + }, null, 2); +} +var flatbuffers36, RecordBatchWriter, RecordBatchStreamWriter, RecordBatchFileWriter, RecordBatchJSONWriter; +var init_writer = __esm({ + "node_modules/apache-arrow/ipc/writer.mjs"() { + init_tslib_es6(); + init_table(); + init_message3(); + init_vector2(); + init_type2(); + init_message2(); + init_message2(); + init_file(); + init_enum(); + init_typecomparator(); + init_stream(); + init_vectorassembler(); + init_jsontypeassembler(); + init_jsonvectorassembler(); + init_buffer(); + init_recordbatch2(); + init_interfaces(); + init_compat(); + init_compression_type(); + init_registry(); + init_constants(); + flatbuffers36 = __toESM(require_flatbuffers(), 1); + RecordBatchWriter = class extends ReadableInterop { + /** @nocollapse */ + // @ts-ignore + static throughNode(options) { + throw new Error(`"throughNode" not available in this environment`); + } + /** @nocollapse */ + static throughDOM(writableStrategy, readableStrategy) { + throw new Error(`"throughDOM" not available in this environment`); + } + constructor(options) { + super(); + this._position = 0; + this._started = false; + this._compression = null; + this._sink = new AsyncByteQueue(); + this._schema = null; + this._dictionaryBlocks = []; + this._recordBatchBlocks = []; + this._seenDictionaries = /* @__PURE__ */ new Map(); + this._dictionaryDeltaOffsets = /* @__PURE__ */ new Map(); + isObject3(options) || (options = { autoDestroy: true, writeLegacyIpcFormat: false, compressionType: null }); + this._autoDestroy = typeof options.autoDestroy === "boolean" ? options.autoDestroy : true; + this._writeLegacyIpcFormat = typeof options.writeLegacyIpcFormat === "boolean" ? options.writeLegacyIpcFormat : false; + if (options.compressionType != null) { + if (this._writeLegacyIpcFormat) { + throw new Error("Legacy IPC format does not support columnar compression. Use modern IPC format (writeLegacyIpcFormat=false)."); + } + if (Object.values(CompressionType).includes(options.compressionType)) { + this._compression = new BodyCompression2(options.compressionType); + } else { + const validCompressionTypes = Object.values(CompressionType).filter((v) => typeof v === "string"); + throw new Error(`Unsupported compressionType: ${options.compressionType} Available types: ${validCompressionTypes.join(", ")}`); + } + } else { + this._compression = null; } - }, - queryParameters: [Parameters.timeoutInSeconds], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.contentLength, - Parameters.metadata, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.blobCacheControl, - Parameters.blobContentType, - Parameters.blobContentMD5, - Parameters.blobContentEncoding, - Parameters.blobContentLanguage, - Parameters.blobContentDisposition, - Parameters.encryptionScope, - Parameters.tier, - Parameters.sourceIfModifiedSince, - Parameters.sourceIfUnmodifiedSince, - Parameters.sourceIfMatch, - Parameters.sourceIfNoneMatch, - Parameters.sourceIfTags, - Parameters.copySource, - Parameters.blobTagsString, - Parameters.sourceContentMD5, - Parameters.copySourceAuthorization, - Parameters.copySourceTags, - Parameters.fileRequestIntent, - Parameters.transactionalContentMD5, - Parameters.blobType2, - Parameters.copySourceBlobProperties - ], - isXML: true, - serializer: xmlSerializer - }; - var stageBlockOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.BlockBlobStageBlockHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlockBlobStageBlockExceptionHeaders + } + toString(sync = false) { + return this._sink.toString(sync); + } + toUint8Array(sync = false) { + return this._sink.toUint8Array(sync); + } + writeAll(input) { + if (isPromise(input)) { + return input.then((x) => this.writeAll(x)); + } else if (isAsyncIterable(input)) { + return writeAllAsync(this, input); } - }, - requestBody: Parameters.body1, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.comp24, - Parameters.blockId - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.contentLength, - Parameters.leaseId, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.encryptionScope, - Parameters.transactionalContentMD5, - Parameters.transactionalContentCrc64, - Parameters.contentType1, - Parameters.accept2 - ], - isXML: true, - contentType: "application/xml; charset=utf-8", - mediaType: "binary", - serializer: xmlSerializer + return writeAll(this, input); + } + get closed() { + return this._sink.closed; + } + [Symbol.asyncIterator]() { + return this._sink[Symbol.asyncIterator](); + } + toDOMStream(options) { + return this._sink.toDOMStream(options); + } + toNodeStream(options) { + return this._sink.toNodeStream(options); + } + close() { + return this.reset()._sink.close(); + } + abort(reason) { + return this.reset()._sink.abort(reason); + } + finish() { + this._autoDestroy ? this.close() : this.reset(this._sink, this._schema); + return this; + } + reset(sink = this._sink, schema = null) { + if (sink === this._sink || sink instanceof AsyncByteQueue) { + this._sink = sink; + } else { + this._sink = new AsyncByteQueue(); + if (sink && isWritableDOMStream(sink)) { + this.toDOMStream({ type: "bytes" }).pipeTo(sink); + } else if (sink && isWritableNodeStream(sink)) { + this.toNodeStream({ objectMode: false }).pipe(sink); + } + } + if (this._started && this._schema) { + this._writeFooter(this._schema); + } + this._started = false; + this._dictionaryBlocks = []; + this._recordBatchBlocks = []; + this._seenDictionaries = /* @__PURE__ */ new Map(); + this._dictionaryDeltaOffsets = /* @__PURE__ */ new Map(); + if (!schema || !compareSchemas(schema, this._schema)) { + if (schema == null) { + this._position = 0; + this._schema = null; + } else { + this._started = true; + this._schema = schema; + this._writeSchema(schema); + } + } + return this; + } + write(payload) { + let schema = null; + if (!this._sink) { + throw new Error(`RecordBatchWriter is closed`); + } else if (payload == null) { + return this.finish() && void 0; + } else if (payload instanceof Table && !(schema = payload.schema)) { + return this.finish() && void 0; + } else if (payload instanceof RecordBatch3 && !(schema = payload.schema)) { + return this.finish() && void 0; + } + if (schema && !compareSchemas(schema, this._schema)) { + if (this._started && this._autoDestroy) { + return this.close(); + } + this.reset(this._sink, schema); + } + if (payload instanceof RecordBatch3) { + if (!(payload instanceof _InternalEmptyPlaceholderRecordBatch)) { + this._writeRecordBatch(payload); + } + } else if (payload instanceof Table) { + this.writeAll(payload.batches); + } else if (isIterable(payload)) { + this.writeAll(payload); + } + } + _writeMessage(message, alignment = 8) { + const a = alignment - 1; + const buffer = Message2.encode(message); + const flatbufferSize = buffer.byteLength; + const prefixSize = !this._writeLegacyIpcFormat ? 8 : 4; + const alignedSize = flatbufferSize + prefixSize + a & ~a; + const nPaddingBytes = alignedSize - flatbufferSize - prefixSize; + if (message.headerType === MessageHeader.RecordBatch) { + this._recordBatchBlocks.push(new FileBlock(alignedSize, message.bodyLength, this._position)); + } else if (message.headerType === MessageHeader.DictionaryBatch) { + this._dictionaryBlocks.push(new FileBlock(alignedSize, message.bodyLength, this._position)); + } + if (!this._writeLegacyIpcFormat) { + this._write(Int32Array.of(-1)); + } + this._write(Int32Array.of(alignedSize - prefixSize)); + if (flatbufferSize > 0) { + this._write(buffer); + } + return this._writePadding(nPaddingBytes); + } + _write(chunk) { + if (this._started) { + const buffer = toUint8Array(chunk); + if (buffer && buffer.byteLength > 0) { + this._sink.write(buffer); + this._position += buffer.byteLength; + } + } + return this; + } + _writeSchema(schema) { + return this._writeMessage(Message2.from(schema)); + } + // @ts-ignore + _writeFooter(schema) { + return this._writeLegacyIpcFormat ? this._write(Int32Array.of(0)) : this._write(Int32Array.of(-1, 0)); + } + _writeMagic() { + return this._write(MAGIC); + } + _writePadding(nBytes) { + return nBytes > 0 ? this._write(new Uint8Array(nBytes)) : this; + } + _writeRecordBatch(batch) { + const { byteLength, nodes, bufferRegions, buffers, variadicBufferCounts } = this._assembleRecordBatch(batch); + const recordBatch = new RecordBatch2(batch.numRows, nodes, bufferRegions, this._compression, variadicBufferCounts, batch.metadata); + const message = Message2.from(recordBatch, byteLength); + return this._writeDictionaries(batch)._writeMessage(message)._writeBodyBuffers(buffers); + } + _assembleRecordBatch(batch) { + let { byteLength, nodes, bufferRegions, buffers, variadicBufferCounts } = VectorAssembler.assemble(batch); + if (this._compression != null) { + ({ byteLength, bufferRegions, buffers } = this._compressBodyBuffers(buffers)); + } + return { byteLength, nodes, bufferRegions, buffers, variadicBufferCounts }; + } + _compressBodyBuffers(buffers) { + const codec = compressionRegistry.get(this._compression.type); + if (!(codec === null || codec === void 0 ? void 0 : codec.encode) || typeof codec.encode !== "function") { + throw new Error(`Codec for compression type "${CompressionType[this._compression.type]}" has invalid encode method`); + } + let currentOffset = 0; + const compressedBuffers = []; + const bufferRegions = []; + for (const buffer of buffers) { + const byteBuf = toUint8Array(buffer); + if (byteBuf.length === 0) { + compressedBuffers.push(new Uint8Array(0), new Uint8Array(0)); + bufferRegions.push(new BufferRegion(currentOffset, 0)); + continue; + } + const compressed = codec.encode(byteBuf); + const isCompressionEffective = compressed.length < byteBuf.length; + const finalBuffer = isCompressionEffective ? compressed : byteBuf; + const byteLength = isCompressionEffective ? finalBuffer.length : LENGTH_NO_COMPRESSED_DATA; + const lengthPrefix = new flatbuffers36.ByteBuffer(new Uint8Array(COMPRESS_LENGTH_PREFIX)); + lengthPrefix.writeInt64(0, BigInt(byteLength)); + compressedBuffers.push(lengthPrefix.bytes(), new Uint8Array(finalBuffer)); + const padding = (currentOffset + 7 & ~7) - currentOffset; + currentOffset += padding; + const fullBodyLength = COMPRESS_LENGTH_PREFIX + finalBuffer.length; + bufferRegions.push(new BufferRegion(currentOffset, fullBodyLength)); + currentOffset += fullBodyLength; + } + const finalPadding = (currentOffset + 7 & ~7) - currentOffset; + currentOffset += finalPadding; + return { byteLength: currentOffset, bufferRegions, buffers: compressedBuffers }; + } + _writeDictionaryBatch(dictionary, id, isDelta = false) { + const { byteLength, nodes, bufferRegions, buffers, variadicBufferCounts } = this._assembleRecordBatch(new Vector([dictionary])); + const recordBatch = new RecordBatch2(dictionary.length, nodes, bufferRegions, this._compression, variadicBufferCounts); + const dictionaryBatch = new DictionaryBatch2(recordBatch, id, isDelta); + const message = Message2.from(dictionaryBatch, byteLength); + return this._writeMessage(message)._writeBodyBuffers(buffers); + } + _writeBodyBuffers(buffers) { + const bufGroupSize = this._compression != null ? 2 : 1; + const bufs = new Array(bufGroupSize); + for (let i = 0; i < buffers.length; i += bufGroupSize) { + let size = 0; + for (let j = -1; ++j < bufGroupSize; ) { + bufs[j] = buffers[i + j]; + size += bufs[j].byteLength; + } + if (size === 0) { + continue; + } + for (const buf of bufs) + this._write(buf); + const padding = (size + 7 & ~7) - size; + if (padding > 0) { + this._writePadding(padding); + } + } + return this; + } + _writeDictionaries(batch) { + var _a6, _b2; + for (const [id, dictionary] of batch.dictionaries) { + const chunks = (_a6 = dictionary === null || dictionary === void 0 ? void 0 : dictionary.data) !== null && _a6 !== void 0 ? _a6 : []; + const prevDictionary = this._seenDictionaries.get(id); + const offset = (_b2 = this._dictionaryDeltaOffsets.get(id)) !== null && _b2 !== void 0 ? _b2 : 0; + if (!prevDictionary || prevDictionary.data[0] !== chunks[0]) { + for (const [index2, chunk] of chunks.entries()) + this._writeDictionaryBatch(chunk, id, index2 > 0); + } else if (offset < chunks.length) { + for (const chunk of chunks.slice(offset)) + this._writeDictionaryBatch(chunk, id, true); + } + this._seenDictionaries.set(id, dictionary); + this._dictionaryDeltaOffsets.set(id, chunks.length); + } + return this; + } }; - var stageBlockFromURLOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.BlockBlobStageBlockFromURLHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlockBlobStageBlockFromURLExceptionHeaders + RecordBatchStreamWriter = class _RecordBatchStreamWriter extends RecordBatchWriter { + /** @nocollapse */ + static writeAll(input, options) { + const writer = new _RecordBatchStreamWriter(options); + if (isPromise(input)) { + return input.then((x) => writer.writeAll(x)); + } else if (isAsyncIterable(input)) { + return writeAllAsync(writer, input); } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.comp24, - Parameters.blockId - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.contentLength, - Parameters.leaseId, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.encryptionScope, - Parameters.sourceIfModifiedSince, - Parameters.sourceIfUnmodifiedSince, - Parameters.sourceIfMatch, - Parameters.sourceIfNoneMatch, - Parameters.sourceContentMD5, - Parameters.copySourceAuthorization, - Parameters.fileRequestIntent, - Parameters.sourceUrl, - Parameters.sourceContentCrc64, - Parameters.sourceRange1 - ], - isXML: true, - serializer: xmlSerializer + return writeAll(writer, input); + } }; - var commitBlockListOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: Mappers.BlockBlobCommitBlockListHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlockBlobCommitBlockListExceptionHeaders + RecordBatchFileWriter = class _RecordBatchFileWriter extends RecordBatchWriter { + /** @nocollapse */ + static writeAll(input, options) { + const writer = new _RecordBatchFileWriter(options); + if (isPromise(input)) { + return input.then((x) => writer.writeAll(x)); + } else if (isAsyncIterable(input)) { + return writeAllAsync(writer, input); } - }, - requestBody: Parameters.blocks, - queryParameters: [Parameters.timeoutInSeconds, Parameters.comp25], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.contentType, - Parameters.accept, - Parameters.version, - Parameters.requestId, - Parameters.metadata, - Parameters.leaseId, - Parameters.ifModifiedSince, - Parameters.ifUnmodifiedSince, - Parameters.encryptionKey, - Parameters.encryptionKeySha256, - Parameters.encryptionAlgorithm, - Parameters.ifMatch, - Parameters.ifNoneMatch, - Parameters.ifTags, - Parameters.blobCacheControl, - Parameters.blobContentType, - Parameters.blobContentMD5, - Parameters.blobContentEncoding, - Parameters.blobContentLanguage, - Parameters.blobContentDisposition, - Parameters.immutabilityPolicyExpiry, - Parameters.immutabilityPolicyMode, - Parameters.encryptionScope, - Parameters.tier, - Parameters.blobTagsString, - Parameters.legalHold1, - Parameters.transactionalContentMD5, - Parameters.transactionalContentCrc64 - ], - isXML: true, - contentType: "application/xml; charset=utf-8", - mediaType: "xml", - serializer: xmlSerializer + return writeAll(writer, input); + } + constructor(options) { + super(options); + this._autoDestroy = true; + this._writeLegacyIpcFormat = false; + } + // @ts-ignore + _writeSchema(schema) { + return this._writeMagic()._writePadding(2); + } + _writeDictionaryBatch(dictionary, id, isDelta = false) { + if (!isDelta && this._seenDictionaries.has(id)) { + throw new Error("The Arrow File format does not support replacement dictionaries. "); + } + return super._writeDictionaryBatch(dictionary, id, isDelta); + } + _writeFooter(schema) { + const buffer = Footer_.encode(new Footer_(schema, MetadataVersion.V5, this._recordBatchBlocks, this._dictionaryBlocks)); + return super._writeFooter(schema)._write(buffer)._write(Int32Array.of(buffer.byteLength))._writeMagic(); + } }; - var getBlockListOperationSpec = { - path: "/{containerName}/{blob}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.BlockList, - headersMapper: Mappers.BlockBlobGetBlockListHeaders - }, - default: { - bodyMapper: Mappers.StorageError, - headersMapper: Mappers.BlockBlobGetBlockListExceptionHeaders + RecordBatchJSONWriter = class _RecordBatchJSONWriter extends RecordBatchWriter { + /** @nocollapse */ + static writeAll(input) { + return new _RecordBatchJSONWriter().writeAll(input); + } + constructor() { + super(); + this._autoDestroy = true; + this._recordBatches = []; + this._recordBatchesWithDictionaries = []; + } + _writeMessage() { + return this; + } + // @ts-ignore + _writeFooter(schema) { + return this; + } + _writeSchema(schema) { + return this._write(`{ + "schema": ${JSON.stringify({ fields: schema.fields.map((field) => fieldToJSON(field)) }, null, 2)}`); + } + _writeDictionaries(batch) { + if (batch.dictionaries.size > 0) { + this._recordBatchesWithDictionaries.push(batch); } - }, - queryParameters: [ - Parameters.timeoutInSeconds, - Parameters.snapshot, - Parameters.comp25, - Parameters.listType - ], - urlParameters: [Parameters.url], - headerParameters: [ - Parameters.version, - Parameters.requestId, - Parameters.accept1, - Parameters.leaseId, - Parameters.ifTags - ], - isXML: true, - serializer: xmlSerializer + return this; + } + _writeDictionaryBatch(dictionary, id, isDelta = false) { + this._write(this._dictionaryBlocks.length === 0 ? ` ` : `, + `); + this._write(dictionaryBatchToJSON(dictionary, id, isDelta)); + this._dictionaryBlocks.push(new FileBlock(0, 0, 0)); + return this; + } + _writeRecordBatch(batch) { + this._writeDictionaries(batch); + this._recordBatches.push(batch); + return this; + } + close() { + if (this._recordBatchesWithDictionaries.length > 0) { + this._write(`, + "dictionaries": [ +`); + for (const batch of this._recordBatchesWithDictionaries) { + super._writeDictionaries(batch); + } + this._write(` + ]`); + } + if (this._recordBatches.length > 0) { + for (let i = -1, n = this._recordBatches.length; ++i < n; ) { + this._write(i === 0 ? `, + "batches": [ + ` : `, + `); + this._write(recordBatchToJSON(this._recordBatches[i])); + this._recordBatchBlocks.push(new FileBlock(0, 0, 0)); + } + this._write(` + ]`); + } + if (this._schema) { + this._write(` +}`); + } + this._recordBatchesWithDictionaries = []; + this._recordBatches = []; + return super.close(); + } }; } }); -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/index.js -var require_operations = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operations/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_service(), exports2); - tslib_1.__exportStar(require_container(), exports2); - tslib_1.__exportStar(require_blob(), exports2); - tslib_1.__exportStar(require_pageBlob(), exports2); - tslib_1.__exportStar(require_appendBlob(), exports2); - tslib_1.__exportStar(require_blockBlob(), exports2); +// node_modules/apache-arrow/io/node/iterable.mjs +function toNodeStream(source, options) { + if (isAsyncIterable(source)) { + return new AsyncIterableReadable(source[Symbol.asyncIterator](), options); } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/storageClient.js -var require_storageClient = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/storageClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageClient = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var coreHttpCompat = tslib_1.__importStar(require_commonjs9()); - var index_js_1 = require_operations(); - var StorageClient = class extends coreHttpCompat.ExtendedServiceClient { - url; - version; - /** - * Initializes a new instance of the StorageClient class. - * @param url The URL of the service account, container, or blob that is the target of the desired - * operation. - * @param options The parameter options - */ - constructor(url2, options) { - if (url2 === void 0) { - throw new Error("'url' cannot be null"); + if (isIterable(source)) { + return new IterableReadable(source[Symbol.iterator](), options); + } + throw new Error(`toNodeStream() must be called with an Iterable or AsyncIterable`); +} +var import_node_stream, IterableReadable, AsyncIterableReadable; +var init_iterable = __esm({ + "node_modules/apache-arrow/io/node/iterable.mjs"() { + init_tslib_es6(); + import_node_stream = require("node:stream"); + init_compat(); + IterableReadable = class extends import_node_stream.Readable { + constructor(it, options) { + super(options); + this._iterator = it; + this._pulling = false; + this._bytesMode = !options || !options.objectMode; + } + _read(size) { + const it = this._iterator; + if (it && !this._pulling && (this._pulling = true)) { + this._pulling = this._pull(size, it); } - if (!options) { - options = {}; + } + _destroy(e, cb) { + const it = this._iterator; + let fn; + it && (fn = e != null && it.throw || it.return); + fn === null || fn === void 0 ? void 0 : fn.call(it, e); + cb && cb(null); + } + _pull(size, it) { + const bm = this._bytesMode; + let r = null; + while (this.readable && !(r = it.next(bm ? size : null)).done) { + if (size != null) { + size -= bm && ArrayBuffer.isView(r.value) ? r.value.byteLength : 1; + } + if (!this.push(r.value) || size <= 0) { + break; + } } - const defaults3 = { - requestContentType: "application/json; charset=utf-8" - }; - const packageDetails = `azsdk-js-azure-storage-blob/12.29.1`; - const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`; - const optionsWithDefaults = { - ...defaults3, - ...options, - userAgentOptions: { - userAgentPrefix - }, - endpoint: options.endpoint ?? options.baseUri ?? "{url}" - }; - super(optionsWithDefaults); - this.url = url2; - this.version = options.version || "2025-11-05"; - this.service = new index_js_1.ServiceImpl(this); - this.container = new index_js_1.ContainerImpl(this); - this.blob = new index_js_1.BlobImpl(this); - this.pageBlob = new index_js_1.PageBlobImpl(this); - this.appendBlob = new index_js_1.AppendBlobImpl(this); - this.blockBlob = new index_js_1.BlockBlobImpl(this); + if (((r === null || r === void 0 ? void 0 : r.done) || !this.readable) && (this.push(null) || true)) { + it.return && it.return(); + } + return !this.readable; + } + }; + AsyncIterableReadable = class extends import_node_stream.Readable { + constructor(it, options) { + super(options); + this._iterator = it; + this._pulling = false; + this._bytesMode = !options || !options.objectMode; + } + _read(size) { + const it = this._iterator; + if (it && !this._pulling && (this._pulling = true)) { + (() => __awaiter(this, void 0, void 0, function* () { + return this._pulling = yield this._pull(size, it); + }))(); + } + } + _destroy(e, cb) { + const it = this._iterator; + let fn; + it && (fn = e != null && it.throw || it.return); + (fn === null || fn === void 0 ? void 0 : fn.call(it, e).then(() => cb && cb(null))) || cb && cb(null); + } + _pull(size, it) { + return __awaiter(this, void 0, void 0, function* () { + const bm = this._bytesMode; + let r = null; + while (this.readable && !(r = yield it.next(bm ? size : null)).done) { + if (size != null) { + size -= bm && ArrayBuffer.isView(r.value) ? r.value.byteLength : 1; + } + if (!this.push(r.value) || size <= 0) { + break; + } + } + if (((r === null || r === void 0 ? void 0 : r.done) || !this.readable) && (this.push(null) || true)) { + it.return && it.return(); + } + return !this.readable; + }); } - service; - container; - blob; - pageBlob; - appendBlob; - blockBlob; }; - exports2.StorageClient = StorageClient; } }); -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/service.js -var require_service2 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/service.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); +// node_modules/apache-arrow/io/node/builder.mjs +function builderThroughNodeStream(options) { + return new BuilderDuplex(makeBuilder(options), options); +} +var import_node_stream2, BuilderDuplex, builderLength, builderByteLength; +var init_builder2 = __esm({ + "node_modules/apache-arrow/io/node/builder.mjs"() { + import_node_stream2 = require("node:stream"); + init_factories(); + BuilderDuplex = class extends import_node_stream2.Duplex { + constructor(builder, options) { + const { queueingStrategy = "count", autoDestroy = true } = options; + const { highWaterMark = queueingStrategy !== "bytes" ? 1e3 : Math.pow(2, 14) } = options; + super({ autoDestroy, highWaterMark: 1, allowHalfOpen: true, writableObjectMode: true, readableObjectMode: true }); + this._numChunks = 0; + this._finished = false; + this._builder = builder; + this._desiredSize = highWaterMark; + this._getSize = queueingStrategy !== "bytes" ? builderLength : builderByteLength; + } + _read(size) { + this._maybeFlush(this._builder, this._desiredSize = size); + } + _final(cb) { + this._maybeFlush(this._builder.finish(), this._desiredSize); + cb && cb(); + } + _write(value, _2, cb) { + const result = this._maybeFlush(this._builder.append(value), this._desiredSize); + cb && cb(); + return result; + } + _destroy(err, cb) { + this._builder.clear(); + cb && cb(err); + } + _maybeFlush(builder, size) { + if (this._getSize(builder) >= size) { + ++this._numChunks && this.push(builder.toVector()); + } + if (builder.finished) { + if (builder.length > 0 || this._numChunks === 0) { + ++this._numChunks && this.push(builder.toVector()); + } + if (!this._finished && (this._finished = true)) { + this.push(null); + } + return false; + } + return this._getSize(builder) < this.writableHighWaterMark; + } + }; + builderLength = (builder) => builder.length; + builderByteLength = (builder) => builder.byteLength; } }); -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/container.js -var require_container2 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/container.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); +// node_modules/apache-arrow/io/node/reader.mjs +function recordBatchReaderThroughNodeStream(options) { + return new RecordBatchReaderDuplex(options); +} +var import_node_stream3, RecordBatchReaderDuplex; +var init_reader2 = __esm({ + "node_modules/apache-arrow/io/node/reader.mjs"() { + init_tslib_es6(); + import_node_stream3 = require("node:stream"); + init_stream(); + init_reader(); + RecordBatchReaderDuplex = class extends import_node_stream3.Duplex { + constructor(options) { + super(Object.assign(Object.assign({ allowHalfOpen: false }, options), { readableObjectMode: true, writableObjectMode: false })); + this._pulling = false; + this._autoDestroy = true; + this._reader = null; + this._pulling = false; + this._asyncQueue = new AsyncByteQueue(); + this._autoDestroy = options && typeof options.autoDestroy === "boolean" ? options.autoDestroy : true; + } + _final(cb) { + const aq = this._asyncQueue; + aq === null || aq === void 0 ? void 0 : aq.close(); + cb && cb(); + } + _write(x, _2, cb) { + const aq = this._asyncQueue; + aq === null || aq === void 0 ? void 0 : aq.write(x); + cb && cb(); + return true; + } + _read(size) { + const aq = this._asyncQueue; + if (aq && !this._pulling && (this._pulling = true)) { + (() => __awaiter(this, void 0, void 0, function* () { + if (!this._reader) { + this._reader = yield this._open(aq); + } + this._pulling = yield this._pull(size, this._reader); + }))(); + } + } + _destroy(err, cb) { + const aq = this._asyncQueue; + if (aq) { + err ? aq.abort(err) : aq.close(); + } + cb(this._asyncQueue = this._reader = null); + } + _open(source) { + return __awaiter(this, void 0, void 0, function* () { + return yield (yield RecordBatchReader.from(source)).open({ autoDestroy: this._autoDestroy }); + }); + } + _pull(size, reader) { + return __awaiter(this, void 0, void 0, function* () { + let r = null; + while (this.readable && !(r = yield reader.next()).done) { + if (!this.push(r.value) || size != null && --size <= 0) { + break; + } + } + if (!this.readable || (r === null || r === void 0 ? void 0 : r.done) && (reader.autoDestroy || (yield reader.reset().open()).closed)) { + this.push(null); + yield reader.cancel(); + } + return !this.readable; + }); + } + }; } }); -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/blob.js -var require_blob2 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/blob.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); +// node_modules/apache-arrow/io/node/writer.mjs +function recordBatchWriterThroughNodeStream(options) { + return new RecordBatchWriterDuplex(new this(options)); +} +var import_node_stream4, RecordBatchWriterDuplex; +var init_writer2 = __esm({ + "node_modules/apache-arrow/io/node/writer.mjs"() { + init_tslib_es6(); + import_node_stream4 = require("node:stream"); + init_stream(); + RecordBatchWriterDuplex = class extends import_node_stream4.Duplex { + constructor(writer, options) { + super(Object.assign(Object.assign({ allowHalfOpen: false }, options), { writableObjectMode: true, readableObjectMode: false })); + this._pulling = false; + this._writer = writer; + this._reader = new AsyncByteStream(writer); + } + _final(cb) { + const writer = this._writer; + writer === null || writer === void 0 ? void 0 : writer.close(); + cb && cb(); + } + _write(x, _2, cb) { + const writer = this._writer; + writer === null || writer === void 0 ? void 0 : writer.write(x); + cb && cb(); + return true; + } + _read(size) { + const it = this._reader; + if (it && !this._pulling && (this._pulling = true)) { + (() => __awaiter(this, void 0, void 0, function* () { + return this._pulling = yield this._pull(size, it); + }))(); + } + } + _destroy(err, cb) { + const writer = this._writer; + if (writer) { + err ? writer.abort(err) : writer.close(); + } + cb(this._reader = this._writer = null); + } + _pull(size, reader) { + return __awaiter(this, void 0, void 0, function* () { + let r = null; + while (this.readable && !(r = yield reader.next(size || null)).done) { + if (size != null && r.value) { + size -= r.value.byteLength; + } + if (!this.push(r.value) || size <= 0) { + break; + } + } + if ((r === null || r === void 0 ? void 0 : r.done) || !this.readable) { + this.push(null); + yield reader.cancel(); + } + return !this.readable; + }); + } + }; } }); -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/pageBlob.js -var require_pageBlob2 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/pageBlob.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); +// node_modules/apache-arrow/io/whatwg/iterable.mjs +function toDOMStream(source, options) { + if (isAsyncIterable(source)) { + return asyncIterableAsReadableDOMStream(source, options); } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/appendBlob.js -var require_appendBlob2 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/appendBlob.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); + if (isIterable(source)) { + return iterableAsReadableDOMStream(source, options); } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/blockBlob.js -var require_blockBlob2 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/blockBlob.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); + throw new Error(`toDOMStream() must be called with an Iterable or AsyncIterable`); +} +function iterableAsReadableDOMStream(source, options) { + let it = null; + const bm = (options === null || options === void 0 ? void 0 : options.type) === "bytes" || false; + const hwm = (options === null || options === void 0 ? void 0 : options.highWaterMark) || Math.pow(2, 24); + return new ReadableStream(Object.assign(Object.assign({}, options), { + start(controller) { + next(controller, it || (it = source[Symbol.iterator]())); + }, + pull(controller) { + it ? next(controller, it) : controller.close(); + }, + cancel() { + (it === null || it === void 0 ? void 0 : it.return) && it.return(); + it = null; + } + }), Object.assign({ highWaterMark: bm ? hwm : void 0 }, options)); + function next(controller, it2) { + let buf; + let r = null; + let size = controller.desiredSize || null; + while (!(r = it2.next(bm ? size : null)).done) { + if (ArrayBuffer.isView(r.value) && (buf = toUint8Array(r.value))) { + size != null && bm && (size = size - buf.byteLength + 1); + r.value = buf; + } + controller.enqueue(r.value); + if (size != null && --size <= 0) { + return; + } + } + controller.close(); + } +} +function asyncIterableAsReadableDOMStream(source, options) { + let it = null; + const bm = (options === null || options === void 0 ? void 0 : options.type) === "bytes" || false; + const hwm = (options === null || options === void 0 ? void 0 : options.highWaterMark) || Math.pow(2, 24); + return new ReadableStream(Object.assign(Object.assign({}, options), { + start(controller) { + return __awaiter(this, void 0, void 0, function* () { + yield next(controller, it || (it = source[Symbol.asyncIterator]())); + }); + }, + pull(controller) { + return __awaiter(this, void 0, void 0, function* () { + it ? yield next(controller, it) : controller.close(); + }); + }, + cancel() { + return __awaiter(this, void 0, void 0, function* () { + (it === null || it === void 0 ? void 0 : it.return) && (yield it.return()); + it = null; + }); + } + }), Object.assign({ highWaterMark: bm ? hwm : void 0 }, options)); + function next(controller, it2) { + return __awaiter(this, void 0, void 0, function* () { + let buf; + let r = null; + let size = controller.desiredSize || null; + while (!(r = yield it2.next(bm ? size : null)).done) { + if (ArrayBuffer.isView(r.value) && (buf = toUint8Array(r.value))) { + size != null && bm && (size = size - buf.byteLength + 1); + r.value = buf; + } + controller.enqueue(r.value); + if (size != null && --size <= 0) { + return; + } + } + controller.close(); + }); + } +} +var init_iterable2 = __esm({ + "node_modules/apache-arrow/io/whatwg/iterable.mjs"() { + init_tslib_es6(); + init_buffer(); + init_compat(); } }); -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/index.js -var require_operationsInterfaces = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/operationsInterfaces/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_service2(), exports2); - tslib_1.__exportStar(require_container2(), exports2); - tslib_1.__exportStar(require_blob2(), exports2); - tslib_1.__exportStar(require_pageBlob2(), exports2); - tslib_1.__exportStar(require_appendBlob2(), exports2); - tslib_1.__exportStar(require_blockBlob2(), exports2); +// node_modules/apache-arrow/io/whatwg/builder.mjs +function builderThroughDOMStream(options) { + return new BuilderTransform(options); +} +var BuilderTransform, chunkLength, chunkByteLength; +var init_builder3 = __esm({ + "node_modules/apache-arrow/io/whatwg/builder.mjs"() { + init_tslib_es6(); + init_factories(); + BuilderTransform = class { + constructor(options) { + this._numChunks = 0; + this._finished = false; + this._bufferedSize = 0; + const { ["readableStrategy"]: readableStrategy, ["writableStrategy"]: writableStrategy, ["queueingStrategy"]: queueingStrategy = "count" } = options, builderOptions = __rest(options, ["readableStrategy", "writableStrategy", "queueingStrategy"]); + this._controller = null; + this._builder = makeBuilder(builderOptions); + this._getSize = queueingStrategy !== "bytes" ? chunkLength : chunkByteLength; + const { ["highWaterMark"]: readableHighWaterMark = queueingStrategy === "bytes" ? Math.pow(2, 14) : 1e3 } = Object.assign({}, readableStrategy); + const { ["highWaterMark"]: writableHighWaterMark = queueingStrategy === "bytes" ? Math.pow(2, 14) : 1e3 } = Object.assign({}, writableStrategy); + this["readable"] = new ReadableStream({ + ["cancel"]: () => { + this._builder.clear(); + }, + ["pull"]: (c) => { + this._maybeFlush(this._builder, this._controller = c); + }, + ["start"]: (c) => { + this._maybeFlush(this._builder, this._controller = c); + } + }, { + "highWaterMark": readableHighWaterMark, + "size": queueingStrategy !== "bytes" ? chunkLength : chunkByteLength + }); + this["writable"] = new WritableStream({ + ["abort"]: () => { + this._builder.clear(); + }, + ["write"]: () => { + this._maybeFlush(this._builder, this._controller); + }, + ["close"]: () => { + this._maybeFlush(this._builder.finish(), this._controller); + } + }, { + "highWaterMark": writableHighWaterMark, + "size": (value) => this._writeValueAndReturnChunkSize(value) + }); + } + _writeValueAndReturnChunkSize(value) { + const bufferedSize = this._bufferedSize; + this._bufferedSize = this._getSize(this._builder.append(value)); + return this._bufferedSize - bufferedSize; + } + _maybeFlush(builder, controller) { + if (controller == null) { + return; + } + if (this._bufferedSize >= controller.desiredSize) { + ++this._numChunks && this._enqueue(controller, builder.toVector()); + } + if (builder.finished) { + if (builder.length > 0 || this._numChunks === 0) { + ++this._numChunks && this._enqueue(controller, builder.toVector()); + } + if (!this._finished && (this._finished = true)) { + this._enqueue(controller, null); + } + } + } + _enqueue(controller, chunk) { + this._bufferedSize = 0; + this._controller = null; + chunk == null ? controller.close() : controller.enqueue(chunk); + } + }; + chunkLength = (chunk) => { + var _a6; + return (_a6 = chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _a6 !== void 0 ? _a6 : 0; + }; + chunkByteLength = (chunk) => { + var _a6; + return (_a6 = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a6 !== void 0 ? _a6 : 0; + }; } }); -// node_modules/@azure/storage-blob/dist/commonjs/generated/src/index.js -var require_src2 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generated/src/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageClient = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_models(), exports2); - var storageClient_js_1 = require_storageClient(); - Object.defineProperty(exports2, "StorageClient", { enumerable: true, get: function() { - return storageClient_js_1.StorageClient; - } }); - tslib_1.__exportStar(require_operationsInterfaces(), exports2); +// node_modules/apache-arrow/io/whatwg/reader.mjs +function recordBatchReaderThroughDOMStream(writableStrategy, readableStrategy) { + const queue2 = new AsyncByteQueue(); + let reader = null; + const readable = new ReadableStream({ + cancel() { + return __awaiter(this, void 0, void 0, function* () { + yield queue2.close(); + }); + }, + start(controller) { + return __awaiter(this, void 0, void 0, function* () { + yield next(controller, reader || (reader = yield open())); + }); + }, + pull(controller) { + return __awaiter(this, void 0, void 0, function* () { + reader ? yield next(controller, reader) : controller.close(); + }); + } + }); + return { writable: new WritableStream(queue2, Object.assign({ "highWaterMark": Math.pow(2, 14) }, writableStrategy)), readable }; + function open() { + return __awaiter(this, void 0, void 0, function* () { + return yield (yield RecordBatchReader.from(queue2)).open(readableStrategy); + }); + } + function next(controller, reader2) { + return __awaiter(this, void 0, void 0, function* () { + let size = controller.desiredSize; + let r = null; + while (!(r = yield reader2.next()).done) { + controller.enqueue(r.value); + if (size != null && --size <= 0) { + return; + } + } + controller.close(); + }); + } +} +var init_reader3 = __esm({ + "node_modules/apache-arrow/io/whatwg/reader.mjs"() { + init_tslib_es6(); + init_stream(); + init_reader(); } }); -// node_modules/@azure/storage-blob/dist/commonjs/StorageContextClient.js -var require_StorageContextClient = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/StorageContextClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageContextClient = void 0; - var index_js_1 = require_src2(); - var StorageContextClient = class extends index_js_1.StorageClient { - async sendOperationRequest(operationArguments, operationSpec) { - const operationSpecToSend = { ...operationSpec }; - if (operationSpecToSend.path === "/{containerName}" || operationSpecToSend.path === "/{containerName}/{blob}") { - operationSpecToSend.path = ""; +// node_modules/apache-arrow/io/whatwg/writer.mjs +function recordBatchWriterThroughDOMStream(writableStrategy, readableStrategy) { + const writer = new this(writableStrategy); + const reader = new AsyncByteStream(writer); + const readable = new ReadableStream({ + // type: 'bytes', + cancel() { + return __awaiter(this, void 0, void 0, function* () { + yield reader.cancel(); + }); + }, + pull(controller) { + return __awaiter(this, void 0, void 0, function* () { + yield next(controller); + }); + }, + start(controller) { + return __awaiter(this, void 0, void 0, function* () { + yield next(controller); + }); + } + }, Object.assign({ "highWaterMark": Math.pow(2, 14) }, readableStrategy)); + return { writable: new WritableStream(writer, writableStrategy), readable }; + function next(controller) { + return __awaiter(this, void 0, void 0, function* () { + let buf = null; + let size = controller.desiredSize; + while (buf = yield reader.read(size || null)) { + controller.enqueue(buf); + if (size != null && (size -= buf.byteLength) <= 0) { + return; } - return super.sendOperationRequest(operationArguments, operationSpecToSend); } - }; - exports2.StorageContextClient = StorageContextClient; + controller.close(); + }); + } +} +var init_writer3 = __esm({ + "node_modules/apache-arrow/io/whatwg/writer.mjs"() { + init_tslib_es6(); + init_stream(); + } +}); + +// node_modules/apache-arrow/ipc/serialization.mjs +function tableFromIPC(input) { + const reader = RecordBatchReader.from(input); + if (isPromise(reader)) { + return reader.then((reader2) => tableFromIPC(reader2)); + } + if (reader.isAsync()) { + return reader.readAll().then((xs) => new Table(xs)); + } + return new Table(reader.readAll()); +} +function tableToIPC(table, type = "stream", compressionType = null) { + const writerOptions = { compressionType }; + return (type === "stream" ? RecordBatchStreamWriter : RecordBatchFileWriter).writeAll(table, writerOptions).toUint8Array(true); +} +var init_serialization = __esm({ + "node_modules/apache-arrow/ipc/serialization.mjs"() { + init_table(); + init_compat(); + init_reader(); + init_writer(); + } +}); + +// node_modules/apache-arrow/util/typecheck.mjs +var typecheck_exports = {}; +__export(typecheck_exports, { + isArrowData: () => isArrowData, + isArrowDataType: () => isArrowDataType, + isArrowField: () => isArrowField, + isArrowRecordBatch: () => isArrowRecordBatch, + isArrowSchema: () => isArrowSchema, + isArrowTable: () => isArrowTable, + isArrowVector: () => isArrowVector +}); +function isArrowSchema(x) { + return Schema4.isSchema(x); +} +function isArrowField(x) { + return Field2.isField(x); +} +function isArrowDataType(x) { + return DataType.isDataType(x); +} +function isArrowData(x) { + return Data.isData(x); +} +function isArrowVector(x) { + return Vector.isVector(x); +} +function isArrowRecordBatch(x) { + return RecordBatch3.isRecordBatch(x); +} +function isArrowTable(x) { + return Table.isTable(x); +} +var init_typecheck = __esm({ + "node_modules/apache-arrow/util/typecheck.mjs"() { + init_schema2(); + init_type2(); + init_data(); + init_vector2(); + init_recordbatch2(); + init_table(); + } +}); + +// node_modules/apache-arrow/Arrow.mjs +var util2; +var init_Arrow = __esm({ + "node_modules/apache-arrow/Arrow.mjs"() { + init_message_header(); + init_compression_type(); + init_enum(); + init_data(); + init_type2(); + init_table(); + init_vector2(); + init_visitor(); + init_schema2(); + init_map2(); + init_struct2(); + init_builder(); + init_factories(); + init_bool2(); + init_null2(); + init_date2(); + init_decimal2(); + init_dictionary(); + init_fixedsizebinary(); + init_float(); + init_int3(); + init_time2(); + init_timestamp2(); + init_interval3(); + init_duration2(); + init_utf83(); + init_utf8view(); + init_largeutf8(); + init_binary2(); + init_binaryview(); + init_largebinary(); + init_list2(); + init_largelist(); + init_fixedsizelist(); + init_map3(); + init_struct3(); + init_union2(); + init_stream(); + init_reader(); + init_writer(); + init_serialization(); + init_registry(); + init_message3(); + init_message2(); + init_recordbatch2(); + init_typecheck(); + init_bn(); + init_int2(); + init_bit(); + init_math(); + init_buffer(); + init_vector(); + init_pretty(); + init_interval2(); + init_typecheck(); + init_typecomparator(); + util2 = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, bn_exports), int_exports), bit_exports), math_exports), buffer_exports), vector_exports), pretty_exports), interval_exports), typecheck_exports), { + compareSchemas, + compareFields, + compareTypes + }); } }); -// node_modules/@azure/storage-blob/dist/commonjs/StorageClient.js -var require_StorageClient = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/StorageClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageClient = void 0; - var StorageContextClient_js_1 = require_StorageContextClient(); - var Pipeline_js_1 = require_Pipeline(); - var utils_common_js_1 = require_utils_common(); - var StorageClient = class { - /** - * Encoded URL string value. - */ - url; - accountName; - /** - * Request policy pipeline. - * - * @internal - */ - pipeline; - /** - * Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. - */ - credential; - /** - * StorageClient is a reference to protocol layer operations entry, which is - * generated by AutoRest generator. - */ - storageClientContext; - /** - */ - isHttps; - /** - * Creates an instance of StorageClient. - * @param url - url to resource - * @param pipeline - request policy pipeline. - */ - constructor(url2, pipeline2) { - this.url = (0, utils_common_js_1.escapeURLPath)(url2); - this.accountName = (0, utils_common_js_1.getAccountNameFromUrl)(url2); - this.pipeline = pipeline2; - this.storageClientContext = new StorageContextClient_js_1.StorageContextClient(this.url, (0, Pipeline_js_1.getCoreClientOptions)(pipeline2)); - this.isHttps = (0, utils_common_js_1.iEqual)((0, utils_common_js_1.getURLScheme)(this.url) || "", "https"); - this.credential = (0, Pipeline_js_1.getCredentialFromPipeline)(pipeline2); - const storageClientContext = this.storageClientContext; - storageClientContext.requestContentType = void 0; +// node_modules/apache-arrow/Arrow.dom.mjs +var init_Arrow_dom = __esm({ + "node_modules/apache-arrow/Arrow.dom.mjs"() { + init_adapters(); + init_builder(); + init_reader(); + init_writer(); + init_iterable2(); + init_builder3(); + init_reader3(); + init_writer3(); + init_Arrow(); + init_Arrow(); + adapters_default.toDOMStream = toDOMStream; + Builder["throughDOM"] = builderThroughDOMStream; + RecordBatchReader["throughDOM"] = recordBatchReaderThroughDOMStream; + RecordBatchFileReader["throughDOM"] = recordBatchReaderThroughDOMStream; + RecordBatchStreamReader["throughDOM"] = recordBatchReaderThroughDOMStream; + RecordBatchWriter["throughDOM"] = recordBatchWriterThroughDOMStream; + RecordBatchFileWriter["throughDOM"] = recordBatchWriterThroughDOMStream; + RecordBatchStreamWriter["throughDOM"] = recordBatchWriterThroughDOMStream; + } +}); + +// node_modules/apache-arrow/Arrow.node.mjs +var Arrow_node_exports = {}; +__export(Arrow_node_exports, { + AsyncByteQueue: () => AsyncByteQueue, + AsyncByteStream: () => AsyncByteStream, + AsyncMessageReader: () => AsyncMessageReader, + AsyncRecordBatchFileReader: () => AsyncRecordBatchFileReader, + AsyncRecordBatchStreamReader: () => AsyncRecordBatchStreamReader, + Binary: () => Binary2, + BinaryBuilder: () => BinaryBuilder, + BinaryView: () => BinaryView2, + BinaryViewBuilder: () => BinaryViewBuilder, + Bool: () => Bool2, + BoolBuilder: () => BoolBuilder, + BufferType: () => BufferType, + Builder: () => Builder, + ByteStream: () => ByteStream, + CompressionType: () => CompressionType, + Data: () => Data, + DataType: () => DataType, + DateBuilder: () => DateBuilder, + DateDay: () => DateDay, + DateDayBuilder: () => DateDayBuilder, + DateMillisecond: () => DateMillisecond, + DateMillisecondBuilder: () => DateMillisecondBuilder, + DateUnit: () => DateUnit, + Date_: () => Date_, + Decimal: () => Decimal2, + DecimalBuilder: () => DecimalBuilder, + DenseUnion: () => DenseUnion, + DenseUnionBuilder: () => DenseUnionBuilder, + Dictionary: () => Dictionary, + DictionaryBuilder: () => DictionaryBuilder, + Duration: () => Duration2, + DurationBuilder: () => DurationBuilder, + DurationMicrosecond: () => DurationMicrosecond, + DurationMicrosecondBuilder: () => DurationMicrosecondBuilder, + DurationMillisecond: () => DurationMillisecond, + DurationMillisecondBuilder: () => DurationMillisecondBuilder, + DurationNanosecond: () => DurationNanosecond, + DurationNanosecondBuilder: () => DurationNanosecondBuilder, + DurationSecond: () => DurationSecond, + DurationSecondBuilder: () => DurationSecondBuilder, + Field: () => Field2, + FixedSizeBinary: () => FixedSizeBinary2, + FixedSizeBinaryBuilder: () => FixedSizeBinaryBuilder, + FixedSizeList: () => FixedSizeList2, + FixedSizeListBuilder: () => FixedSizeListBuilder, + Float: () => Float, + Float16: () => Float16, + Float16Builder: () => Float16Builder, + Float32: () => Float32, + Float32Builder: () => Float32Builder, + Float64: () => Float64, + Float64Builder: () => Float64Builder, + FloatBuilder: () => FloatBuilder, + Int: () => Int_, + Int16: () => Int16, + Int16Builder: () => Int16Builder, + Int32: () => Int32, + Int32Builder: () => Int32Builder, + Int64: () => Int64, + Int64Builder: () => Int64Builder, + Int8: () => Int8, + Int8Builder: () => Int8Builder, + IntBuilder: () => IntBuilder, + Interval: () => Interval_, + IntervalBuilder: () => IntervalBuilder, + IntervalDayTime: () => IntervalDayTime, + IntervalDayTimeBuilder: () => IntervalDayTimeBuilder, + IntervalMonthDayNano: () => IntervalMonthDayNano, + IntervalMonthDayNanoBuilder: () => IntervalMonthDayNanoBuilder, + IntervalUnit: () => IntervalUnit, + IntervalYearMonth: () => IntervalYearMonth, + IntervalYearMonthBuilder: () => IntervalYearMonthBuilder, + JSONMessageReader: () => JSONMessageReader, + LargeBinary: () => LargeBinary2, + LargeBinaryBuilder: () => LargeBinaryBuilder, + LargeList: () => LargeList2, + LargeListBuilder: () => LargeListBuilder, + LargeUtf8: () => LargeUtf82, + LargeUtf8Builder: () => LargeUtf8Builder, + List: () => List2, + ListBuilder: () => ListBuilder, + MapBuilder: () => MapBuilder, + MapRow: () => MapRow, + Map_: () => Map_, + Message: () => Message2, + MessageHeader: () => MessageHeader, + MessageReader: () => MessageReader, + MetadataVersion: () => MetadataVersion, + Null: () => Null2, + NullBuilder: () => NullBuilder, + Precision: () => Precision, + RecordBatch: () => RecordBatch3, + RecordBatchFileReader: () => RecordBatchFileReader, + RecordBatchFileWriter: () => RecordBatchFileWriter, + RecordBatchJSONWriter: () => RecordBatchJSONWriter, + RecordBatchReader: () => RecordBatchReader, + RecordBatchStreamReader: () => RecordBatchStreamReader, + RecordBatchStreamWriter: () => RecordBatchStreamWriter, + RecordBatchWriter: () => RecordBatchWriter, + Schema: () => Schema4, + SparseUnion: () => SparseUnion, + SparseUnionBuilder: () => SparseUnionBuilder, + Struct: () => Struct, + StructBuilder: () => StructBuilder, + StructRow: () => StructRow, + Table: () => Table, + Time: () => Time_, + TimeBuilder: () => TimeBuilder, + TimeMicrosecond: () => TimeMicrosecond, + TimeMicrosecondBuilder: () => TimeMicrosecondBuilder, + TimeMillisecond: () => TimeMillisecond, + TimeMillisecondBuilder: () => TimeMillisecondBuilder, + TimeNanosecond: () => TimeNanosecond, + TimeNanosecondBuilder: () => TimeNanosecondBuilder, + TimeSecond: () => TimeSecond, + TimeSecondBuilder: () => TimeSecondBuilder, + TimeUnit: () => TimeUnit, + Timestamp: () => Timestamp_, + TimestampBuilder: () => TimestampBuilder, + TimestampMicrosecond: () => TimestampMicrosecond, + TimestampMicrosecondBuilder: () => TimestampMicrosecondBuilder, + TimestampMillisecond: () => TimestampMillisecond, + TimestampMillisecondBuilder: () => TimestampMillisecondBuilder, + TimestampNanosecond: () => TimestampNanosecond, + TimestampNanosecondBuilder: () => TimestampNanosecondBuilder, + TimestampSecond: () => TimestampSecond, + TimestampSecondBuilder: () => TimestampSecondBuilder, + Type: () => Type2, + Uint16: () => Uint16, + Uint16Builder: () => Uint16Builder, + Uint32: () => Uint32, + Uint32Builder: () => Uint32Builder, + Uint64: () => Uint64, + Uint64Builder: () => Uint64Builder, + Uint8: () => Uint8, + Uint8Builder: () => Uint8Builder, + Union: () => Union_, + UnionBuilder: () => UnionBuilder, + UnionMode: () => UnionMode, + Utf8: () => Utf82, + Utf8Builder: () => Utf8Builder, + Utf8View: () => Utf8View2, + Utf8ViewBuilder: () => Utf8ViewBuilder, + Vector: () => Vector, + Visitor: () => Visitor, + builderThroughAsyncIterable: () => builderThroughAsyncIterable, + builderThroughIterable: () => builderThroughIterable, + compressionRegistry: () => compressionRegistry, + isArrowData: () => isArrowData, + isArrowDataType: () => isArrowDataType, + isArrowField: () => isArrowField, + isArrowRecordBatch: () => isArrowRecordBatch, + isArrowSchema: () => isArrowSchema, + isArrowTable: () => isArrowTable, + isArrowVector: () => isArrowVector, + makeBuilder: () => makeBuilder, + makeData: () => makeData, + makeTable: () => makeTable, + makeVector: () => makeVector, + tableFromArrays: () => tableFromArrays, + tableFromIPC: () => tableFromIPC, + tableFromJSON: () => tableFromJSON, + tableToIPC: () => tableToIPC, + util: () => util2, + vectorFromArray: () => vectorFromArray +}); +var init_Arrow_node = __esm({ + "node_modules/apache-arrow/Arrow.node.mjs"() { + init_adapters(); + init_builder(); + init_reader(); + init_writer(); + init_iterable(); + init_builder2(); + init_reader2(); + init_writer2(); + init_Arrow_dom(); + adapters_default.toNodeStream = toNodeStream; + Builder["throughNode"] = builderThroughNodeStream; + RecordBatchReader["throughNode"] = recordBatchReaderThroughNodeStream; + RecordBatchWriter["throughNode"] = recordBatchWriterThroughNodeStream; + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/utils/blobListArrowParser.js +var require_blobListArrowParser = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/utils/blobListArrowParser.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } + return to; }; - exports2.StorageClient = StorageClient; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var blobListArrowParser_exports = {}; + __export2(blobListArrowParser_exports, { + parseBlobListArrowResponse: () => parseBlobListArrowResponse + }); + module2.exports = __toCommonJS2(blobListArrowParser_exports); + var import_core_util = require_commonjs4(); + var import_utils_common = require_utils_common2(); + async function parseBlobListArrowResponse(response) { + const { tableFromIPC: tableFromIPC2 } = await Promise.resolve().then(() => (init_Arrow_node(), Arrow_node_exports)); + const table = response.readableStreamBody ? await tableFromIPC2(response.readableStreamBody) : tableFromIPC2(await (0, import_utils_common.readResponseBodyToBytes)(response)); + return projectArrowTable(table); + } + function projectArrowTable(table) { + const nextMarker = table.schema.metadata?.get("NextMarker") ?? void 0; + const getColumn = (columnName) => table.getChild(columnName); + const cell = (rowIndex, columnName) => getColumn(columnName)?.get(rowIndex); + const asString = (rowIndex, columnName) => { + const value = cell(rowIndex, columnName); + return value === void 0 || value === null ? void 0 : String(value); + }; + const asBoolean = (rowIndex, columnName) => { + const value = cell(rowIndex, columnName); + return value === void 0 || value === null ? void 0 : Boolean(value); + }; + const asNumber = (rowIndex, columnName) => { + const value = cell(rowIndex, columnName); + return value === void 0 || value === null ? void 0 : Number(value); + }; + const asDate = (rowIndex, columnName) => { + const value = cell(rowIndex, columnName); + if (value === void 0 || value === null) { + return void 0; + } + const millis = Number(value); + if (Number.isNaN(millis)) { + const parsed = Date.parse(String(value)); + return Number.isNaN(parsed) ? void 0 : new Date(parsed); + } + return new Date(millis); + }; + const asBytesFromBase64 = (rowIndex, columnName) => { + const value = asString(rowIndex, columnName); + return value === void 0 ? void 0 : (0, import_core_util.stringToUint8Array)(value, "base64"); + }; + const asMap = (rowIndex, columnName) => toRecord(cell(rowIndex, columnName)); + const blobItems = []; + const blobPrefixes = []; + for (let i = 0; i < table.numRows; i++) { + const resourceType = asString(i, "ResourceType"); + if (resourceType !== void 0 && resourceType.toLowerCase() === "blobprefix") { + blobPrefixes.push({ name: { content: asString(i, "Name") ?? "" } }); + continue; + } + const properties = { + createdOn: asDate(i, "Creation-Time"), + lastModified: asDate(i, "Last-Modified") ?? /* @__PURE__ */ new Date(0), + etag: asString(i, "Etag") ?? "", + contentLength: asNumber(i, "Content-Length"), + contentType: asString(i, "Content-Type"), + contentEncoding: asString(i, "Content-Encoding"), + contentLanguage: asString(i, "Content-Language"), + contentMD5: asBytesFromBase64(i, "Content-MD5"), + contentDisposition: asString(i, "Content-Disposition"), + cacheControl: asString(i, "Cache-Control"), + blobSequenceNumber: asNumber(i, "x-ms-blob-sequence-number"), + blobType: asString(i, "BlobType"), + leaseStatus: asString(i, "LeaseStatus"), + leaseState: asString(i, "LeaseState"), + leaseDuration: asString(i, "LeaseDuration"), + copyId: asString(i, "CopyId"), + copyStatus: asString(i, "CopyStatus"), + copySource: asString(i, "CopySource"), + copyProgress: asString(i, "CopyProgress"), + copyCompletedOn: asDate(i, "CopyCompletionTime"), + copyStatusDescription: asString(i, "CopyStatusDescription"), + serverEncrypted: asBoolean(i, "ServerEncrypted"), + incrementalCopy: asBoolean(i, "IncrementalCopy"), + destinationSnapshot: asString(i, "CopyDestinationSnapshot"), + deletedOn: asDate(i, "DeletedTime"), + remainingRetentionDays: asNumber(i, "RemainingRetentionDays"), + accessTier: asString(i, "AccessTier"), + accessTierInferred: asBoolean(i, "AccessTierInferred"), + archiveStatus: asString(i, "ArchiveStatus"), + smartAccessTier: asString(i, "SmartAccessTier"), + customerProvidedKeySha256: asString(i, "CustomerProvidedKeySha256"), + encryptionScope: asString(i, "EncryptionScope"), + accessTierChangedOn: asDate(i, "AccessTierChangeTime"), + tagCount: asNumber(i, "TagCount"), + expiresOn: asDate(i, "Expiry-Time"), + isSealed: asBoolean(i, "Sealed"), + rehydratePriority: asString( + i, + "RehydratePriority" + ), + lastAccessedOn: asDate(i, "LastAccessTime"), + immutabilityPolicyExpiresOn: asDate(i, "ImmutabilityPolicyUntilDate"), + immutabilityPolicyMode: asString( + i, + "ImmutabilityPolicyMode" + ), + legalHold: asBoolean(i, "LegalHold") + }; + blobItems.push({ + name: { content: asString(i, "Name") ?? "" }, + deleted: asBoolean(i, "Deleted") ?? false, + snapshot: asString(i, "Snapshot") ?? "", + versionId: asString(i, "VersionId"), + isCurrentVersion: asBoolean(i, "IsCurrentVersion"), + properties, + metadata: asMap(i, "Metadata"), + blobTags: toBlobTags(asMap(i, "Tags")), + objectReplicationMetadata: asMap(i, "OrMetadata"), + hasVersionsOnly: asBoolean(i, "HasVersionsOnly") + }); + } + return { nextMarker, blobItems, blobPrefixes }; + } + function toBlobTags(map) { + return map === void 0 ? void 0 : { blobTagSet: Object.entries(map).map(([key, value]) => ({ key, value })) }; + } + function toRecord(value) { + if (value === void 0 || value === null) { + return void 0; + } + const entries = []; + const asText = (v) => v === void 0 || v === null ? "" : String(v); + if (typeof value[Symbol.iterator] === "function") { + for (const entry of value) { + if (Array.isArray(entry)) { + entries.push([String(entry[0]), asText(entry[1])]); + } else if (entry && typeof entry === "object" && "key" in entry) { + const { key, value: entryValue } = entry; + entries.push([String(key), asText(entryValue)]); + } + } + } else if (typeof value === "object") { + for (const [key, entryValue] of Object.entries(value)) { + entries.push([key, asText(entryValue)]); + } + } + return Object.fromEntries(entries); + } } }); -// node_modules/@azure/storage-blob/dist/commonjs/utils/tracing.js -var require_tracing = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/utils/tracing.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.tracingClient = void 0; - var core_tracing_1 = require_commonjs5(); - var constants_js_1 = require_constants10(); - exports2.tracingClient = (0, core_tracing_1.createTracingClient)({ - packageName: "@azure/storage-blob", - packageVersion: constants_js_1.SDK_VERSION, - namespace: "Microsoft.Storage" +// node_modules/@azure/storage-blob/dist/commonjs/utils/blobListXmlParser.js +var require_blobListXmlParser = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/utils/blobListXmlParser.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var blobListXmlParser_exports = {}; + __export2(blobListXmlParser_exports, { + deserializeListBlobFlatSegmentXml: () => deserializeListBlobFlatSegmentXml, + deserializeListBlobHierarchySegmentXml: () => deserializeListBlobHierarchySegmentXml }); + module2.exports = __toCommonJS2(blobListXmlParser_exports); + var coreClient = __toESM2(require_commonjs8()); + var import_core_xml = require_commonjs10(); + var Mappers = __toESM2(require_mappers()); + var import_utils_common = require_utils_common2(); + var listBlobsXmlSerializer = coreClient.createSerializer( + Mappers, + /* isXml */ + true + ); + async function readResponseBodyToText(response) { + const bytes = await (0, import_utils_common.readResponseBodyToBytes)(response); + return new TextDecoder().decode(bytes); + } + async function deserializeListBlobFlatSegmentXml(response) { + const bodyAsText = await readResponseBodyToText(response); + const parsedXml = await (0, import_core_xml.parseXML)(bodyAsText, { + includeRoot: true + }); + return { + parsed: listBlobsXmlSerializer.deserialize( + Mappers.ListBlobsFlatSegmentResponse, + parsedXml.EnumerationResults ?? parsedXml, + "EnumerationResults" + ), + bodyAsText + }; + } + async function deserializeListBlobHierarchySegmentXml(response) { + const bodyAsText = await readResponseBodyToText(response); + const parsedXml = await (0, import_core_xml.parseXML)(bodyAsText, { + includeRoot: true + }); + return { + parsed: listBlobsXmlSerializer.deserialize( + Mappers.ListBlobsHierarchySegmentResponse, + parsedXml.EnumerationResults ?? parsedXml, + "EnumerationResults" + ), + bodyAsText + }; + } } }); // node_modules/@azure/storage-blob/dist/commonjs/sas/BlobSASPermissions.js var require_BlobSASPermissions = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/sas/BlobSASPermissions.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BlobSASPermissions = void 0; + "node_modules/@azure/storage-blob/dist/commonjs/sas/BlobSASPermissions.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BlobSASPermissions_exports = {}; + __export2(BlobSASPermissions_exports, { + BlobSASPermissions: () => BlobSASPermissions + }); + module2.exports = __toCommonJS2(BlobSASPermissions_exports); var BlobSASPermissions = class _BlobSASPermissions { /** * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an @@ -64652,16 +94076,34 @@ var require_BlobSASPermissions = __commonJS({ return permissions.join(""); } }; - exports2.BlobSASPermissions = BlobSASPermissions; } }); // node_modules/@azure/storage-blob/dist/commonjs/sas/ContainerSASPermissions.js var require_ContainerSASPermissions = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/sas/ContainerSASPermissions.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ContainerSASPermissions = void 0; + "node_modules/@azure/storage-blob/dist/commonjs/sas/ContainerSASPermissions.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var ContainerSASPermissions_exports = {}; + __export2(ContainerSASPermissions_exports, { + ContainerSASPermissions: () => ContainerSASPermissions + }); + module2.exports = __toCommonJS2(ContainerSASPermissions_exports); var ContainerSASPermissions = class _ContainerSASPermissions { /** * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an @@ -64871,59 +94313,34 @@ var require_ContainerSASPermissions = __commonJS({ return permissions.join(""); } }; - exports2.ContainerSASPermissions = ContainerSASPermissions; - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/credentials/UserDelegationKeyCredential.js -var require_UserDelegationKeyCredential = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/credentials/UserDelegationKeyCredential.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UserDelegationKeyCredential = void 0; - var node_crypto_1 = require("node:crypto"); - var UserDelegationKeyCredential = class { - /** - * Azure Storage account name; readonly. - */ - accountName; - /** - * Azure Storage user delegation key; readonly. - */ - userDelegationKey; - /** - * Key value in Buffer type. - */ - key; - /** - * Creates an instance of UserDelegationKeyCredential. - * @param accountName - - * @param userDelegationKey - - */ - constructor(accountName, userDelegationKey) { - this.accountName = accountName; - this.userDelegationKey = userDelegationKey; - this.key = Buffer.from(userDelegationKey.value, "base64"); - } - /** - * Generates a hash signature for an HTTP request or for a SAS. - * - * @param stringToSign - - */ - computeHMACSHA256(stringToSign) { - return (0, node_crypto_1.createHmac)("sha256", this.key).update(stringToSign, "utf8").digest("base64"); - } - }; - exports2.UserDelegationKeyCredential = UserDelegationKeyCredential; } }); // node_modules/@azure/storage-blob/dist/commonjs/sas/SasIPRange.js var require_SasIPRange = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/sas/SasIPRange.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ipRangeToString = ipRangeToString; + "node_modules/@azure/storage-blob/dist/commonjs/sas/SasIPRange.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var SasIPRange_exports = {}; + __export2(SasIPRange_exports, { + ipRangeToString: () => ipRangeToString + }); + module2.exports = __toCommonJS2(SasIPRange_exports); function ipRangeToString(ipRange) { return ipRange.end ? `${ipRange.start}-${ipRange.end}` : ipRange.start; } @@ -64932,17 +94349,37 @@ var require_SasIPRange = __commonJS({ // node_modules/@azure/storage-blob/dist/commonjs/sas/SASQueryParameters.js var require_SASQueryParameters = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/sas/SASQueryParameters.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SASQueryParameters = exports2.SASProtocol = void 0; - var SasIPRange_js_1 = require_SasIPRange(); - var utils_common_js_1 = require_utils_common(); - var SASProtocol; - (function(SASProtocol2) { + "node_modules/@azure/storage-blob/dist/commonjs/sas/SASQueryParameters.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var SASQueryParameters_exports = {}; + __export2(SASQueryParameters_exports, { + SASProtocol: () => SASProtocol, + SASQueryParameters: () => SASQueryParameters + }); + module2.exports = __toCommonJS2(SASQueryParameters_exports); + var import_SasIPRange = require_SasIPRange(); + var import_utils_common = require_utils_common2(); + var SASProtocol = /* @__PURE__ */ ((SASProtocol2) => { SASProtocol2["Https"] = "https"; SASProtocol2["HttpsAndHttp"] = "https,http"; - })(SASProtocol || (exports2.SASProtocol = SASProtocol = {})); + return SASProtocol2; + })(SASProtocol || {}); var SASQueryParameters = class { /** * The storage API version. @@ -64982,6 +94419,12 @@ var require_SASQueryParameters = __commonJS({ * @see https://learn.microsoft.com/rest/api/storageservices/establishing-a-stored-access-policy */ identifier; + /** + * Optional. Beginning in version 2025-07-05, this value specifies the Entra ID of the user would is authorized to + * use the resulting SAS URL. The resulting SAS URL must be used in conjunction with an Entra ID token that has been + * issued to the user specified in this value. + */ + delegatedUserObjectId; /** * Optional. Encryption scope to use when sending requests authorized with this SAS URI. */ @@ -65049,6 +94492,11 @@ var require_SASQueryParameters = __commonJS({ * Property of user delegation key. */ signedVersion; + /** + * The delegated user tenant id in Azure AD. + * Property of user delegation key. + */ + signedDelegatedUserTid; /** * Authorized AAD Object ID in GUID format. The AAD Object ID of a user authorized by the owner of the User Delegation Key * to perform the action granted by the SAS. The Azure Storage service will ensure that the owner of the user delegation key @@ -65061,6 +94509,18 @@ var require_SASQueryParameters = __commonJS({ * This is only used for User Delegation SAS. */ correlationId; + /** + * Keys for request headers required in the SAS token + */ + requestHeaderKeys; + /** + * Keys for request query parameters required in the SAS token + */ + requestQueryParameterKeys; + /** To indicate the depth of the virtual blob directory specified + * in the canonicalizedresource field of the string-to-sign. + */ + directoryDepth; /** * Optional. IP range allowed for this SAS. * @@ -65075,7 +94535,7 @@ var require_SASQueryParameters = __commonJS({ } return void 0; } - constructor(version, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey, preauthorizedAgentObjectId, correlationId, encryptionScope) { + constructor(version, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey, preauthorizedAgentObjectId, correlationId, encryptionScope, delegatedUserObjectId, requestHeaderKeys, requestQueryParameterKeys, directoryDepth) { this.version = version; this.signature = signature; if (permissionsOrOptions !== void 0 && typeof permissionsOrOptions !== "string") { @@ -65087,6 +94547,7 @@ var require_SASQueryParameters = __commonJS({ this.expiresOn = permissionsOrOptions.expiresOn; this.ipRangeInner = permissionsOrOptions.ipRange; this.identifier = permissionsOrOptions.identifier; + this.delegatedUserObjectId = permissionsOrOptions.delegatedUserObjectId; this.encryptionScope = permissionsOrOptions.encryptionScope; this.resource = permissionsOrOptions.resource; this.cacheControl = permissionsOrOptions.cacheControl; @@ -65094,6 +94555,9 @@ var require_SASQueryParameters = __commonJS({ this.contentEncoding = permissionsOrOptions.contentEncoding; this.contentLanguage = permissionsOrOptions.contentLanguage; this.contentType = permissionsOrOptions.contentType; + this.requestHeaderKeys = permissionsOrOptions.requestHeaderKeys; + this.requestQueryParameterKeys = permissionsOrOptions.requestQueryParameterKeys; + this.directoryDepth = permissionsOrOptions.directoryDepth; if (permissionsOrOptions.userDelegationKey) { this.signedOid = permissionsOrOptions.userDelegationKey.signedObjectId; this.signedTenantId = permissionsOrOptions.userDelegationKey.signedTenantId; @@ -65101,6 +94565,7 @@ var require_SASQueryParameters = __commonJS({ this.signedExpiresOn = permissionsOrOptions.userDelegationKey.signedExpiresOn; this.signedService = permissionsOrOptions.userDelegationKey.signedService; this.signedVersion = permissionsOrOptions.userDelegationKey.signedVersion; + this.signedDelegatedUserTid = permissionsOrOptions.userDelegationKey.signedDelegatedUserTenantId; this.preauthorizedAgentObjectId = permissionsOrOptions.preauthorizedAgentObjectId; this.correlationId = permissionsOrOptions.correlationId; } @@ -65112,6 +94577,7 @@ var require_SASQueryParameters = __commonJS({ this.protocol = protocol; this.startsOn = startsOn; this.ipRangeInner = ipRange; + this.delegatedUserObjectId = delegatedUserObjectId; this.encryptionScope = encryptionScope; this.identifier = identifier; this.resource = resource; @@ -65120,6 +94586,9 @@ var require_SASQueryParameters = __commonJS({ this.contentEncoding = contentEncoding; this.contentLanguage = contentLanguage; this.contentType = contentType; + this.requestHeaderKeys = requestHeaderKeys; + this.requestQueryParameterKeys = requestQueryParameterKeys; + this.directoryDepth = directoryDepth; if (userDelegationKey) { this.signedOid = userDelegationKey.signedObjectId; this.signedTenantId = userDelegationKey.signedTenantId; @@ -65127,6 +94596,7 @@ var require_SASQueryParameters = __commonJS({ this.signedExpiresOn = userDelegationKey.signedExpiresOn; this.signedService = userDelegationKey.signedService; this.signedVersion = userDelegationKey.signedVersion; + this.signedDelegatedUserTid = userDelegationKey.signedDelegatedUserTenantId; this.preauthorizedAgentObjectId = preauthorizedAgentObjectId; this.correlationId = correlationId; } @@ -65161,14 +94631,23 @@ var require_SASQueryParameters = __commonJS({ // Signed key version "sr", "sp", - "sig", "rscc", "rscd", "rsce", "rscl", "rsct", "saoid", - "scid" + "scid", + "sdd", + "sduoid", + // Signed key user delegation object ID + "skdutid", + // Signed key user delegation tenant ID + "srh", + // Request Headers + "srq", + // Request QueryParameters + "sig" ]; const queries = []; for (const param of params) { @@ -65186,13 +94665,25 @@ var require_SASQueryParameters = __commonJS({ this.tryAppendQueryParameter(queries, param, this.protocol); break; case "st": - this.tryAppendQueryParameter(queries, param, this.startsOn ? (0, utils_common_js_1.truncatedISO8061Date)(this.startsOn, false) : void 0); + this.tryAppendQueryParameter( + queries, + param, + this.startsOn ? (0, import_utils_common.truncatedISO8061Date)(this.startsOn, false) : void 0 + ); break; case "se": - this.tryAppendQueryParameter(queries, param, this.expiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(this.expiresOn, false) : void 0); + this.tryAppendQueryParameter( + queries, + param, + this.expiresOn ? (0, import_utils_common.truncatedISO8061Date)(this.expiresOn, false) : void 0 + ); break; case "sip": - this.tryAppendQueryParameter(queries, param, this.ipRange ? (0, SasIPRange_js_1.ipRangeToString)(this.ipRange) : void 0); + this.tryAppendQueryParameter( + queries, + param, + this.ipRange ? (0, import_SasIPRange.ipRangeToString)(this.ipRange) : void 0 + ); break; case "si": this.tryAppendQueryParameter(queries, param, this.identifier); @@ -65207,10 +94698,18 @@ var require_SASQueryParameters = __commonJS({ this.tryAppendQueryParameter(queries, param, this.signedTenantId); break; case "skt": - this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? (0, utils_common_js_1.truncatedISO8061Date)(this.signedStartsOn, false) : void 0); + this.tryAppendQueryParameter( + queries, + param, + this.signedStartsOn ? (0, import_utils_common.truncatedISO8061Date)(this.signedStartsOn, false) : void 0 + ); break; case "ske": - this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(this.signedExpiresOn, false) : void 0); + this.tryAppendQueryParameter( + queries, + param, + this.signedExpiresOn ? (0, import_utils_common.truncatedISO8061Date)(this.signedExpiresOn, false) : void 0 + ); break; case "sks": this.tryAppendQueryParameter(queries, param, this.signedService); @@ -65218,6 +94717,9 @@ var require_SASQueryParameters = __commonJS({ case "skv": this.tryAppendQueryParameter(queries, param, this.signedVersion); break; + case "skdutid": + this.tryAppendQueryParameter(queries, param, this.signedDelegatedUserTid); + break; case "sr": this.tryAppendQueryParameter(queries, param, this.resource); break; @@ -65248,6 +94750,22 @@ var require_SASQueryParameters = __commonJS({ case "scid": this.tryAppendQueryParameter(queries, param, this.correlationId); break; + case "sduoid": + this.tryAppendQueryParameter(queries, param, this.delegatedUserObjectId); + break; + case "srh": + this.tryAppendQueryParameter(queries, param, this.requestHeaderKeys); + break; + case "srq": + this.tryAppendQueryParameter(queries, param, this.requestQueryParameterKeys); + break; + case "sdd": + this.tryAppendQueryParameter( + queries, + param, + this.directoryDepth !== void 0 ? this.directoryDepth.toString() : "" + ); + break; } } return queries.join("&"); @@ -65270,34 +94788,59 @@ var require_SASQueryParameters = __commonJS({ } } }; - exports2.SASQueryParameters = SASQueryParameters; } }); // node_modules/@azure/storage-blob/dist/commonjs/sas/BlobSASSignatureValues.js var require_BlobSASSignatureValues = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/sas/BlobSASSignatureValues.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.generateBlobSASQueryParameters = generateBlobSASQueryParameters; - exports2.generateBlobSASQueryParametersInternal = generateBlobSASQueryParametersInternal; - var BlobSASPermissions_js_1 = require_BlobSASPermissions(); - var ContainerSASPermissions_js_1 = require_ContainerSASPermissions(); - var StorageSharedKeyCredential_js_1 = require_StorageSharedKeyCredential(); - var UserDelegationKeyCredential_js_1 = require_UserDelegationKeyCredential(); - var SasIPRange_js_1 = require_SasIPRange(); - var SASQueryParameters_js_1 = require_SASQueryParameters(); - var constants_js_1 = require_constants10(); - var utils_common_js_1 = require_utils_common(); - function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { - return generateBlobSASQueryParametersInternal(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName).sasQueryParameters; + "node_modules/@azure/storage-blob/dist/commonjs/sas/BlobSASSignatureValues.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BlobSASSignatureValues_exports = {}; + __export2(BlobSASSignatureValues_exports, { + generateBlobSASQueryParameters: () => generateBlobSASQueryParameters2, + generateBlobSASQueryParametersInternal: () => generateBlobSASQueryParametersInternal + }); + module2.exports = __toCommonJS2(BlobSASSignatureValues_exports); + var import_BlobSASPermissions = require_BlobSASPermissions(); + var import_ContainerSASPermissions = require_ContainerSASPermissions(); + var import_storage_common = require_commonjs12(); + var import_SasIPRange = require_SasIPRange(); + var import_SASQueryParameters = require_SASQueryParameters(); + var import_constants5 = require_constants11(); + var import_utils_common = require_utils_common2(); + var import_storage_common2 = require_commonjs12(); + function generateBlobSASQueryParameters2(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { + return generateBlobSASQueryParametersInternal( + blobSASSignatureValues, + sharedKeyCredentialOrUserDelegationKey, + accountName + ).sasQueryParameters; } function generateBlobSASQueryParametersInternal(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { - const version = blobSASSignatureValues.version ? blobSASSignatureValues.version : constants_js_1.SERVICE_VERSION; - const sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential ? sharedKeyCredentialOrUserDelegationKey : void 0; + const version = blobSASSignatureValues.version ? blobSASSignatureValues.version : import_constants5.SERVICE_VERSION; + const sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof import_storage_common.StorageSharedKeyCredential ? sharedKeyCredentialOrUserDelegationKey : void 0; let userDelegationKeyCredential; if (sharedKeyCredential === void 0 && accountName !== void 0) { - userDelegationKeyCredential = new UserDelegationKeyCredential_js_1.UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); + userDelegationKeyCredential = new import_storage_common2.UserDelegationKeyCredential( + accountName, + sharedKeyCredentialOrUserDelegationKey + ); } if (sharedKeyCredential === void 0 && userDelegationKeyCredential === void 0) { throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); @@ -65306,21 +94849,42 @@ var require_BlobSASSignatureValues = __commonJS({ if (sharedKeyCredential !== void 0) { return generateBlobSASQueryParameters20201206(blobSASSignatureValues, sharedKeyCredential); } else { - if (version >= "2025-07-05") { - return generateBlobSASQueryParametersUDK20250705(blobSASSignatureValues, userDelegationKeyCredential); + if (version >= "2026-04-06") { + return generateBlobSASQueryParametersUDK20260406( + blobSASSignatureValues, + userDelegationKeyCredential + ); + } else if (version >= "2025-07-05") { + return generateBlobSASQueryParametersUDK20250705( + blobSASSignatureValues, + userDelegationKeyCredential + ); } else { - return generateBlobSASQueryParametersUDK20201206(blobSASSignatureValues, userDelegationKeyCredential); + return generateBlobSASQueryParametersUDK20201206( + blobSASSignatureValues, + userDelegationKeyCredential + ); } } } if (version >= "2018-11-09") { if (sharedKeyCredential !== void 0) { - return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); + if (version >= "2020-02-10") { + return generateBlobSASQueryParameters20200210(blobSASSignatureValues, sharedKeyCredential); + } else { + return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); + } } else { if (version >= "2020-02-10") { - return generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential); + return generateBlobSASQueryParametersUDK20200210( + blobSASSignatureValues, + userDelegationKeyCredential + ); } else { - return generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential); + return generateBlobSASQueryParametersUDK20181109( + blobSASSignatureValues, + userDelegationKeyCredential + ); } } } @@ -65328,7 +94892,9 @@ var require_BlobSASSignatureValues = __commonJS({ if (sharedKeyCredential !== void 0) { return generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential); } else { - throw new RangeError("'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key."); + throw new RangeError( + "'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key." + ); } } throw new RangeError("'version' must be >= '2015-04-05'."); @@ -65336,7 +94902,9 @@ var require_BlobSASSignatureValues = __commonJS({ function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); if (!blobSASSignatureValues.identifier && !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + throw new RangeError( + "Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided." + ); } let resource = "c"; if (blobSASSignatureValues.blobName) { @@ -65345,18 +94913,26 @@ var require_BlobSASSignatureValues = __commonJS({ let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions_js_1.BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_BlobSASPermissions.BlobSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } else { - verifiedPermissions = ContainerSASPermissions_js_1.ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_ContainerSASPermissions.ContainerSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } } const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", - blobSASSignatureValues.expiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", - getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.startsOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName( + sharedKeyCredential.accountName, + blobSASSignatureValues.containerName, + blobSASSignatureValues.blobName + ), blobSASSignatureValues.identifier, - blobSASSignatureValues.ipRange ? (0, SasIPRange_js_1.ipRangeToString)(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.ipRange ? (0, import_SasIPRange.ipRangeToString)(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", @@ -65367,14 +94943,33 @@ var require_BlobSASSignatureValues = __commonJS({ ].join("\n"); const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return { - sasQueryParameters: new SASQueryParameters_js_1.SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, void 0, void 0, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType), + sasQueryParameters: new import_SASQueryParameters.SASQueryParameters( + blobSASSignatureValues.version, + signature, + verifiedPermissions, + void 0, + void 0, + blobSASSignatureValues.protocol, + blobSASSignatureValues.startsOn, + blobSASSignatureValues.expiresOn, + blobSASSignatureValues.ipRange, + blobSASSignatureValues.identifier, + resource, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType + ), stringToSign }; } function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); if (!blobSASSignatureValues.identifier && !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + throw new RangeError( + "Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided." + ); } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; @@ -65390,18 +94985,106 @@ var require_BlobSASSignatureValues = __commonJS({ let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions_js_1.BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_BlobSASPermissions.BlobSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); + } else { + verifiedPermissions = import_ContainerSASPermissions.ContainerSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); + } + } + const stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName( + sharedKeyCredential.accountName, + blobSASSignatureValues.containerName, + blobSASSignatureValues.blobName + ), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? (0, import_SasIPRange.ipRangeToString)(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return { + sasQueryParameters: new import_SASQueryParameters.SASQueryParameters( + blobSASSignatureValues.version, + signature, + verifiedPermissions, + void 0, + void 0, + blobSASSignatureValues.protocol, + blobSASSignatureValues.startsOn, + blobSASSignatureValues.expiresOn, + blobSASSignatureValues.ipRange, + blobSASSignatureValues.identifier, + resource, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType + ), + stringToSign + }; + } + function generateBlobSASQueryParameters20200210(blobSASSignatureValues, sharedKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + if (!blobSASSignatureValues.identifier && !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { + throw new RangeError( + "Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided." + ); + } + let resource = "c"; + let timestamp = blobSASSignatureValues.snapshotTime; + let directoryDepth = void 0; + if (blobSASSignatureValues.blobName) { + if (blobSASSignatureValues.isDirectory === true) { + resource = "d"; + directoryDepth = trimBlobName(blobSASSignatureValues.blobName).split("/").length; + } else { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + } + let verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = import_BlobSASPermissions.BlobSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } else { - verifiedPermissions = ContainerSASPermissions_js_1.ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_ContainerSASPermissions.ContainerSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } } const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", - blobSASSignatureValues.expiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", - getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.startsOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName( + sharedKeyCredential.accountName, + blobSASSignatureValues.containerName, + blobSASSignatureValues.blobName + ), blobSASSignatureValues.identifier, - blobSASSignatureValues.ipRange ? (0, SasIPRange_js_1.ipRangeToString)(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.ipRange ? (0, import_SasIPRange.ipRangeToString)(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, @@ -65414,41 +95097,82 @@ var require_BlobSASSignatureValues = __commonJS({ ].join("\n"); const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return { - sasQueryParameters: new SASQueryParameters_js_1.SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, void 0, void 0, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType), + sasQueryParameters: new import_SASQueryParameters.SASQueryParameters( + blobSASSignatureValues.version, + signature, + verifiedPermissions, + void 0, + void 0, + blobSASSignatureValues.protocol, + blobSASSignatureValues.startsOn, + blobSASSignatureValues.expiresOn, + blobSASSignatureValues.ipRange, + blobSASSignatureValues.identifier, + resource, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType, + void 0, + void 0, + void 0, + void 0, + void 0, + void 0, + void 0, + directoryDepth + ), stringToSign }; } function generateBlobSASQueryParameters20201206(blobSASSignatureValues, sharedKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); if (!blobSASSignatureValues.identifier && !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + throw new RangeError( + "Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided." + ); } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; + let directoryDepth = void 0; if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; + if (blobSASSignatureValues.isDirectory === true) { + resource = "d"; + directoryDepth = trimBlobName(blobSASSignatureValues.blobName).split("/").length; + } else { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } } } let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions_js_1.BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_BlobSASPermissions.BlobSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } else { - verifiedPermissions = ContainerSASPermissions_js_1.ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_ContainerSASPermissions.ContainerSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } } const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", - blobSASSignatureValues.expiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", - getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.startsOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName( + sharedKeyCredential.accountName, + blobSASSignatureValues.containerName, + blobSASSignatureValues.blobName + ), blobSASSignatureValues.identifier, - blobSASSignatureValues.ipRange ? (0, SasIPRange_js_1.ipRangeToString)(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.ipRange ? (0, import_SasIPRange.ipRangeToString)(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, @@ -65462,14 +95186,41 @@ var require_BlobSASSignatureValues = __commonJS({ ].join("\n"); const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return { - sasQueryParameters: new SASQueryParameters_js_1.SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, void 0, void 0, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, void 0, void 0, void 0, blobSASSignatureValues.encryptionScope), + sasQueryParameters: new import_SASQueryParameters.SASQueryParameters( + blobSASSignatureValues.version, + signature, + verifiedPermissions, + void 0, + void 0, + blobSASSignatureValues.protocol, + blobSASSignatureValues.startsOn, + blobSASSignatureValues.expiresOn, + blobSASSignatureValues.ipRange, + blobSASSignatureValues.identifier, + resource, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType, + void 0, + void 0, + void 0, + blobSASSignatureValues.encryptionScope, + void 0, + void 0, + void 0, + directoryDepth + ), stringToSign }; } function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + throw new RangeError( + "Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS." + ); } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; @@ -65485,23 +95236,31 @@ var require_BlobSASSignatureValues = __commonJS({ let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions_js_1.BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_BlobSASPermissions.BlobSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } else { - verifiedPermissions = ContainerSASPermissions_js_1.ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_ContainerSASPermissions.ContainerSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } } const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", - blobSASSignatureValues.expiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", - getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.startsOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName( + userDelegationKeyCredential.accountName, + blobSASSignatureValues.containerName, + blobSASSignatureValues.blobName + ), userDelegationKeyCredential.userDelegationKey.signedObjectId, userDelegationKeyCredential.userDelegationKey.signedTenantId, - userDelegationKeyCredential.userDelegationKey.signedStartsOn ? (0, utils_common_js_1.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", - userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedStartsOn ? (0, import_utils_common.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? (0, import_utils_common.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedService, userDelegationKeyCredential.userDelegationKey.signedVersion, - blobSASSignatureValues.ipRange ? (0, SasIPRange_js_1.ipRangeToString)(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.ipRange ? (0, import_SasIPRange.ipRangeToString)(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, @@ -65514,50 +95273,84 @@ var require_BlobSASSignatureValues = __commonJS({ ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return { - sasQueryParameters: new SASQueryParameters_js_1.SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, void 0, void 0, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey), + sasQueryParameters: new import_SASQueryParameters.SASQueryParameters( + blobSASSignatureValues.version, + signature, + verifiedPermissions, + void 0, + void 0, + blobSASSignatureValues.protocol, + blobSASSignatureValues.startsOn, + blobSASSignatureValues.expiresOn, + blobSASSignatureValues.ipRange, + blobSASSignatureValues.identifier, + resource, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType, + userDelegationKeyCredential.userDelegationKey + ), stringToSign }; } function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + throw new RangeError( + "Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS." + ); } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; + let directoryDepth = void 0; if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; + if (blobSASSignatureValues.isDirectory === true) { + resource = "d"; + directoryDepth = trimBlobName(blobSASSignatureValues.blobName).split("/").length; + } else { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } } } let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions_js_1.BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_BlobSASPermissions.BlobSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } else { - verifiedPermissions = ContainerSASPermissions_js_1.ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_ContainerSASPermissions.ContainerSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } } const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", - blobSASSignatureValues.expiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", - getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.startsOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName( + userDelegationKeyCredential.accountName, + blobSASSignatureValues.containerName, + blobSASSignatureValues.blobName + ), userDelegationKeyCredential.userDelegationKey.signedObjectId, userDelegationKeyCredential.userDelegationKey.signedTenantId, - userDelegationKeyCredential.userDelegationKey.signedStartsOn ? (0, utils_common_js_1.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", - userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedStartsOn ? (0, import_utils_common.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? (0, import_utils_common.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedService, userDelegationKeyCredential.userDelegationKey.signedVersion, blobSASSignatureValues.preauthorizedAgentObjectId, void 0, // agentObjectId blobSASSignatureValues.correlationId, - blobSASSignatureValues.ipRange ? (0, SasIPRange_js_1.ipRangeToString)(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.ipRange ? (0, import_SasIPRange.ipRangeToString)(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, @@ -65570,50 +95363,91 @@ var require_BlobSASSignatureValues = __commonJS({ ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return { - sasQueryParameters: new SASQueryParameters_js_1.SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, void 0, void 0, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId), + sasQueryParameters: new import_SASQueryParameters.SASQueryParameters( + blobSASSignatureValues.version, + signature, + verifiedPermissions, + void 0, + void 0, + blobSASSignatureValues.protocol, + blobSASSignatureValues.startsOn, + blobSASSignatureValues.expiresOn, + blobSASSignatureValues.ipRange, + blobSASSignatureValues.identifier, + resource, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType, + userDelegationKeyCredential.userDelegationKey, + blobSASSignatureValues.preauthorizedAgentObjectId, + blobSASSignatureValues.correlationId, + void 0, + void 0, + void 0, + void 0, + directoryDepth + ), stringToSign }; } function generateBlobSASQueryParametersUDK20201206(blobSASSignatureValues, userDelegationKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + throw new RangeError( + "Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS." + ); } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; + let directoryDepth = void 0; if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; + if (blobSASSignatureValues.isDirectory === true) { + resource = "d"; + directoryDepth = trimBlobName(blobSASSignatureValues.blobName).split("/").length; + } else { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } } } let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions_js_1.BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_BlobSASPermissions.BlobSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } else { - verifiedPermissions = ContainerSASPermissions_js_1.ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_ContainerSASPermissions.ContainerSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } } const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", - blobSASSignatureValues.expiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", - getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.startsOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName( + userDelegationKeyCredential.accountName, + blobSASSignatureValues.containerName, + blobSASSignatureValues.blobName + ), userDelegationKeyCredential.userDelegationKey.signedObjectId, userDelegationKeyCredential.userDelegationKey.signedTenantId, - userDelegationKeyCredential.userDelegationKey.signedStartsOn ? (0, utils_common_js_1.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", - userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedStartsOn ? (0, import_utils_common.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? (0, import_utils_common.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedService, userDelegationKeyCredential.userDelegationKey.signedVersion, blobSASSignatureValues.preauthorizedAgentObjectId, void 0, // agentObjectId blobSASSignatureValues.correlationId, - blobSASSignatureValues.ipRange ? (0, SasIPRange_js_1.ipRangeToString)(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.ipRange ? (0, import_SasIPRange.ipRangeToString)(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, @@ -65627,59 +95461,202 @@ var require_BlobSASSignatureValues = __commonJS({ ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return { - sasQueryParameters: new SASQueryParameters_js_1.SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, void 0, void 0, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId, blobSASSignatureValues.encryptionScope), + sasQueryParameters: new import_SASQueryParameters.SASQueryParameters( + blobSASSignatureValues.version, + signature, + verifiedPermissions, + void 0, + void 0, + blobSASSignatureValues.protocol, + blobSASSignatureValues.startsOn, + blobSASSignatureValues.expiresOn, + blobSASSignatureValues.ipRange, + blobSASSignatureValues.identifier, + resource, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType, + userDelegationKeyCredential.userDelegationKey, + blobSASSignatureValues.preauthorizedAgentObjectId, + blobSASSignatureValues.correlationId, + blobSASSignatureValues.encryptionScope, + void 0, + void 0, + void 0, + directoryDepth + ), stringToSign }; } function generateBlobSASQueryParametersUDK20250705(blobSASSignatureValues, userDelegationKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + throw new RangeError( + "Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS." + ); } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; + let directoryDepth = void 0; if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; + if (blobSASSignatureValues.isDirectory === true) { + resource = "d"; + directoryDepth = trimBlobName(blobSASSignatureValues.blobName).split("/").length; + } else { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } } } let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions_js_1.BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_BlobSASPermissions.BlobSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } else { - verifiedPermissions = ContainerSASPermissions_js_1.ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + verifiedPermissions = import_ContainerSASPermissions.ContainerSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); } } const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", - blobSASSignatureValues.expiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", - getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.startsOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName( + userDelegationKeyCredential.accountName, + blobSASSignatureValues.containerName, + blobSASSignatureValues.blobName + ), userDelegationKeyCredential.userDelegationKey.signedObjectId, userDelegationKeyCredential.userDelegationKey.signedTenantId, - userDelegationKeyCredential.userDelegationKey.signedStartsOn ? (0, utils_common_js_1.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", - userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedStartsOn ? (0, import_utils_common.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? (0, import_utils_common.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedService, userDelegationKeyCredential.userDelegationKey.signedVersion, blobSASSignatureValues.preauthorizedAgentObjectId, void 0, // agentObjectId blobSASSignatureValues.correlationId, - void 0, + userDelegationKeyCredential.userDelegationKey.signedDelegatedUserTenantId, // SignedKeyDelegatedUserTenantId, will be added in a future release. + blobSASSignatureValues.delegatedUserObjectId, + blobSASSignatureValues.ipRange ? (0, import_SasIPRange.ipRangeToString)(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp, + blobSASSignatureValues.encryptionScope, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType + ].join("\n"); + const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + return { + sasQueryParameters: new import_SASQueryParameters.SASQueryParameters( + blobSASSignatureValues.version, + signature, + verifiedPermissions, + void 0, + void 0, + blobSASSignatureValues.protocol, + blobSASSignatureValues.startsOn, + blobSASSignatureValues.expiresOn, + blobSASSignatureValues.ipRange, + blobSASSignatureValues.identifier, + resource, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType, + userDelegationKeyCredential.userDelegationKey, + blobSASSignatureValues.preauthorizedAgentObjectId, + blobSASSignatureValues.correlationId, + blobSASSignatureValues.encryptionScope, + blobSASSignatureValues.delegatedUserObjectId, + void 0, + void 0, + directoryDepth + ), + stringToSign + }; + } + function generateBlobSASQueryParametersUDK20260406(blobSASSignatureValues, userDelegationKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { + throw new RangeError( + "Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS." + ); + } + let resource = "c"; + let timestamp = blobSASSignatureValues.snapshotTime; + let directoryDepth = void 0; + if (blobSASSignatureValues.blobName) { + if (blobSASSignatureValues.isDirectory === true) { + resource = "d"; + directoryDepth = trimBlobName(blobSASSignatureValues.blobName).split("/").length; + } else { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + } + let verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = import_BlobSASPermissions.BlobSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); + } else { + verifiedPermissions = import_ContainerSASPermissions.ContainerSASPermissions.parse( + blobSASSignatureValues.permissions.toString() + ).toString(); + } + } + const stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? (0, import_utils_common.truncatedISO8061Date)(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName( + userDelegationKeyCredential.accountName, + blobSASSignatureValues.containerName, + blobSASSignatureValues.blobName + ), + userDelegationKeyCredential.userDelegationKey.signedObjectId, + userDelegationKeyCredential.userDelegationKey.signedTenantId, + userDelegationKeyCredential.userDelegationKey.signedStartsOn ? (0, import_utils_common.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? (0, import_utils_common.truncatedISO8061Date)(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedService, + userDelegationKeyCredential.userDelegationKey.signedVersion, + blobSASSignatureValues.preauthorizedAgentObjectId, void 0, - // SignedDelegatedUserObjectId, will be added in future release. - blobSASSignatureValues.ipRange ? (0, SasIPRange_js_1.ipRangeToString)(blobSASSignatureValues.ipRange) : "", + // agentObjectId + blobSASSignatureValues.correlationId, + userDelegationKeyCredential.userDelegationKey.signedDelegatedUserTenantId, + // SignedKeyDelegatedUserTenantId, will be added in a future release. + blobSASSignatureValues.delegatedUserObjectId, + blobSASSignatureValues.ipRange ? (0, import_SasIPRange.ipRangeToString)(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, timestamp, blobSASSignatureValues.encryptionScope, + formatRequestHeadersForSasSigning(blobSASSignatureValues.requestHeaders), + formatRequestQueryParametersForSasSigning(blobSASSignatureValues.requestQueryParameters), blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, @@ -65688,10 +95665,70 @@ var require_BlobSASSignatureValues = __commonJS({ ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return { - sasQueryParameters: new SASQueryParameters_js_1.SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, void 0, void 0, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId, blobSASSignatureValues.encryptionScope), + sasQueryParameters: new import_SASQueryParameters.SASQueryParameters( + blobSASSignatureValues.version, + signature, + verifiedPermissions, + void 0, + void 0, + blobSASSignatureValues.protocol, + blobSASSignatureValues.startsOn, + blobSASSignatureValues.expiresOn, + blobSASSignatureValues.ipRange, + blobSASSignatureValues.identifier, + resource, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType, + userDelegationKeyCredential.userDelegationKey, + blobSASSignatureValues.preauthorizedAgentObjectId, + blobSASSignatureValues.correlationId, + blobSASSignatureValues.encryptionScope, + blobSASSignatureValues.delegatedUserObjectId, + getKeysOfRequestHeaders(blobSASSignatureValues.requestHeaders), + getKeysOfRequestHeaders(blobSASSignatureValues.requestQueryParameters), + directoryDepth + ), stringToSign }; } + function formatRequestHeadersForSasSigning(requestHeaders) { + if (requestHeaders === void 0) { + return void 0; + } + let canonicalValue = ""; + Object.keys(requestHeaders).forEach(function(key) { + canonicalValue = canonicalValue + key + ":" + requestHeaders[key] + "\n"; + }); + return canonicalValue; + } + function formatRequestQueryParametersForSasSigning(queryParameters) { + if (queryParameters === void 0) { + return void 0; + } + let canonicalValue = ""; + Object.keys(queryParameters).forEach(function(key) { + canonicalValue = canonicalValue + "\n" + key + ":" + queryParameters[key]; + }); + return canonicalValue; + } + function getKeysOfRequestHeaders(requestHeaders) { + if (requestHeaders === void 0) { + return void 0; + } + let requestKeys = ""; + let index2 = 0; + Object.keys(requestHeaders).forEach(function(key) { + if (index2 !== 0) { + requestKeys = requestKeys + ","; + } + requestKeys = requestKeys + key; + ++index2; + }); + return requestKeys; + } function getCanonicalName(accountName, containerName, blobName) { const elements = [`/blob/${accountName}/${containerName}`]; if (blobName) { @@ -65700,7 +95737,7 @@ var require_BlobSASSignatureValues = __commonJS({ return elements.join(""); } function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { - const version = blobSASSignatureValues.version ? blobSASSignatureValues.version : constants_js_1.SERVICE_VERSION; + const version = blobSASSignatureValues.version ? blobSASSignatureValues.version : import_constants5.SERVICE_VERSION; if (blobSASSignatureValues.snapshotTime && version < "2018-11-09") { throw RangeError("'version' must be >= '2018-11-09' when providing 'snapshotTime'."); } @@ -65732,7 +95769,9 @@ var require_BlobSASSignatureValues = __commonJS({ throw RangeError("'version' must be >= '2021-04-10' when providing the 'f' permission."); } if (version < "2020-02-10" && (blobSASSignatureValues.preauthorizedAgentObjectId || blobSASSignatureValues.correlationId)) { - throw RangeError("'version' must be >= '2020-02-10' when providing 'preauthorizedAgentObjectId' or 'correlationId'."); + throw RangeError( + "'version' must be >= '2020-02-10' when providing 'preauthorizedAgentObjectId' or 'correlationId'." + ); } if (blobSASSignatureValues.encryptionScope && version < "2020-12-06") { throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS."); @@ -65740,19 +95779,48 @@ var require_BlobSASSignatureValues = __commonJS({ blobSASSignatureValues.version = version; return blobSASSignatureValues; } + function trimBlobName(blobName) { + let internalName = blobName; + while (internalName.startsWith("/")) { + internalName = internalName.substring(1); + } + while (internalName.endsWith("/")) { + internalName = internalName.substring(0, internalName.length - 1); + } + return internalName; + } } }); // node_modules/@azure/storage-blob/dist/commonjs/BlobLeaseClient.js var require_BlobLeaseClient = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/BlobLeaseClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BlobLeaseClient = void 0; - var core_util_1 = require_commonjs4(); - var constants_js_1 = require_constants10(); - var tracing_js_1 = require_tracing(); - var utils_common_js_1 = require_utils_common(); + "node_modules/@azure/storage-blob/dist/commonjs/BlobLeaseClient.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BlobLeaseClient_exports = {}; + __export2(BlobLeaseClient_exports, { + BlobLeaseClient: () => BlobLeaseClient + }); + module2.exports = __toCommonJS2(BlobLeaseClient_exports); + var import_core_util = require_commonjs4(); + var import_constants5 = require_constants11(); + var import_tracing = require_tracing(); + var import_utils_common = require_utils_common2(); var BlobLeaseClient = class { _leaseId; _url; @@ -65790,7 +95858,7 @@ var require_BlobLeaseClient = __commonJS({ this._containerOrBlobOperation = clientContext.blob; } if (!leaseId) { - leaseId = (0, core_util_1.randomUUID)(); + leaseId = (0, import_core_util.randomUUID)(); } this._leaseId = leaseId; } @@ -65807,21 +95875,29 @@ var require_BlobLeaseClient = __commonJS({ * @returns Response data for acquire lease operation. */ async acquireLease(duration, options = {}) { - if (this._isContainer && (options.conditions?.ifMatch && options.conditions?.ifMatch !== constants_js_1.ETagNone || options.conditions?.ifNoneMatch && options.conditions?.ifNoneMatch !== constants_js_1.ETagNone || options.conditions?.tagConditions)) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + if (this._isContainer && (options.conditions?.ifMatch && options.conditions?.ifMatch !== import_constants5.ETagNone || options.conditions?.ifNoneMatch && options.conditions?.ifNoneMatch !== import_constants5.ETagNone || options.conditions?.tagConditions)) { + throw new RangeError( + "The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable." + ); } - return tracing_js_1.tracingClient.withSpan("BlobLeaseClient-acquireLease", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this._containerOrBlobOperation.acquireLease({ - abortSignal: options.abortSignal, - duration, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - proposedLeaseId: this._leaseId, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "BlobLeaseClient-acquireLease", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this._containerOrBlobOperation.acquireLease({ + abortSignal: options.abortSignal, + duration, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + proposedLeaseId: this._leaseId, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * To change the ID of the lease. @@ -65834,21 +95910,29 @@ var require_BlobLeaseClient = __commonJS({ * @returns Response data for change lease operation. */ async changeLease(proposedLeaseId, options = {}) { - if (this._isContainer && (options.conditions?.ifMatch && options.conditions?.ifMatch !== constants_js_1.ETagNone || options.conditions?.ifNoneMatch && options.conditions?.ifNoneMatch !== constants_js_1.ETagNone || options.conditions?.tagConditions)) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + if (this._isContainer && (options.conditions?.ifMatch && options.conditions?.ifMatch !== import_constants5.ETagNone || options.conditions?.ifNoneMatch && options.conditions?.ifNoneMatch !== import_constants5.ETagNone || options.conditions?.tagConditions)) { + throw new RangeError( + "The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable." + ); } - return tracing_js_1.tracingClient.withSpan("BlobLeaseClient-changeLease", options, async (updatedOptions) => { - const response = (0, utils_common_js_1.assertResponse)(await this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId, { - abortSignal: options.abortSignal, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - tracingOptions: updatedOptions.tracingOptions - })); - this._leaseId = proposedLeaseId; - return response; - }); + return import_tracing.tracingClient.withSpan( + "BlobLeaseClient-changeLease", + options, + async (updatedOptions) => { + const response = (0, import_utils_common.assertResponse)( + await this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId, { + abortSignal: options.abortSignal, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + tracingOptions: updatedOptions.tracingOptions + }) + ); + this._leaseId = proposedLeaseId; + return response; + } + ); } /** * To free the lease if it is no longer needed so that another client may @@ -65861,19 +95945,27 @@ var require_BlobLeaseClient = __commonJS({ * @returns Response data for release lease operation. */ async releaseLease(options = {}) { - if (this._isContainer && (options.conditions?.ifMatch && options.conditions?.ifMatch !== constants_js_1.ETagNone || options.conditions?.ifNoneMatch && options.conditions?.ifNoneMatch !== constants_js_1.ETagNone || options.conditions?.tagConditions)) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + if (this._isContainer && (options.conditions?.ifMatch && options.conditions?.ifMatch !== import_constants5.ETagNone || options.conditions?.ifNoneMatch && options.conditions?.ifNoneMatch !== import_constants5.ETagNone || options.conditions?.tagConditions)) { + throw new RangeError( + "The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable." + ); } - return tracing_js_1.tracingClient.withSpan("BlobLeaseClient-releaseLease", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this._containerOrBlobOperation.releaseLease(this._leaseId, { - abortSignal: options.abortSignal, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "BlobLeaseClient-releaseLease", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this._containerOrBlobOperation.releaseLease(this._leaseId, { + abortSignal: options.abortSignal, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * To renew the lease. @@ -65885,10 +95977,12 @@ var require_BlobLeaseClient = __commonJS({ * @returns Response data for renew lease operation. */ async renewLease(options = {}) { - if (this._isContainer && (options.conditions?.ifMatch && options.conditions?.ifMatch !== constants_js_1.ETagNone || options.conditions?.ifNoneMatch && options.conditions?.ifNoneMatch !== constants_js_1.ETagNone || options.conditions?.tagConditions)) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + if (this._isContainer && (options.conditions?.ifMatch && options.conditions?.ifMatch !== import_constants5.ETagNone || options.conditions?.ifNoneMatch && options.conditions?.ifNoneMatch !== import_constants5.ETagNone || options.conditions?.tagConditions)) { + throw new RangeError( + "The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable." + ); } - return tracing_js_1.tracingClient.withSpan("BlobLeaseClient-renewLease", options, async (updatedOptions) => { + return import_tracing.tracingClient.withSpan("BlobLeaseClient-renewLease", options, async (updatedOptions) => { return this._containerOrBlobOperation.renewLease(this._leaseId, { abortSignal: options.abortSignal, modifiedAccessConditions: { @@ -65911,10 +96005,12 @@ var require_BlobLeaseClient = __commonJS({ * @returns Response data for break lease operation. */ async breakLease(breakPeriod, options = {}) { - if (this._isContainer && (options.conditions?.ifMatch && options.conditions?.ifMatch !== constants_js_1.ETagNone || options.conditions?.ifNoneMatch && options.conditions?.ifNoneMatch !== constants_js_1.ETagNone || options.conditions?.tagConditions)) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + if (this._isContainer && (options.conditions?.ifMatch && options.conditions?.ifMatch !== import_constants5.ETagNone || options.conditions?.ifNoneMatch && options.conditions?.ifNoneMatch !== import_constants5.ETagNone || options.conditions?.tagConditions)) { + throw new RangeError( + "The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable." + ); } - return tracing_js_1.tracingClient.withSpan("BlobLeaseClient-breakLease", options, async (updatedOptions) => { + return import_tracing.tracingClient.withSpan("BlobLeaseClient-breakLease", options, async (updatedOptions) => { const operationOptions = { abortSignal: options.abortSignal, breakPeriod, @@ -65924,23 +96020,72 @@ var require_BlobLeaseClient = __commonJS({ }, tracingOptions: updatedOptions.tracingOptions }; - return (0, utils_common_js_1.assertResponse)(await this._containerOrBlobOperation.breakLease(operationOptions)); + return (0, import_utils_common.assertResponse)( + await this._containerOrBlobOperation.breakLease(operationOptions) + ); }); } }; - exports2.BlobLeaseClient = BlobLeaseClient; } }); -// node_modules/@azure/storage-blob/dist/commonjs/utils/RetriableReadableStream.js -var require_RetriableReadableStream = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/utils/RetriableReadableStream.js"(exports2) { +// node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError4 = __commonJS({ + "node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError2 = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } + }; + exports2.AbortError = AbortError2; + } +}); + +// node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs13 = __commonJS({ + "node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RetriableReadableStream = void 0; - var abort_controller_1 = require_commonjs11(); - var node_stream_1 = require("node:stream"); - var RetriableReadableStream = class extends node_stream_1.Readable { + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError4(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); + } +}); + +// node_modules/@azure/storage-blob/dist/commonjs/utils/RetriableReadableStream.js +var require_RetriableReadableStream = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/utils/RetriableReadableStream.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var RetriableReadableStream_exports = {}; + __export2(RetriableReadableStream_exports, { + RetriableReadableStream: () => RetriableReadableStream + }); + module2.exports = __toCommonJS2(RetriableReadableStream_exports); + var import_abort_controller = require_commonjs13(); + var import_node_stream5 = require("node:stream"); + var RetriableReadableStream = class extends import_node_stream5.Readable { start; offset; end; @@ -66004,7 +96149,7 @@ var require_RetriableReadableStream = __commonJS({ } }; sourceAbortedHandler = () => { - const abortError = new abort_controller_1.AbortError("The operation was aborted."); + const abortError = new import_abort_controller.AbortError("The operation was aborted."); this.destroy(abortError); }; sourceErrorOrEndHandler = (err) => { @@ -66026,10 +96171,18 @@ var require_RetriableReadableStream = __commonJS({ this.destroy(error3); }); } else { - this.destroy(new Error(`Data corruption failure: received less data than required and reached maxRetires limitation. Received data offset: ${this.offset - 1}, data needed offset: ${this.end}, retries: ${this.retries}, max retries: ${this.maxRetryRequests}`)); + this.destroy( + new Error( + `Data corruption failure: received less data than required and reached maxRetires limitation. Received data offset: ${this.offset - 1}, data needed offset: ${this.end}, retries: ${this.retries}, max retries: ${this.maxRetryRequests}` + ) + ); } } else { - this.destroy(new Error(`Data corruption failure: Received more data than original request, data needed offset is ${this.end}, received offset: ${this.offset - 1}`)); + this.destroy( + new Error( + `Data corruption failure: Received more data than original request, data needed offset is ${this.end}, received offset: ${this.offset - 1}` + ) + ); } }; _destroy(error3, callback) { @@ -66038,18 +96191,37 @@ var require_RetriableReadableStream = __commonJS({ callback(error3 === null ? void 0 : error3); } }; - exports2.RetriableReadableStream = RetriableReadableStream; } }); // node_modules/@azure/storage-blob/dist/commonjs/BlobDownloadResponse.js var require_BlobDownloadResponse = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/BlobDownloadResponse.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BlobDownloadResponse = void 0; - var core_util_1 = require_commonjs4(); - var RetriableReadableStream_js_1 = require_RetriableReadableStream(); + "node_modules/@azure/storage-blob/dist/commonjs/BlobDownloadResponse.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BlobDownloadResponse_exports = {}; + __export2(BlobDownloadResponse_exports, { + BlobDownloadResponse: () => BlobDownloadResponse + }); + module2.exports = __toCommonJS2(BlobDownloadResponse_exports); + var import_core_util = require_commonjs4(); + var import_storage_common = require_commonjs12(); + var import_RetriableReadableStream = require_RetriableReadableStream(); var BlobDownloadResponse = class { /** * Indicates that the service supports @@ -66458,6 +96630,46 @@ var require_BlobDownloadResponse = __commonJS({ get legalHold() { return this.originalResponse.legalHold; } + /** + * The access tier of the blob. Values include premium page-blob tiers and block-blob tiers + * such as Hot, Cool, Cold, Archive, and Smart. See + * https://learn.microsoft.com/azure/storage/blobs/storage-blob-storage-tiers. + * + * @readonly + */ + get accessTier() { + return this.originalResponse.accessTier; + } + /** + * For page blobs on a premium storage account only. If the access tier is not explicitly set on + * the blob, the tier is inferred based on its content length and this header will be returned + * with true value. + * + * @readonly + */ + get accessTierInferred() { + return this.originalResponse.accessTierInferred; + } + /** + * The time the tier was changed on the object. This is only returned if the tier on the block + * blob was ever set. + * + * @readonly + */ + get accessTierChangedOn() { + return this.originalResponse.accessTierChangedOn; + } + /** + * The underlying tier of a smart tier blob. Only returned if the blob is in Smart tier. + * + * @readonly + */ + get smartAccessTier() { + return this.originalResponse.smartAccessTier; + } + get structuredBodyType() { + return this.originalResponse.structuredBodyType; + } /** * The response body as a browser Blob. * Always undefined in node.js. @@ -66476,7 +96688,7 @@ var require_BlobDownloadResponse = __commonJS({ * @readonly */ get readableStreamBody() { - return core_util_1.isNodeLike ? this.blobDownloadStream : void 0; + return import_core_util.isNodeLike ? this.blobDownloadStream : void 0; } /** * The HTTP response. @@ -66497,32 +96709,80 @@ var require_BlobDownloadResponse = __commonJS({ */ constructor(originalResponse, getter, offset, count, options = {}) { this.originalResponse = originalResponse; - this.blobDownloadStream = new RetriableReadableStream_js_1.RetriableReadableStream(this.originalResponse.readableStreamBody, getter, offset, count, options); + const streamBody = this.originalResponse.structuredBodyType === void 0 ? this.originalResponse.readableStreamBody : (0, import_storage_common.structuredMessageDecodingStream)(this.originalResponse.readableStreamBody, options); + this.blobDownloadStream = new import_RetriableReadableStream.RetriableReadableStream( + streamBody, + getter, + offset, + count, + options + ); } }; - exports2.BlobDownloadResponse = BlobDownloadResponse; } }); // node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroConstants.js var require_AvroConstants = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroConstants.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AVRO_SCHEMA_KEY = exports2.AVRO_CODEC_KEY = exports2.AVRO_INIT_BYTES = exports2.AVRO_SYNC_MARKER_SIZE = void 0; - exports2.AVRO_SYNC_MARKER_SIZE = 16; - exports2.AVRO_INIT_BYTES = new Uint8Array([79, 98, 106, 1]); - exports2.AVRO_CODEC_KEY = "avro.codec"; - exports2.AVRO_SCHEMA_KEY = "avro.schema"; + "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroConstants.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var AvroConstants_exports = {}; + __export2(AvroConstants_exports, { + AVRO_CODEC_KEY: () => AVRO_CODEC_KEY, + AVRO_INIT_BYTES: () => AVRO_INIT_BYTES, + AVRO_SCHEMA_KEY: () => AVRO_SCHEMA_KEY, + AVRO_SYNC_MARKER_SIZE: () => AVRO_SYNC_MARKER_SIZE + }); + module2.exports = __toCommonJS2(AvroConstants_exports); + var AVRO_SYNC_MARKER_SIZE = 16; + var AVRO_INIT_BYTES = new Uint8Array([79, 98, 106, 1]); + var AVRO_CODEC_KEY = "avro.codec"; + var AVRO_SCHEMA_KEY = "avro.schema"; } }); // node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroParser.js var require_AvroParser = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroParser.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AvroType = exports2.AvroParser = void 0; + "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroParser.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var AvroParser_exports = {}; + __export2(AvroParser_exports, { + AvroParser: () => AvroParser, + AvroType: () => AvroType + }); + module2.exports = __toCommonJS2(AvroParser_exports); var AvroParser = class _AvroParser { /** * Reads a fixed number of bytes from the stream. @@ -66649,28 +96909,8 @@ var require_AvroParser = __commonJS({ return items; } }; - exports2.AvroParser = AvroParser; - var AvroComplex; - (function(AvroComplex2) { - AvroComplex2["RECORD"] = "record"; - AvroComplex2["ENUM"] = "enum"; - AvroComplex2["ARRAY"] = "array"; - AvroComplex2["MAP"] = "map"; - AvroComplex2["UNION"] = "union"; - AvroComplex2["FIXED"] = "fixed"; - })(AvroComplex || (AvroComplex = {})); - var AvroPrimitive; - (function(AvroPrimitive2) { - AvroPrimitive2["NULL"] = "null"; - AvroPrimitive2["BOOLEAN"] = "boolean"; - AvroPrimitive2["INT"] = "int"; - AvroPrimitive2["LONG"] = "long"; - AvroPrimitive2["FLOAT"] = "float"; - AvroPrimitive2["DOUBLE"] = "double"; - AvroPrimitive2["BYTES"] = "bytes"; - AvroPrimitive2["STRING"] = "string"; - })(AvroPrimitive || (AvroPrimitive = {})); var AvroType = class _AvroType { + // eslint-disable-line @typescript-eslint/no-wrapper-object-types /** * Determines the AvroType from the Avro Schema. */ @@ -66686,14 +96926,14 @@ var require_AvroParser = __commonJS({ } static fromStringSchema(schema) { switch (schema) { - case AvroPrimitive.NULL: - case AvroPrimitive.BOOLEAN: - case AvroPrimitive.INT: - case AvroPrimitive.LONG: - case AvroPrimitive.FLOAT: - case AvroPrimitive.DOUBLE: - case AvroPrimitive.BYTES: - case AvroPrimitive.STRING: + case "null": + case "boolean": + case "int": + case "long": + case "float": + case "double": + case "bytes": + case "string": return new AvroPrimitiveType(schema); default: throw new Error(`Unexpected Avro type ${schema}`); @@ -66709,7 +96949,7 @@ var require_AvroParser = __commonJS({ } catch { } switch (type) { - case AvroComplex.RECORD: + case "record": if (schema.aliases) { throw new Error(`aliases currently is not supported, schema: ${schema}`); } @@ -66724,7 +96964,7 @@ var require_AvroParser = __commonJS({ fields[field.name] = _AvroType.fromSchema(field.type); } return new AvroRecordType(fields, schema.name); - case AvroComplex.ENUM: + case "enum": if (schema.aliases) { throw new Error(`aliases currently is not supported, schema: ${schema}`); } @@ -66732,21 +96972,20 @@ var require_AvroParser = __commonJS({ throw new Error(`Required attribute 'symbols' doesn't exist on schema: ${schema}`); } return new AvroEnumType(schema.symbols); - case AvroComplex.MAP: + case "map": if (!schema.values) { throw new Error(`Required attribute 'values' doesn't exist on schema: ${schema}`); } return new AvroMapType(_AvroType.fromSchema(schema.values)); - case AvroComplex.ARRAY: + case "array": // Unused today - case AvroComplex.FIXED: + case "fixed": // Unused today default: throw new Error(`Unexpected Avro type ${type} in ${schema}`); } } }; - exports2.AvroType = AvroType; var AvroPrimitiveType = class extends AvroType { _primitive; constructor(primitive) { @@ -66756,21 +96995,21 @@ var require_AvroParser = __commonJS({ // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types read(stream2, options = {}) { switch (this._primitive) { - case AvroPrimitive.NULL: + case "null": return AvroParser.readNull(); - case AvroPrimitive.BOOLEAN: + case "boolean": return AvroParser.readBoolean(stream2, options); - case AvroPrimitive.INT: + case "int": return AvroParser.readInt(stream2, options); - case AvroPrimitive.LONG: + case "long": return AvroParser.readLong(stream2, options); - case AvroPrimitive.FLOAT: + case "float": return AvroParser.readFloat(stream2, options); - case AvroPrimitive.DOUBLE: + case "double": return AvroParser.readDouble(stream2, options); - case AvroPrimitive.BYTES: + case "bytes": return AvroParser.readBytes(stream2, options); - case AvroPrimitive.STRING: + case "string": return AvroParser.readString(stream2, options); default: throw new Error("Unknown Avro Primitive"); @@ -66839,20 +97078,35 @@ var require_AvroParser = __commonJS({ // node_modules/@azure/storage-blob/dist/commonjs/internal-avro/utils/utils.common.js var require_utils_common3 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/utils/utils.common.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.arraysEqual = arraysEqual; + "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/utils/utils.common.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var utils_common_exports = {}; + __export2(utils_common_exports, { + arraysEqual: () => arraysEqual + }); + module2.exports = __toCommonJS2(utils_common_exports); function arraysEqual(a, b) { - if (a === b) - return true; - if (a == null || b == null) - return false; - if (a.length !== b.length) - return false; + if (a === b) return true; + if (a == null || b == null) return false; + if (a.length !== b.length) return false; for (let i = 0; i < a.length; ++i) { - if (a[i] !== b[i]) - return false; + if (a[i] !== b[i]) return false; } return true; } @@ -66861,14 +97115,33 @@ var require_utils_common3 = __commonJS({ // node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroReader.js var require_AvroReader = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroReader.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AvroReader = void 0; - var AvroConstants_js_1 = require_AvroConstants(); - var AvroParser_js_1 = require_AvroParser(); - var utils_common_js_1 = require_utils_common3(); - var AvroReader = class { + "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroReader.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var AvroReader_exports = {}; + __export2(AvroReader_exports, { + AvroReader: () => AvroReader2 + }); + module2.exports = __toCommonJS2(AvroReader_exports); + var import_AvroConstants = require_AvroConstants(); + var import_AvroParser = require_AvroParser(); + var import_utils_common = require_utils_common3(); + var AvroReader2 = class { _dataStream; _headerStream; _syncMarker; @@ -66897,31 +97170,31 @@ var require_AvroReader = __commonJS({ this._initialBlockOffset = currentBlockOffset || 0; } async initialize(options = {}) { - const header = await AvroParser_js_1.AvroParser.readFixedBytes(this._headerStream, AvroConstants_js_1.AVRO_INIT_BYTES.length, { + const header = await import_AvroParser.AvroParser.readFixedBytes(this._headerStream, import_AvroConstants.AVRO_INIT_BYTES.length, { abortSignal: options.abortSignal }); - if (!(0, utils_common_js_1.arraysEqual)(header, AvroConstants_js_1.AVRO_INIT_BYTES)) { + if (!(0, import_utils_common.arraysEqual)(header, import_AvroConstants.AVRO_INIT_BYTES)) { throw new Error("Stream is not an Avro file."); } - this._metadata = await AvroParser_js_1.AvroParser.readMap(this._headerStream, AvroParser_js_1.AvroParser.readString, { + this._metadata = await import_AvroParser.AvroParser.readMap(this._headerStream, import_AvroParser.AvroParser.readString, { abortSignal: options.abortSignal }); - const codec = this._metadata[AvroConstants_js_1.AVRO_CODEC_KEY]; + const codec = this._metadata[import_AvroConstants.AVRO_CODEC_KEY]; if (!(codec === void 0 || codec === null || codec === "null")) { throw new Error("Codecs are not supported"); } - this._syncMarker = await AvroParser_js_1.AvroParser.readFixedBytes(this._headerStream, AvroConstants_js_1.AVRO_SYNC_MARKER_SIZE, { + this._syncMarker = await import_AvroParser.AvroParser.readFixedBytes(this._headerStream, import_AvroConstants.AVRO_SYNC_MARKER_SIZE, { abortSignal: options.abortSignal }); - const schema = JSON.parse(this._metadata[AvroConstants_js_1.AVRO_SCHEMA_KEY]); - this._itemType = AvroParser_js_1.AvroType.fromSchema(schema); + const schema = JSON.parse(this._metadata[import_AvroConstants.AVRO_SCHEMA_KEY]); + this._itemType = import_AvroParser.AvroType.fromSchema(schema); if (this._blockOffset === 0) { this._blockOffset = this._initialBlockOffset + this._dataStream.position; } - this._itemsRemainingInBlock = await AvroParser_js_1.AvroParser.readLong(this._dataStream, { + this._itemsRemainingInBlock = await import_AvroParser.AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }); - await AvroParser_js_1.AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }); + await import_AvroParser.AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }); this._initialized = true; if (this._objectIndex && this._objectIndex > 0) { for (let i = 0; i < this._objectIndex; i++) { @@ -66944,61 +97217,97 @@ var require_AvroReader = __commonJS({ this._itemsRemainingInBlock--; this._objectIndex++; if (this._itemsRemainingInBlock === 0) { - const marker = await AvroParser_js_1.AvroParser.readFixedBytes(this._dataStream, AvroConstants_js_1.AVRO_SYNC_MARKER_SIZE, { + const marker = await import_AvroParser.AvroParser.readFixedBytes(this._dataStream, import_AvroConstants.AVRO_SYNC_MARKER_SIZE, { abortSignal: options.abortSignal }); this._blockOffset = this._initialBlockOffset + this._dataStream.position; this._objectIndex = 0; - if (!(0, utils_common_js_1.arraysEqual)(this._syncMarker, marker)) { + if (!(0, import_utils_common.arraysEqual)(this._syncMarker, marker)) { throw new Error("Stream is not a valid Avro file."); } try { - this._itemsRemainingInBlock = await AvroParser_js_1.AvroParser.readLong(this._dataStream, { + this._itemsRemainingInBlock = await import_AvroParser.AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }); } catch { this._itemsRemainingInBlock = 0; } if (this._itemsRemainingInBlock > 0) { - await AvroParser_js_1.AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }); + await import_AvroParser.AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }); } } yield result; } } }; - exports2.AvroReader = AvroReader; } }); // node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroReadable.js var require_AvroReadable = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroReadable.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AvroReadable = void 0; - var AvroReadable = class { + "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroReadable.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var AvroReadable_exports = {}; + __export2(AvroReadable_exports, { + AvroReadable: () => AvroReadable2 + }); + module2.exports = __toCommonJS2(AvroReadable_exports); + var AvroReadable2 = class { }; - exports2.AvroReadable = AvroReadable; } }); // node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroReadableFromStream.js var require_AvroReadableFromStream = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroReadableFromStream.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AvroReadableFromStream = void 0; - var AvroReadable_js_1 = require_AvroReadable(); - var abort_controller_1 = require_commonjs11(); - var buffer_1 = require("buffer"); - var ABORT_ERROR = new abort_controller_1.AbortError("Reading from the avro stream was aborted."); - var AvroReadableFromStream = class extends AvroReadable_js_1.AvroReadable { + "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/AvroReadableFromStream.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var AvroReadableFromStream_exports = {}; + __export2(AvroReadableFromStream_exports, { + AvroReadableFromStream: () => AvroReadableFromStream2 + }); + module2.exports = __toCommonJS2(AvroReadableFromStream_exports); + var import_AvroReadable = require_AvroReadable(); + var import_abort_controller = require_commonjs13(); + var import_buffer30 = require("buffer"); + var ABORT_ERROR = new import_abort_controller.AbortError("Reading from the avro stream was aborted."); + var AvroReadableFromStream2 = class extends import_AvroReadable.AvroReadable { _position; _readable; toUint8Array(data) { if (typeof data === "string") { - return buffer_1.Buffer.from(data); + return import_buffer30.Buffer.from(data); } return data; } @@ -67028,7 +97337,7 @@ var require_AvroReadableFromStream = __commonJS({ this._position += chunk.length; return this.toUint8Array(chunk); } else { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { const cleanUp = () => { this._readable.removeListener("readable", readableCallback); this._readable.removeListener("error", rejectCallback); @@ -67043,7 +97352,7 @@ var require_AvroReadableFromStream = __commonJS({ if (callbackChunk) { this._position += callbackChunk.length; cleanUp(); - resolve14(this.toUint8Array(callbackChunk)); + resolve15(this.toUint8Array(callbackChunk)); } }; const rejectCallback = () => { @@ -67065,40 +97374,70 @@ var require_AvroReadableFromStream = __commonJS({ } } }; - exports2.AvroReadableFromStream = AvroReadableFromStream; } }); // node_modules/@azure/storage-blob/dist/commonjs/internal-avro/index.js var require_internal_avro = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AvroReadableFromStream = exports2.AvroReadable = exports2.AvroReader = void 0; - var AvroReader_js_1 = require_AvroReader(); - Object.defineProperty(exports2, "AvroReader", { enumerable: true, get: function() { - return AvroReader_js_1.AvroReader; - } }); - var AvroReadable_js_1 = require_AvroReadable(); - Object.defineProperty(exports2, "AvroReadable", { enumerable: true, get: function() { - return AvroReadable_js_1.AvroReadable; - } }); - var AvroReadableFromStream_js_1 = require_AvroReadableFromStream(); - Object.defineProperty(exports2, "AvroReadableFromStream", { enumerable: true, get: function() { - return AvroReadableFromStream_js_1.AvroReadableFromStream; - } }); + "node_modules/@azure/storage-blob/dist/commonjs/internal-avro/index.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var internal_avro_exports = {}; + __export2(internal_avro_exports, { + AvroReadable: () => import_AvroReadable.AvroReadable, + AvroReadableFromStream: () => import_AvroReadableFromStream.AvroReadableFromStream, + AvroReader: () => import_AvroReader.AvroReader + }); + module2.exports = __toCommonJS2(internal_avro_exports); + var import_AvroReader = require_AvroReader(); + var import_AvroReadable = require_AvroReadable(); + var import_AvroReadableFromStream = require_AvroReadableFromStream(); } }); // node_modules/@azure/storage-blob/dist/commonjs/utils/BlobQuickQueryStream.js var require_BlobQuickQueryStream = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/utils/BlobQuickQueryStream.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BlobQuickQueryStream = void 0; - var node_stream_1 = require("node:stream"); - var index_js_1 = require_internal_avro(); - var BlobQuickQueryStream = class extends node_stream_1.Readable { + "node_modules/@azure/storage-blob/dist/commonjs/utils/BlobQuickQueryStream.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BlobQuickQueryStream_exports = {}; + __export2(BlobQuickQueryStream_exports, { + BlobQuickQueryStream: () => BlobQuickQueryStream + }); + module2.exports = __toCommonJS2(BlobQuickQueryStream_exports); + var import_node_stream5 = require("node:stream"); + var import_internal_avro = require_internal_avro(); + var BlobQuickQueryStream = class extends import_node_stream5.Readable { source; avroReader; avroIter; @@ -67116,7 +97455,7 @@ var require_BlobQuickQueryStream = __commonJS({ this.source = source; this.onProgress = options.onProgress; this.onError = options.onError; - this.avroReader = new index_js_1.AvroReader(new index_js_1.AvroReadableFromStream(this.source)); + this.avroReader = new import_internal_avro.AvroReader(new import_internal_avro.AvroReadableFromStream(this.source)); this.avroIter = this.avroReader.parseObjects({ abortSignal: options.abortSignal }); } _read() { @@ -67204,18 +97543,36 @@ var require_BlobQuickQueryStream = __commonJS({ } while (!avroNext.done && !this.avroPaused); } }; - exports2.BlobQuickQueryStream = BlobQuickQueryStream; } }); // node_modules/@azure/storage-blob/dist/commonjs/BlobQueryResponse.js var require_BlobQueryResponse = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/BlobQueryResponse.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BlobQueryResponse = void 0; - var core_util_1 = require_commonjs4(); - var BlobQuickQueryStream_js_1 = require_BlobQuickQueryStream(); + "node_modules/@azure/storage-blob/dist/commonjs/BlobQueryResponse.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BlobQueryResponse_exports = {}; + __export2(BlobQueryResponse_exports, { + BlobQueryResponse: () => BlobQueryResponse + }); + module2.exports = __toCommonJS2(BlobQueryResponse_exports); + var import_core_util = require_commonjs4(); + var import_BlobQuickQueryStream = require_BlobQuickQueryStream(); var BlobQueryResponse = class { /** * Indicates that the service supports @@ -67553,7 +97910,7 @@ var require_BlobQueryResponse = __commonJS({ * @readonly */ get readableStreamBody() { - return core_util_1.isNodeLike ? this.blobDownloadStream : void 0; + return import_core_util.isNodeLike ? this.blobDownloadStream : void 0; } /** * The HTTP response. @@ -67571,44 +97928,67 @@ var require_BlobQueryResponse = __commonJS({ */ constructor(originalResponse, options = {}) { this.originalResponse = originalResponse; - this.blobDownloadStream = new BlobQuickQueryStream_js_1.BlobQuickQueryStream(this.originalResponse.readableStreamBody, options); + this.blobDownloadStream = new import_BlobQuickQueryStream.BlobQuickQueryStream( + this.originalResponse.readableStreamBody, + options + ); } }; - exports2.BlobQueryResponse = BlobQueryResponse; } }); // node_modules/@azure/storage-blob/dist/commonjs/models.js var require_models2 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/models.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StorageBlobAudience = exports2.PremiumPageBlobTier = exports2.BlockBlobTier = void 0; - exports2.toAccessTier = toAccessTier; - exports2.ensureCpkIfSpecified = ensureCpkIfSpecified; - exports2.getBlobServiceAccountAudience = getBlobServiceAccountAudience; - var constants_js_1 = require_constants10(); - var BlockBlobTier; - (function(BlockBlobTier2) { - BlockBlobTier2["Hot"] = "Hot"; - BlockBlobTier2["Cool"] = "Cool"; - BlockBlobTier2["Cold"] = "Cold"; - BlockBlobTier2["Archive"] = "Archive"; - })(BlockBlobTier || (exports2.BlockBlobTier = BlockBlobTier = {})); - var PremiumPageBlobTier; - (function(PremiumPageBlobTier2) { - PremiumPageBlobTier2["P4"] = "P4"; - PremiumPageBlobTier2["P6"] = "P6"; - PremiumPageBlobTier2["P10"] = "P10"; - PremiumPageBlobTier2["P15"] = "P15"; - PremiumPageBlobTier2["P20"] = "P20"; - PremiumPageBlobTier2["P30"] = "P30"; - PremiumPageBlobTier2["P40"] = "P40"; - PremiumPageBlobTier2["P50"] = "P50"; - PremiumPageBlobTier2["P60"] = "P60"; - PremiumPageBlobTier2["P70"] = "P70"; - PremiumPageBlobTier2["P80"] = "P80"; - })(PremiumPageBlobTier || (exports2.PremiumPageBlobTier = PremiumPageBlobTier = {})); + "node_modules/@azure/storage-blob/dist/commonjs/models.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var models_exports = {}; + __export2(models_exports, { + BlockBlobTier: () => BlockBlobTier2, + PremiumPageBlobTier: () => PremiumPageBlobTier2, + StorageBlobAudience: () => StorageBlobAudience2, + ensureCpkIfSpecified: () => ensureCpkIfSpecified, + getBlobServiceAccountAudience: () => getBlobServiceAccountAudience2, + toAccessTier: () => toAccessTier + }); + module2.exports = __toCommonJS2(models_exports); + var import_constants5 = require_constants11(); + var BlockBlobTier2 = /* @__PURE__ */ ((BlockBlobTier22) => { + BlockBlobTier22["Hot"] = "Hot"; + BlockBlobTier22["Cool"] = "Cool"; + BlockBlobTier22["Cold"] = "Cold"; + BlockBlobTier22["Archive"] = "Archive"; + return BlockBlobTier22; + })(BlockBlobTier2 || {}); + var PremiumPageBlobTier2 = /* @__PURE__ */ ((PremiumPageBlobTier22) => { + PremiumPageBlobTier22["P4"] = "P4"; + PremiumPageBlobTier22["P6"] = "P6"; + PremiumPageBlobTier22["P10"] = "P10"; + PremiumPageBlobTier22["P15"] = "P15"; + PremiumPageBlobTier22["P20"] = "P20"; + PremiumPageBlobTier22["P30"] = "P30"; + PremiumPageBlobTier22["P40"] = "P40"; + PremiumPageBlobTier22["P50"] = "P50"; + PremiumPageBlobTier22["P60"] = "P60"; + PremiumPageBlobTier22["P70"] = "P70"; + PremiumPageBlobTier22["P80"] = "P80"; + return PremiumPageBlobTier22; + })(PremiumPageBlobTier2 || {}); function toAccessTier(tier) { if (tier === void 0) { return void 0; @@ -67620,15 +98000,15 @@ var require_models2 = __commonJS({ throw new RangeError("Customer-provided encryption key must be used over HTTPS."); } if (cpk && !cpk.encryptionAlgorithm) { - cpk.encryptionAlgorithm = constants_js_1.EncryptionAlgorithmAES25; + cpk.encryptionAlgorithm = import_constants5.EncryptionAlgorithmAES25; } } - var StorageBlobAudience; - (function(StorageBlobAudience2) { - StorageBlobAudience2["StorageOAuthScopes"] = "https://storage.azure.com/.default"; - StorageBlobAudience2["DiskComputeOAuthScopes"] = "https://disk.compute.azure.com/.default"; - })(StorageBlobAudience || (exports2.StorageBlobAudience = StorageBlobAudience = {})); - function getBlobServiceAccountAudience(storageAccountName) { + var StorageBlobAudience2 = /* @__PURE__ */ ((StorageBlobAudience22) => { + StorageBlobAudience22["StorageOAuthScopes"] = "https://storage.azure.com/.default"; + StorageBlobAudience22["DiskComputeOAuthScopes"] = "https://disk.compute.azure.com/.default"; + return StorageBlobAudience22; + })(StorageBlobAudience2 || {}); + function getBlobServiceAccountAudience2(storageAccountName) { return `https://${storageAccountName}.blob.core.windows.net/.default`; } } @@ -67636,10 +98016,29 @@ var require_models2 = __commonJS({ // node_modules/@azure/storage-blob/dist/commonjs/PageBlobRangeResponse.js var require_PageBlobRangeResponse = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/PageBlobRangeResponse.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.rangeResponseFromModel = rangeResponseFromModel; + "node_modules/@azure/storage-blob/dist/commonjs/PageBlobRangeResponse.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var PageBlobRangeResponse_exports = {}; + __export2(PageBlobRangeResponse_exports, { + rangeResponseFromModel: () => rangeResponseFromModel + }); + module2.exports = __toCommonJS2(PageBlobRangeResponse_exports); function rangeResponseFromModel(response) { const pageRange = (response._response.parsedBody.pageRange || []).map((x) => ({ offset: x.start, @@ -67677,7 +98076,7 @@ var require_logger2 = __commonJS({ }); // node_modules/@azure/core-lro/dist/commonjs/poller/constants.js -var require_constants12 = __commonJS({ +var require_constants13 = __commonJS({ "node_modules/@azure/core-lro/dist/commonjs/poller/constants.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); @@ -67694,7 +98093,7 @@ var require_operation = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.pollOperation = exports2.initOperation = exports2.deserializeState = void 0; var logger_js_1 = require_logger2(); - var constants_js_1 = require_constants12(); + var constants_js_1 = require_constants13(); function deserializeState(serializedState) { try { return JSON.parse(serializedState).state; @@ -67876,7 +98275,7 @@ var require_operation2 = __commonJS({ return rawResponse.headers["azure-asyncoperation"]; } function findResourceLocation(inputs) { - var _a2; + var _a6; const { location, requestMethod, requestPath, resourceLocationConfig } = inputs; switch (requestMethod) { case "PUT": { @@ -67886,7 +98285,7 @@ var require_operation2 = __commonJS({ return void 0; } case "PATCH": { - return (_a2 = getDefault()) !== null && _a2 !== void 0 ? _a2 : requestPath; + return (_a6 = getDefault()) !== null && _a6 !== void 0 ? _a6 : requestPath; } default: { return getDefault(); @@ -67968,14 +98367,14 @@ var require_operation2 = __commonJS({ } } function getStatus(rawResponse) { - var _a2; - const { status } = (_a2 = rawResponse.body) !== null && _a2 !== void 0 ? _a2 : {}; + var _a6; + const { status } = (_a6 = rawResponse.body) !== null && _a6 !== void 0 ? _a6 : {}; return transformStatus({ status, statusCode: rawResponse.statusCode }); } function getProvisioningState(rawResponse) { - var _a2, _b; - const { properties, provisioningState } = (_a2 = rawResponse.body) !== null && _a2 !== void 0 ? _a2 : {}; - const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; + var _a6, _b2; + const { properties, provisioningState } = (_a6 = rawResponse.body) !== null && _a6 !== void 0 ? _a6 : {}; + const status = (_b2 = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b2 !== void 0 ? _b2 : provisioningState; return transformStatus({ status, statusCode: rawResponse.statusCode }); } function toOperationStatus(statusCode) { @@ -68020,8 +98419,8 @@ var require_operation2 = __commonJS({ function getStatusFromInitialResponse(inputs) { const { response, state, operationLocation } = inputs; function helper() { - var _a2; - const mode = (_a2 = state.config.metadata) === null || _a2 === void 0 ? void 0 : _a2["mode"]; + var _a6; + const mode = (_a6 = state.config.metadata) === null || _a6 === void 0 ? void 0 : _a6["mode"]; switch (mode) { case void 0: return toOperationStatus(response.rawResponse.statusCode); @@ -68056,8 +98455,8 @@ var require_operation2 = __commonJS({ } exports2.initHttpOperation = initHttpOperation; function getOperationLocation({ rawResponse }, state) { - var _a2; - const mode = (_a2 = state.config.metadata) === null || _a2 === void 0 ? void 0 : _a2["mode"]; + var _a6; + const mode = (_a6 = state.config.metadata) === null || _a6 === void 0 ? void 0 : _a6["mode"]; switch (mode) { case "OperationLocation": { return getOperationLocationPollingUrl({ @@ -68076,8 +98475,8 @@ var require_operation2 = __commonJS({ } exports2.getOperationLocation = getOperationLocation; function getOperationStatus({ rawResponse }, state) { - var _a2; - const mode = (_a2 = state.config.metadata) === null || _a2 === void 0 ? void 0 : _a2["mode"]; + var _a6; + const mode = (_a6 = state.config.metadata) === null || _a6 === void 0 ? void 0 : _a6["mode"]; switch (mode) { case "OperationLocation": { return getStatus(rawResponse); @@ -68094,8 +98493,8 @@ var require_operation2 = __commonJS({ } exports2.getOperationStatus = getOperationStatus; function accessBodyProperty({ flatResponse, rawResponse }, prop) { - var _a2, _b; - return (_a2 = flatResponse === null || flatResponse === void 0 ? void 0 : flatResponse[prop]) !== null && _a2 !== void 0 ? _a2 : (_b = rawResponse.body) === null || _b === void 0 ? void 0 : _b[prop]; + var _a6, _b2; + return (_a6 = flatResponse === null || flatResponse === void 0 ? void 0 : flatResponse[prop]) !== null && _a6 !== void 0 ? _a6 : (_b2 = rawResponse.body) === null || _b2 === void 0 ? void 0 : _b2[prop]; } function getResourceLocation(res, state) { const loc = accessBodyProperty(res, "resourceLocation"); @@ -68143,7 +98542,7 @@ var require_poller = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.buildCreatePoller = void 0; var operation_js_1 = require_operation(); - var constants_js_1 = require_constants12(); + var constants_js_1 = require_constants13(); var core_util_1 = require_commonjs4(); var createStateProxy = () => ({ /** @@ -68382,7 +98781,7 @@ var require_operation3 = __commonJS({ this.pollerConfig = pollerConfig; } async update(options) { - var _a2; + var _a6; const stateProxy = createStateProxy(); if (!this.state.isStarted) { this.state = Object.assign(Object.assign({}, this.state), await (0, operation_js_1.initHttpOperation)({ @@ -68410,7 +98809,7 @@ var require_operation3 = __commonJS({ setErrorAsResult: this.setErrorAsResult }); } - (_a2 = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a2 === void 0 ? void 0 : _a2.call(options, this.state); + (_a6 = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a6 === void 0 ? void 0 : _a6.call(options, this.state); return this; } async cancel() { @@ -68523,8 +98922,8 @@ var require_poller3 = __commonJS({ this.stopped = true; this.pollProgressCallbacks = []; this.operation = operation; - this.promise = new Promise((resolve14, reject) => { - this.resolve = resolve14; + this.promise = new Promise((resolve15, reject) => { + this.resolve = resolve15; this.reject = reject; }); this.promise.catch(() => { @@ -68760,7 +99159,7 @@ var require_lroEngine = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.LroEngine = void 0; var operation_js_1 = require_operation3(); - var constants_js_1 = require_constants12(); + var constants_js_1 = require_constants13(); var poller_js_1 = require_poller3(); var operation_js_2 = require_operation(); var LroEngine = class extends poller_js_1.Poller { @@ -68777,7 +99176,7 @@ var require_lroEngine = __commonJS({ * The method used by the poller to wait before attempting to update its operation. */ delay() { - return new Promise((resolve14) => setTimeout(() => resolve14(), this.config.intervalInMs)); + return new Promise((resolve15) => setTimeout(() => resolve15(), this.config.intervalInMs)); } }; exports2.LroEngine = LroEngine; @@ -68824,16 +99223,42 @@ var require_commonjs14 = __commonJS({ // node_modules/@azure/storage-blob/dist/commonjs/pollers/BlobStartCopyFromUrlPoller.js var require_BlobStartCopyFromUrlPoller = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/pollers/BlobStartCopyFromUrlPoller.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BlobBeginCopyFromUrlPoller = void 0; - var core_util_1 = require_commonjs4(); - var core_lro_1 = require_commonjs14(); - var BlobBeginCopyFromUrlPoller = class extends core_lro_1.Poller { + "node_modules/@azure/storage-blob/dist/commonjs/pollers/BlobStartCopyFromUrlPoller.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BlobStartCopyFromUrlPoller_exports = {}; + __export2(BlobStartCopyFromUrlPoller_exports, { + BlobBeginCopyFromUrlPoller: () => BlobBeginCopyFromUrlPoller + }); + module2.exports = __toCommonJS2(BlobStartCopyFromUrlPoller_exports); + var import_core_util = require_commonjs4(); + var import_core_lro = require_commonjs14(); + var BlobBeginCopyFromUrlPoller = class extends import_core_lro.Poller { intervalInMs; constructor(options) { - const { blobClient, copySource, intervalInMs = 15e3, onProgress, resumeFrom, startCopyFromURLOptions } = options; + const { + blobClient, + copySource, + intervalInMs = 15e3, + onProgress, + resumeFrom, + startCopyFromURLOptions + } = options; let state; if (resumeFrom) { state = JSON.parse(resumeFrom).state; @@ -68851,10 +99276,9 @@ var require_BlobStartCopyFromUrlPoller = __commonJS({ this.intervalInMs = intervalInMs; } delay() { - return (0, core_util_1.delay)(this.intervalInMs); + return (0, import_core_util.delay)(this.intervalInMs); } }; - exports2.BlobBeginCopyFromUrlPoller = BlobBeginCopyFromUrlPoller; var cancel = async function cancel2(options = {}) { const state = this.state; const { copyId } = state; @@ -68896,7 +99320,9 @@ var require_BlobStartCopyFromUrlPoller = __commonJS({ state.result = result; state.isCompleted = true; } else if (copyStatus === "failed") { - state.error = new Error(`Blob copy failed with reason: "${result.copyStatusDescription || "unknown"}"`); + state.error = new Error( + `Blob copy failed with reason: "${result.copyStatusDescription || "unknown"}"` + ); state.isCompleted = true; } } catch (err) { @@ -68906,7 +99332,7 @@ var require_BlobStartCopyFromUrlPoller = __commonJS({ } return makeBlobBeginCopyFromURLPollOperation(state); }; - var toString2 = function toString3() { + var toString2 = function toString22() { return JSON.stringify({ state: this.state }, (key, value) => { if (key === "blobClient") { return void 0; @@ -68927,16 +99353,37 @@ var require_BlobStartCopyFromUrlPoller = __commonJS({ // node_modules/@azure/storage-blob/dist/commonjs/Range.js var require_Range = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/Range.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.rangeToString = rangeToString; + "node_modules/@azure/storage-blob/dist/commonjs/Range.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var Range_exports = {}; + __export2(Range_exports, { + rangeToString: () => rangeToString + }); + module2.exports = __toCommonJS2(Range_exports); function rangeToString(iRange) { if (iRange.offset < 0) { throw new RangeError(`Range.offset cannot be smaller than 0.`); } if (iRange.count && iRange.count <= 0) { - throw new RangeError(`Range.count must be larger than 0. Leave it undefined if you want a range from offset to the end.`); + throw new RangeError( + `Range.count must be larger than 0. Leave it undefined if you want a range from offset to the end.` + ); } return iRange.count ? `bytes=${iRange.offset}-${iRange.offset + iRange.count - 1}` : `bytes=${iRange.offset}-`; } @@ -68945,16 +99392,30 @@ var require_Range = __commonJS({ // node_modules/@azure/storage-blob/dist/commonjs/utils/Batch.js var require_Batch = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/utils/Batch.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Batch = void 0; - var events_1 = require("events"); - var BatchStates; - (function(BatchStates2) { - BatchStates2[BatchStates2["Good"] = 0] = "Good"; - BatchStates2[BatchStates2["Error"] = 1] = "Error"; - })(BatchStates || (BatchStates = {})); + "node_modules/@azure/storage-blob/dist/commonjs/utils/Batch.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var Batch_exports = {}; + __export2(Batch_exports, { + Batch: () => Batch + }); + module2.exports = __toCommonJS2(Batch_exports); + var import_events2 = require("events"); var Batch = class { /** * Concurrency. Must be lager than 0. @@ -68980,7 +99441,7 @@ var require_Batch = __commonJS({ * States of Batch. When an error happens, state will turn into error. * Batch will stop execute left operations. */ - state = BatchStates.Good; + state = 0; /** * A private emitter used to pass events inside this class. */ @@ -68994,7 +99455,7 @@ var require_Batch = __commonJS({ throw new RangeError("concurrency must be larger than 0"); } this.concurrency = concurrency; - this.emitter = new events_1.EventEmitter(); + this.emitter = new import_events2.EventEmitter(); } /** * Add a operation into queue. @@ -69023,10 +99484,10 @@ var require_Batch = __commonJS({ return Promise.resolve(); } this.parallelExecute(); - return new Promise((resolve14, reject) => { - this.emitter.on("finish", resolve14); + return new Promise((resolve15, reject) => { + this.emitter.on("finish", resolve15); this.emitter.on("error", (error3) => { - this.state = BatchStates.Error; + this.state = 1; reject(error3); }); }); @@ -69047,7 +99508,7 @@ var require_Batch = __commonJS({ * */ parallelExecute() { - if (this.state === BatchStates.Error) { + if (this.state === 1) { return; } if (this.completed >= this.operations.length) { @@ -69064,52 +99525,91 @@ var require_Batch = __commonJS({ } } }; - exports2.Batch = Batch; } }); // node_modules/@azure/storage-blob/dist/commonjs/utils/utils.js -var require_utils6 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/utils/utils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.fsCreateReadStream = exports2.fsStat = void 0; - exports2.streamToBuffer = streamToBuffer; - exports2.streamToBuffer2 = streamToBuffer2; - exports2.streamToBuffer3 = streamToBuffer3; - exports2.readStreamToLocalFile = readStreamToLocalFile; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var node_fs_1 = tslib_1.__importDefault(require("node:fs")); - var node_util_1 = tslib_1.__importDefault(require("node:util")); - var constants_js_1 = require_constants10(); +var require_utils7 = __commonJS({ + "node_modules/@azure/storage-blob/dist/commonjs/utils/utils.js"(exports2, module2) { + var __create2 = Object.create; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var utils_exports = {}; + __export2(utils_exports, { + fsCreateReadStream: () => fsCreateReadStream, + fsStat: () => fsStat, + readStreamToLocalFile: () => readStreamToLocalFile, + streamToBuffer: () => streamToBuffer, + streamToBuffer2: () => streamToBuffer2, + streamToBuffer3: () => streamToBuffer3 + }); + module2.exports = __toCommonJS2(utils_exports); + var import_node_fs = __toESM2(require("node:fs")); + var import_node_util = __toESM2(require("node:util")); + var import_constants5 = require_constants11(); async function streamToBuffer(stream2, buffer, offset, end, encoding) { let pos = 0; const count = end - offset; - return new Promise((resolve14, reject) => { - const timeout = setTimeout(() => reject(new Error(`The operation cannot be completed in timeout.`)), constants_js_1.REQUEST_TIMEOUT); + return new Promise((resolve15, reject) => { + const timeout = setTimeout( + () => reject(new Error(`The operation cannot be completed in timeout.`)), + import_constants5.REQUEST_TIMEOUT + ); stream2.on("readable", () => { if (pos >= count) { clearTimeout(timeout); - resolve14(); - return; - } - let chunk = stream2.read(); - if (!chunk) { + resolve15(); return; } - if (typeof chunk === "string") { - chunk = Buffer.from(chunk, encoding); + let chunk; + while ((chunk = stream2.read()) !== null) { + if (typeof chunk === "string") { + chunk = Buffer.from(chunk, encoding); + } + const chunkLength2 = pos + chunk.length > count ? count - pos : chunk.length; + buffer.fill(chunk.slice(0, chunkLength2), offset + pos, offset + pos + chunkLength2); + pos += chunkLength2; + if (pos >= count) { + clearTimeout(timeout); + resolve15(); + return; + } } - const chunkLength = pos + chunk.length > count ? count - pos : chunk.length; - buffer.fill(chunk.slice(0, chunkLength), offset + pos, offset + pos + chunkLength); - pos += chunkLength; }); stream2.on("end", () => { clearTimeout(timeout); if (pos < count) { - reject(new Error(`Stream drains before getting enough data needed. Data read: ${pos}, data need: ${count}`)); + reject( + new Error( + `Stream drains before getting enough data needed. Data read: ${pos}, data need: ${count}` + ) + ); } - resolve14(); + resolve15(); }); stream2.on("error", (msg) => { clearTimeout(timeout); @@ -69120,87 +99620,107 @@ var require_utils6 = __commonJS({ async function streamToBuffer2(stream2, buffer, encoding) { let pos = 0; const bufferSize = buffer.length; - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { stream2.on("readable", () => { - let chunk = stream2.read(); - if (!chunk) { - return; - } - if (typeof chunk === "string") { - chunk = Buffer.from(chunk, encoding); - } - if (pos + chunk.length > bufferSize) { - reject(new Error(`Stream exceeds buffer size. Buffer size: ${bufferSize}`)); - return; + let chunk; + while ((chunk = stream2.read()) !== null) { + if (typeof chunk === "string") { + chunk = Buffer.from(chunk, encoding); + } + if (pos + chunk.length > bufferSize) { + reject(new Error(`Stream exceeds buffer size. Buffer size: ${bufferSize}`)); + return; + } + buffer.fill(chunk, pos, pos + chunk.length); + pos += chunk.length; } - buffer.fill(chunk, pos, pos + chunk.length); - pos += chunk.length; }); stream2.on("end", () => { - resolve14(pos); + resolve15(pos); }); stream2.on("error", reject); }); } async function streamToBuffer3(readableStream, encoding) { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { const chunks = []; readableStream.on("data", (data) => { chunks.push(typeof data === "string" ? Buffer.from(data, encoding) : data); }); readableStream.on("end", () => { - resolve14(Buffer.concat(chunks)); + resolve15(Buffer.concat(chunks)); }); readableStream.on("error", reject); }); } async function readStreamToLocalFile(rs, file) { - return new Promise((resolve14, reject) => { - const ws = node_fs_1.default.createWriteStream(file); + return new Promise((resolve15, reject) => { + const ws = import_node_fs.default.createWriteStream(file); rs.on("error", (err) => { reject(err); }); ws.on("error", (err) => { reject(err); }); - ws.on("close", resolve14); + ws.on("close", resolve15); rs.pipe(ws); }); } - exports2.fsStat = node_util_1.default.promisify(node_fs_1.default.stat); - exports2.fsCreateReadStream = node_fs_1.default.createReadStream; + var fsStat = import_node_util.default.promisify(import_node_fs.default.stat); + var fsCreateReadStream = import_node_fs.default.createReadStream; } }); // node_modules/@azure/storage-blob/dist/commonjs/Clients.js var require_Clients = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/Clients.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PageBlobClient = exports2.BlockBlobClient = exports2.AppendBlobClient = exports2.BlobClient = void 0; - var core_rest_pipeline_1 = require_commonjs6(); - var core_auth_1 = require_commonjs7(); - var core_util_1 = require_commonjs4(); - var core_util_2 = require_commonjs4(); - var BlobDownloadResponse_js_1 = require_BlobDownloadResponse(); - var BlobQueryResponse_js_1 = require_BlobQueryResponse(); - var AnonymousCredential_js_1 = require_AnonymousCredential(); - var StorageSharedKeyCredential_js_1 = require_StorageSharedKeyCredential(); - var models_js_1 = require_models2(); - var PageBlobRangeResponse_js_1 = require_PageBlobRangeResponse(); - var Pipeline_js_1 = require_Pipeline(); - var BlobStartCopyFromUrlPoller_js_1 = require_BlobStartCopyFromUrlPoller(); - var Range_js_1 = require_Range(); - var StorageClient_js_1 = require_StorageClient(); - var Batch_js_1 = require_Batch(); - var storage_common_1 = require_commonjs13(); - var constants_js_1 = require_constants10(); - var tracing_js_1 = require_tracing(); - var utils_common_js_1 = require_utils_common(); - var utils_js_1 = require_utils6(); - var BlobSASSignatureValues_js_1 = require_BlobSASSignatureValues(); - var BlobLeaseClient_js_1 = require_BlobLeaseClient(); - var BlobClient = class _BlobClient extends StorageClient_js_1.StorageClient { + "node_modules/@azure/storage-blob/dist/commonjs/Clients.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var Clients_exports = {}; + __export2(Clients_exports, { + AppendBlobClient: () => AppendBlobClient, + BlobClient: () => BlobClient, + BlockBlobClient: () => BlockBlobClient, + PageBlobClient: () => PageBlobClient + }); + module2.exports = __toCommonJS2(Clients_exports); + var import_core_rest_pipeline = require_commonjs6(); + var import_core_auth = require_commonjs7(); + var import_core_util = require_commonjs4(); + var import_core_util2 = require_commonjs4(); + var import_BlobDownloadResponse = require_BlobDownloadResponse(); + var import_BlobQueryResponse = require_BlobQueryResponse(); + var import_storage_common = require_commonjs12(); + var import_models = require_models2(); + var import_PageBlobRangeResponse = require_PageBlobRangeResponse(); + var import_Pipeline = require_Pipeline(); + var import_BlobStartCopyFromUrlPoller = require_BlobStartCopyFromUrlPoller(); + var import_Range = require_Range(); + var import_StorageClient = require_StorageClient(); + var import_Batch = require_Batch(); + var import_storage_common2 = require_commonjs12(); + var import_constants5 = require_constants11(); + var import_tracing = require_tracing(); + var import_utils_common = require_utils_common2(); + var import_utils5 = require_utils7(); + var import_BlobSASSignatureValues = require_BlobSASSignatureValues(); + var import_BlobLeaseClient = require_BlobLeaseClient(); + var BlobClient = class _BlobClient extends import_StorageClient.StorageClient { /** * blobContext provided by protocol layer. */ @@ -69209,6 +99729,10 @@ var require_Clients = __commonJS({ _containerName; _versionId; _snapshot; + /** + * Config used in creating blob client instances. + */ + blobClientConfig; /** * The name of the blob. */ @@ -69225,39 +99749,51 @@ var require_Clients = __commonJS({ options = options || {}; let pipeline2; let url2; - if ((0, Pipeline_js_1.isPipelineLike)(credentialOrPipelineOrContainerName)) { + if ((0, import_Pipeline.isPipelineLike)(credentialOrPipelineOrContainerName)) { url2 = urlOrConnectionString; pipeline2 = credentialOrPipelineOrContainerName; - } else if (core_util_1.isNodeLike && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential_js_1.AnonymousCredential || (0, core_auth_1.isTokenCredential)(credentialOrPipelineOrContainerName)) { + options = blobNameOrOptions; + } else if (import_core_util.isNodeLike && credentialOrPipelineOrContainerName instanceof import_storage_common.StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof import_storage_common.AnonymousCredential || (0, import_core_auth.isTokenCredential)(credentialOrPipelineOrContainerName)) { url2 = urlOrConnectionString; options = blobNameOrOptions; - pipeline2 = (0, Pipeline_js_1.newPipeline)(credentialOrPipelineOrContainerName, options); + pipeline2 = (0, import_Pipeline.newPipeline)(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { url2 = urlOrConnectionString; if (blobNameOrOptions && typeof blobNameOrOptions !== "string") { options = blobNameOrOptions; } - pipeline2 = (0, Pipeline_js_1.newPipeline)(new AnonymousCredential_js_1.AnonymousCredential(), options); + pipeline2 = (0, import_Pipeline.newPipeline)(new import_storage_common.AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { const containerName = credentialOrPipelineOrContainerName; const blobName = blobNameOrOptions; - const extractedCreds = (0, utils_common_js_1.extractConnectionStringParts)(urlOrConnectionString); + const extractedCreds = (0, import_utils_common.extractConnectionStringParts)(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { - if (core_util_1.isNodeLike) { - const sharedKeyCredential = new StorageSharedKeyCredential_js_1.StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url2 = (0, utils_common_js_1.appendToURLPath)((0, utils_common_js_1.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + if (import_core_util.isNodeLike) { + const sharedKeyCredential = new import_storage_common.StorageSharedKeyCredential( + extractedCreds.accountName, + extractedCreds.accountKey + ); + url2 = (0, import_utils_common.appendToURLPath)( + (0, import_utils_common.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), + encodeURIComponent(blobName) + ); if (!options.proxyOptions) { - options.proxyOptions = (0, core_rest_pipeline_1.getDefaultProxySettings)(extractedCreds.proxyUri); + options.proxyOptions = (0, import_core_rest_pipeline.getDefaultProxySettings)(extractedCreds.proxyUri); } - pipeline2 = (0, Pipeline_js_1.newPipeline)(sharedKeyCredential, options); + pipeline2 = (0, import_Pipeline.newPipeline)(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } else if (extractedCreds.kind === "SASConnString") { - url2 = (0, utils_common_js_1.appendToURLPath)((0, utils_common_js_1.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; - pipeline2 = (0, Pipeline_js_1.newPipeline)(new AnonymousCredential_js_1.AnonymousCredential(), options); + url2 = (0, import_utils_common.appendToURLPath)( + (0, import_utils_common.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), + encodeURIComponent(blobName) + ) + "?" + extractedCreds.accountSas; + pipeline2 = (0, import_Pipeline.newPipeline)(new import_storage_common.AnonymousCredential(), options); } else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + throw new Error( + "Connection string must be either an Account connection string or a SAS connection string" + ); } } else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); @@ -69265,8 +99801,9 @@ var require_Clients = __commonJS({ super(url2, pipeline2); ({ blobName: this._name, containerName: this._containerName } = this.getBlobAndContainerNamesFromUrl()); this.blobContext = this.storageClientContext.blob; - this._snapshot = (0, utils_common_js_1.getURLParameter)(this.url, constants_js_1.URLConstants.Parameters.SNAPSHOT); - this._versionId = (0, utils_common_js_1.getURLParameter)(this.url, constants_js_1.URLConstants.Parameters.VERSIONID); + this._snapshot = (0, import_utils_common.getURLParameter)(this.url, import_constants5.URLConstants.Parameters.SNAPSHOT); + this._versionId = (0, import_utils_common.getURLParameter)(this.url, import_constants5.URLConstants.Parameters.VERSIONID); + this.blobClientConfig = options; } /** * Creates a new BlobClient object identical to the source but with the specified snapshot timestamp. @@ -69276,7 +99813,15 @@ var require_Clients = __commonJS({ * @returns A new BlobClient object identical to the source but with the specified snapshot timestamp */ withSnapshot(snapshot) { - return new _BlobClient((0, utils_common_js_1.setURLParameter)(this.url, constants_js_1.URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? void 0 : snapshot), this.pipeline); + return new _BlobClient( + (0, import_utils_common.setURLParameter)( + this.url, + import_constants5.URLConstants.Parameters.SNAPSHOT, + snapshot.length === 0 ? void 0 : snapshot + ), + this.pipeline, + this.blobClientConfig + ); } /** * Creates a new BlobClient object pointing to a version of this blob. @@ -69286,28 +99831,36 @@ var require_Clients = __commonJS({ * @returns A new BlobClient object pointing to the version of this blob. */ withVersion(versionId) { - return new _BlobClient((0, utils_common_js_1.setURLParameter)(this.url, constants_js_1.URLConstants.Parameters.VERSIONID, versionId.length === 0 ? void 0 : versionId), this.pipeline); + return new _BlobClient( + (0, import_utils_common.setURLParameter)( + this.url, + import_constants5.URLConstants.Parameters.VERSIONID, + versionId.length === 0 ? void 0 : versionId + ), + this.pipeline, + this.blobClientConfig + ); } /** * Creates a AppendBlobClient object. * */ getAppendBlobClient() { - return new AppendBlobClient(this.url, this.pipeline); + return new AppendBlobClient(this.url, this.pipeline, this.blobClientConfig); } /** * Creates a BlockBlobClient object. * */ getBlockBlobClient() { - return new BlockBlobClient(this.url, this.pipeline); + return new BlockBlobClient(this.url, this.pipeline, this.blobClientConfig); } /** * Creates a PageBlobClient object. * */ getPageBlobClient() { - return new PageBlobClient(this.url, this.pipeline); + return new PageBlobClient(this.url, this.pipeline, this.blobClientConfig); } /** * Reads or downloads a blob from the system, including its metadata and properties. @@ -69328,6 +99881,7 @@ var require_Clients = __commonJS({ * ```ts snippet:ReadmeSampleDownloadBlob_Node * import { BlobServiceClient } from "@azure/storage-blob"; * import { DefaultAzureCredential } from "@azure/identity"; + * import { buffer } from "node:stream/consumers"; * * const account = ""; * const blobServiceClient = new BlobServiceClient( @@ -69344,22 +99898,10 @@ var require_Clients = __commonJS({ * // In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody * const downloadBlockBlobResponse = await blobClient.download(); * if (downloadBlockBlobResponse.readableStreamBody) { - * const downloaded = await streamToString(downloadBlockBlobResponse.readableStreamBody); - * console.log(`Downloaded blob content: ${downloaded}`); - * } - * - * async function streamToString(stream: NodeJS.ReadableStream): Promise { - * const result = await new Promise>((resolve, reject) => { - * const chunks: Buffer[] = []; - * stream.on("data", (data) => { - * chunks.push(Buffer.isBuffer(data) ? data : Buffer.from(data)); - * }); - * stream.on("end", () => { - * resolve(Buffer.concat(chunks)); - * }); - * stream.on("error", reject); - * }); - * return result.toString(); + * // Download the raw bytes of the blob. Use `text` from "node:stream/consumers" + * // instead if you want to read the content as a string directly. + * const downloaded = await buffer(downloadBlockBlobResponse.readableStreamBody); + * console.log(`Downloaded blob content: ${downloaded.toString()}`); * } * ``` * @@ -69393,72 +99935,103 @@ var require_Clients = __commonJS({ async download(offset = 0, count, options = {}) { options.conditions = options.conditions || {}; options.conditions = options.conditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("BlobClient-download", options, async (updatedOptions) => { - const res = (0, utils_common_js_1.assertResponse)(await this.blobContext.download({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - requestOptions: { - onDownloadProgress: core_util_1.isNodeLike ? void 0 : options.onProgress - // for Node.js, progress is reported by RetriableReadableStream - }, - range: offset === 0 && !count ? void 0 : (0, Range_js_1.rangeToString)({ offset, count }), - rangeGetContentMD5: options.rangeGetContentMD5, - rangeGetContentCRC64: options.rangeGetContentCrc64, - snapshot: options.snapshot, - cpkInfo: options.customerProvidedKey, - tracingOptions: updatedOptions.tracingOptions - })); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan("BlobClient-download", options, async (updatedOptions) => { + let contentChecksumAlgorithm = options.contentChecksumAlgorithm ?? this.blobClientConfig?.downloadContentChecksumAlgorithm; + if (contentChecksumAlgorithm === void 0) { + contentChecksumAlgorithm = "Customized"; + } else if (contentChecksumAlgorithm === "Auto") { + contentChecksumAlgorithm = "StorageCrc64"; + } + if (contentChecksumAlgorithm === "StorageCrc64") { + await import_storage_common2.StorageCRC64Calculator.init(); + } + const res = (0, import_utils_common.assertResponse)( + await this.blobContext.download({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + requestOptions: { + onDownloadProgress: import_core_util.isNodeLike ? void 0 : options.onProgress + // for Node.js, progress is reported by RetriableReadableStream + }, + range: offset === 0 && !count ? void 0 : (0, import_Range.rangeToString)({ offset, count }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey, + tracingOptions: updatedOptions.tracingOptions, + structuredBodyType: contentChecksumAlgorithm === "StorageCrc64" ? "XSM/1.0; properties=crc64" : void 0 + }) + ); const wrappedRes = { ...res, _response: res._response, // _response is made non-enumerable objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, - objectReplicationSourceProperties: (0, utils_common_js_1.parseObjectReplicationRecord)(res.objectReplicationRules) + objectReplicationSourceProperties: (0, import_utils_common.parseObjectReplicationRecord)(res.objectReplicationRules) }; - if (!core_util_1.isNodeLike) { + if (!import_core_util.isNodeLike) { + if (contentChecksumAlgorithm === "StorageCrc64") { + wrappedRes.blobBody = (0, import_storage_common2.structuredMessageDecodingBrowser)(await wrappedRes.blobBody); + } return wrappedRes; } if (options.maxRetryRequests === void 0 || options.maxRetryRequests < 0) { - options.maxRetryRequests = constants_js_1.DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; + options.maxRetryRequests = import_constants5.DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; } if (res.contentLength === void 0) { throw new RangeError(`File download response doesn't contain valid content length header`); } + if (contentChecksumAlgorithm === "StorageCrc64" && res.structuredContentLength === void 0) { + throw new RangeError(`Unexpected structured content length`); + } if (!res.etag) { throw new RangeError(`File download response doesn't contain valid etag header`); } - return new BlobDownloadResponse_js_1.BlobDownloadResponse(wrappedRes, async (start) => { - const updatedDownloadOptions = { - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ifMatch: options.conditions.ifMatch || res.etag, - ifModifiedSince: options.conditions.ifModifiedSince, - ifNoneMatch: options.conditions.ifNoneMatch, - ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, - ifTags: options.conditions?.tagConditions - }, - range: (0, Range_js_1.rangeToString)({ - count: offset + res.contentLength - start, - offset: start - }), - rangeGetContentMD5: options.rangeGetContentMD5, - rangeGetContentCRC64: options.rangeGetContentCrc64, - snapshot: options.snapshot, - cpkInfo: options.customerProvidedKey - }; - return (await this.blobContext.download({ - abortSignal: options.abortSignal, - ...updatedDownloadOptions - })).readableStreamBody; - }, offset, res.contentLength, { - maxRetryRequests: options.maxRetryRequests, - onProgress: options.onProgress - }); + const expectedContentLength = contentChecksumAlgorithm === "StorageCrc64" ? res.structuredContentLength : res.contentLength; + return new import_BlobDownloadResponse.BlobDownloadResponse( + wrappedRes, + async (start) => { + const updatedDownloadOptions = { + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ifMatch: options.conditions.ifMatch || res.etag, + ifModifiedSince: options.conditions.ifModifiedSince, + ifNoneMatch: options.conditions.ifNoneMatch, + ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, + ifTags: options.conditions?.tagConditions + }, + range: (0, import_Range.rangeToString)({ + count: offset + expectedContentLength - start, + offset: start + }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey, + structuredBodyType: contentChecksumAlgorithm === "StorageCrc64" ? "XSM/1.0; properties=crc64" : void 0 + }; + const resBody = (await this.blobContext.download({ + abortSignal: options.abortSignal, + ...updatedDownloadOptions + })).readableStreamBody; + if (contentChecksumAlgorithm === "StorageCrc64") { + return (0, import_storage_common.structuredMessageDecodingStream)(resBody, {}); + } else { + return resBody; + } + }, + offset, + expectedContentLength, + { + maxRetryRequests: options.maxRetryRequests, + onProgress: options.onProgress + } + ); }); } /** @@ -69471,9 +100044,9 @@ var require_Clients = __commonJS({ * @param options - options to Exists operation. */ async exists(options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobClient-exists", options, async (updatedOptions) => { + return import_tracing.tracingClient.withSpan("BlobClient-exists", options, async (updatedOptions) => { try { - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); await this.getProperties({ abortSignal: options.abortSignal, customerProvidedKey: options.customerProvidedKey, @@ -69484,7 +100057,7 @@ var require_Clients = __commonJS({ } catch (e) { if (e.statusCode === 404) { return false; - } else if (e.statusCode === 409 && (e.details.errorCode === constants_js_1.BlobUsesCustomerSpecifiedEncryptionMsg || e.details.errorCode === constants_js_1.BlobDoesNotUseCustomerSpecifiedEncryption)) { + } else if (e.statusCode === 409 && (e.details.errorCode === import_constants5.BlobUsesCustomerSpecifiedEncryptionMsg || e.details.errorCode === import_constants5.BlobDoesNotUseCustomerSpecifiedEncryption)) { return true; } throw e; @@ -69505,24 +100078,26 @@ var require_Clients = __commonJS({ */ async getProperties(options = {}) { options.conditions = options.conditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("BlobClient-getProperties", options, async (updatedOptions) => { - const res = (0, utils_common_js_1.assertResponse)(await this.blobContext.getProperties({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - cpkInfo: options.customerProvidedKey, - tracingOptions: updatedOptions.tracingOptions - })); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan("BlobClient-getProperties", options, async (updatedOptions) => { + const res = (0, import_utils_common.assertResponse)( + await this.blobContext.getProperties({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + cpkInfo: options.customerProvidedKey, + tracingOptions: updatedOptions.tracingOptions + }) + ); return { ...res, _response: res._response, // _response is made non-enumerable objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, - objectReplicationSourceProperties: (0, utils_common_js_1.parseObjectReplicationRecord)(res.objectReplicationRules) + objectReplicationSourceProperties: (0, import_utils_common.parseObjectReplicationRecord)(res.objectReplicationRules) }; }); } @@ -69537,17 +100112,21 @@ var require_Clients = __commonJS({ */ async delete(options = {}) { options.conditions = options.conditions || {}; - return tracing_js_1.tracingClient.withSpan("BlobClient-delete", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blobContext.delete({ - abortSignal: options.abortSignal, - deleteSnapshots: options.deleteSnapshots, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - tracingOptions: updatedOptions.tracingOptions - })); + return import_tracing.tracingClient.withSpan("BlobClient-delete", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blobContext.delete({ + abortSignal: options.abortSignal, + deleteSnapshots: options.deleteSnapshots, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + tracingOptions: updatedOptions.tracingOptions, + accessTierIfModifiedSince: options.conditions?.accessTierIfModifiedSince, + accessTierIfUnmodifiedSince: options.conditions?.accessTierIfUnmodifiedSince + }) + ); }); } /** @@ -69560,9 +100139,9 @@ var require_Clients = __commonJS({ * @param options - Optional options to Blob Delete operation. */ async deleteIfExists(options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobClient-deleteIfExists", options, async (updatedOptions) => { + return import_tracing.tracingClient.withSpan("BlobClient-deleteIfExists", options, async (updatedOptions) => { try { - const res = (0, utils_common_js_1.assertResponse)(await this.delete(updatedOptions)); + const res = (0, import_utils_common.assertResponse)(await this.delete(updatedOptions)); return { succeeded: true, ...res, @@ -69590,11 +100169,13 @@ var require_Clients = __commonJS({ * @param options - Optional options to Blob Undelete operation. */ async undelete(options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobClient-undelete", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blobContext.undelete({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); + return import_tracing.tracingClient.withSpan("BlobClient-undelete", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blobContext.undelete({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } /** @@ -69614,19 +100195,21 @@ var require_Clients = __commonJS({ */ async setHTTPHeaders(blobHTTPHeaders, options = {}) { options.conditions = options.conditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("BlobClient-setHTTPHeaders", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blobContext.setHttpHeaders({ - abortSignal: options.abortSignal, - blobHttpHeaders: blobHTTPHeaders, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - // cpkInfo: options.customerProvidedKey, // CPK is not included in Swagger, should change this back when this issue is fixed in Swagger. - tracingOptions: updatedOptions.tracingOptions - })); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan("BlobClient-setHTTPHeaders", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blobContext.setHttpHeaders({ + abortSignal: options.abortSignal, + blobHttpHeaders: blobHTTPHeaders, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + // cpkInfo: options.customerProvidedKey, // CPK is not included in Swagger, should change this back when this issue is fixed in Swagger. + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } /** @@ -69642,20 +100225,22 @@ var require_Clients = __commonJS({ */ async setMetadata(metadata, options = {}) { options.conditions = options.conditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("BlobClient-setMetadata", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blobContext.setMetadata({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - tracingOptions: updatedOptions.tracingOptions - })); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan("BlobClient-setMetadata", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blobContext.setMetadata({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } /** @@ -69668,17 +100253,20 @@ var require_Clients = __commonJS({ * @param options - */ async setTags(tags, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobClient-setTags", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blobContext.setTags({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - tracingOptions: updatedOptions.tracingOptions, - tags: (0, utils_common_js_1.toBlobTags)(tags) - })); + return import_tracing.tracingClient.withSpan("BlobClient-setTags", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blobContext.setTags({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + blobModifiedAccessConditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions, + tags: (0, import_utils_common.toBlobTags)(tags) + }) + ); }); } /** @@ -69687,21 +100275,24 @@ var require_Clients = __commonJS({ * @param options - */ async getTags(options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobClient-getTags", options, async (updatedOptions) => { - const response = (0, utils_common_js_1.assertResponse)(await this.blobContext.getTags({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - tracingOptions: updatedOptions.tracingOptions - })); + return import_tracing.tracingClient.withSpan("BlobClient-getTags", options, async (updatedOptions) => { + const response = (0, import_utils_common.assertResponse)( + await this.blobContext.getTags({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + blobModifiedAccessConditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions + }) + ); const wrappedResponse = { ...response, _response: response._response, // _response is made non-enumerable - tags: (0, utils_common_js_1.toTags)({ blobTagSet: response.blobTagSet }) || {} + tags: (0, import_utils_common.toTags)({ blobTagSet: response.blobTagSet }) || {} }; return wrappedResponse; }); @@ -69713,7 +100304,7 @@ var require_Clients = __commonJS({ * @returns A new BlobLeaseClient object for managing leases on the blob. */ getBlobLeaseClient(proposeLeaseId) { - return new BlobLeaseClient_js_1.BlobLeaseClient(this, proposeLeaseId); + return new import_BlobLeaseClient.BlobLeaseClient(this, proposeLeaseId); } /** * Creates a read-only snapshot of a blob. @@ -69723,20 +100314,22 @@ var require_Clients = __commonJS({ */ async createSnapshot(options = {}) { options.conditions = options.conditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("BlobClient-createSnapshot", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blobContext.createSnapshot({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata: options.metadata, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - tracingOptions: updatedOptions.tracingOptions - })); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan("BlobClient-createSnapshot", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blobContext.createSnapshot({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } /** @@ -69818,7 +100411,7 @@ var require_Clients = __commonJS({ getProperties: (...args) => this.getProperties(...args), startCopyFromURL: (...args) => this.startCopyFromURL(...args) }; - const poller = new BlobStartCopyFromUrlPoller_js_1.BlobBeginCopyFromUrlPoller({ + const poller = new import_BlobStartCopyFromUrlPoller.BlobBeginCopyFromUrlPoller({ blobClient: client, copySource, intervalInMs: options.intervalInMs, @@ -69838,13 +100431,19 @@ var require_Clients = __commonJS({ * @param options - Optional options to the Blob Abort Copy From URL operation. */ async abortCopyFromURL(copyId, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobClient-abortCopyFromURL", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blobContext.abortCopyFromURL(copyId, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "BlobClient-abortCopyFromURL", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blobContext.abortCopyFromURL(copyId, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * The synchronous Copy From URL operation copies a blob or an internet resource to a new blob. It will not @@ -69857,33 +100456,35 @@ var require_Clients = __commonJS({ async syncCopyFromURL(copySource, options = {}) { options.conditions = options.conditions || {}; options.sourceConditions = options.sourceConditions || {}; - return tracing_js_1.tracingClient.withSpan("BlobClient-syncCopyFromURL", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blobContext.copyFromURL(copySource, { - abortSignal: options.abortSignal, - metadata: options.metadata, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions?.ifMatch, - sourceIfModifiedSince: options.sourceConditions?.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions?.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions?.ifUnmodifiedSince - }, - sourceContentMD5: options.sourceContentMD5, - copySourceAuthorization: (0, utils_common_js_1.httpAuthorizationToString)(options.sourceAuthorization), - tier: (0, models_js_1.toAccessTier)(options.tier), - blobTagsString: (0, utils_common_js_1.toBlobTagsString)(options.tags), - immutabilityPolicyExpiry: options.immutabilityPolicy?.expiriesOn, - immutabilityPolicyMode: options.immutabilityPolicy?.policyMode, - legalHold: options.legalHold, - encryptionScope: options.encryptionScope, - copySourceTags: options.copySourceTags, - fileRequestIntent: options.sourceShareTokenIntent, - tracingOptions: updatedOptions.tracingOptions - })); + return import_tracing.tracingClient.withSpan("BlobClient-syncCopyFromURL", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blobContext.copyFromURL(copySource, { + abortSignal: options.abortSignal, + metadata: options.metadata, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions?.ifMatch, + sourceIfModifiedSince: options.sourceConditions?.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions?.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions?.ifUnmodifiedSince + }, + sourceContentMD5: options.sourceContentMD5, + copySourceAuthorization: (0, import_utils_common.httpAuthorizationToString)(options.sourceAuthorization), + tier: (0, import_models.toAccessTier)(options.tier), + blobTagsString: (0, import_utils_common.toBlobTagsString)(options.tags), + immutabilityPolicyExpiry: options.immutabilityPolicy?.expiriesOn, + immutabilityPolicyMode: options.immutabilityPolicy?.policyMode, + legalHold: options.legalHold, + encryptionScope: options.encryptionScope, + copySourceTags: options.copySourceTags, + fileRequestIntent: options.sourceShareTokenIntent, + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } /** @@ -69898,17 +100499,19 @@ var require_Clients = __commonJS({ * @param options - Optional options to the Blob Set Tier operation. */ async setAccessTier(tier, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobClient-setAccessTier", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blobContext.setTier((0, models_js_1.toAccessTier)(tier), { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - rehydratePriority: options.rehydratePriority, - tracingOptions: updatedOptions.tracingOptions - })); + return import_tracing.tracingClient.withSpan("BlobClient-setAccessTier", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blobContext.setTier((0, import_models.toAccessTier)(tier), { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + rehydratePriority: options.rehydratePriority, + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } async downloadToBuffer(param1, param2, param3, param4 = {}) { @@ -69930,7 +100533,7 @@ var require_Clients = __commonJS({ throw new RangeError("blockSize option must be >= 0"); } if (blockSize === 0) { - blockSize = constants_js_1.DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; + blockSize = import_constants5.DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; } if (offset < 0) { throw new RangeError("offset option must be >= 0"); @@ -69941,53 +100544,64 @@ var require_Clients = __commonJS({ if (!options.conditions) { options.conditions = {}; } - return tracing_js_1.tracingClient.withSpan("BlobClient-downloadToBuffer", options, async (updatedOptions) => { - if (!count) { - const response = await this.getProperties({ - ...options, - tracingOptions: updatedOptions.tracingOptions - }); - count = response.contentLength - offset; - if (count < 0) { - throw new RangeError(`offset ${offset} shouldn't be larger than blob size ${response.contentLength}`); - } - } - if (!buffer) { - try { - buffer = Buffer.alloc(count); - } catch (error3) { - throw new Error(`Unable to allocate the buffer of size: ${count}(in bytes). Please try passing your own buffer to the "downloadToBuffer" method or try using other methods like "download" or "downloadToFile". ${error3.message}`); - } - } - if (buffer.length < count) { - throw new RangeError(`The buffer's size should be equal to or larger than the request count of bytes: ${count}`); - } - let transferProgress = 0; - const batch = new Batch_js_1.Batch(options.concurrency); - for (let off = offset; off < offset + count; off = off + blockSize) { - batch.addOperation(async () => { - let chunkEnd = offset + count; - if (off + blockSize < chunkEnd) { - chunkEnd = off + blockSize; - } - const response = await this.download(off, chunkEnd - off, { - abortSignal: options.abortSignal, - conditions: options.conditions, - maxRetryRequests: options.maxRetryRequestsPerBlock, - customerProvidedKey: options.customerProvidedKey, + return import_tracing.tracingClient.withSpan( + "BlobClient-downloadToBuffer", + options, + async (updatedOptions) => { + if (!count) { + const response = await this.getProperties({ + ...options, tracingOptions: updatedOptions.tracingOptions }); - const stream2 = response.readableStreamBody; - await (0, utils_js_1.streamToBuffer)(stream2, buffer, off - offset, chunkEnd - offset); - transferProgress += chunkEnd - off; - if (options.onProgress) { - options.onProgress({ loadedBytes: transferProgress }); + count = response.contentLength - offset; + if (count < 0) { + throw new RangeError( + `offset ${offset} shouldn't be larger than blob size ${response.contentLength}` + ); } - }); + } + if (!buffer) { + try { + buffer = Buffer.alloc(count); + } catch (error3) { + throw new Error( + `Unable to allocate the buffer of size: ${count}(in bytes). Please try passing your own buffer to the "downloadToBuffer" method or try using other methods like "download" or "downloadToFile". ${error3.message}` + ); + } + } + if (buffer.length < count) { + throw new RangeError( + `The buffer's size should be equal to or larger than the request count of bytes: ${count}` + ); + } + let transferProgress = 0; + const batch = new import_Batch.Batch(options.concurrency); + for (let off = offset; off < offset + count; off = off + blockSize) { + batch.addOperation(async () => { + let chunkEnd = offset + count; + if (off + blockSize < chunkEnd) { + chunkEnd = off + blockSize; + } + const response = await this.download(off, chunkEnd - off, { + abortSignal: options.abortSignal, + conditions: options.conditions, + maxRetryRequests: options.maxRetryRequestsPerBlock, + customerProvidedKey: options.customerProvidedKey, + contentChecksumAlgorithm: options.contentChecksumAlgorithm, + tracingOptions: updatedOptions.tracingOptions + }); + const stream2 = response.readableStreamBody; + await (0, import_utils5.streamToBuffer)(stream2, buffer, off - offset, chunkEnd - offset); + transferProgress += chunkEnd - off; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress }); + } + }); + } + await batch.do(); + return buffer; } - await batch.do(); - return buffer; - }); + ); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. @@ -70006,13 +100620,13 @@ var require_Clients = __commonJS({ * at the specified path. */ async downloadToFile(filePath, offset = 0, count, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobClient-downloadToFile", options, async (updatedOptions) => { + return import_tracing.tracingClient.withSpan("BlobClient-downloadToFile", options, async (updatedOptions) => { const response = await this.download(offset, count, { ...options, tracingOptions: updatedOptions.tracingOptions }); if (response.readableStreamBody) { - await (0, utils_js_1.readStreamToLocalFile)(response.readableStreamBody, filePath); + await (0, import_utils5.readStreamToLocalFile)(response.readableStreamBody, filePath); } response.blobDownloadStream = void 0; return response; @@ -70027,7 +100641,7 @@ var require_Clients = __commonJS({ const pathComponents = parsedUrl.pathname.match("/([^/]*)(/(.*))?"); containerName = pathComponents[1]; blobName = pathComponents[3]; - } else if ((0, utils_common_js_1.isIpEndpointStyle)(parsedUrl)) { + } else if ((0, import_utils_common.isIpEndpointStyle)(parsedUrl)) { const pathComponents = parsedUrl.pathname.match("/([^/]*)/([^/]*)(/(.*))?"); containerName = pathComponents[2]; blobName = pathComponents[4]; @@ -70061,34 +100675,40 @@ var require_Clients = __commonJS({ * @param options - Optional options to the Blob Start Copy From URL operation. */ async startCopyFromURL(copySource, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobClient-startCopyFromURL", options, async (updatedOptions) => { - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - return (0, utils_common_js_1.assertResponse)(await this.blobContext.startCopyFromURL(copySource, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata: options.metadata, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, - sourceIfTags: options.sourceConditions.tagConditions - }, - immutabilityPolicyExpiry: options.immutabilityPolicy?.expiriesOn, - immutabilityPolicyMode: options.immutabilityPolicy?.policyMode, - legalHold: options.legalHold, - rehydratePriority: options.rehydratePriority, - tier: (0, models_js_1.toAccessTier)(options.tier), - blobTagsString: (0, utils_common_js_1.toBlobTagsString)(options.tags), - sealBlob: options.sealBlob, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "BlobClient-startCopyFromURL", + options, + async (updatedOptions) => { + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + return (0, import_utils_common.assertResponse)( + await this.blobContext.startCopyFromURL(copySource, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, + sourceIfTags: options.sourceConditions.tagConditions + }, + immutabilityPolicyExpiry: options.immutabilityPolicy?.expiriesOn, + immutabilityPolicyMode: options.immutabilityPolicy?.policyMode, + legalHold: options.legalHold, + rehydratePriority: options.rehydratePriority, + tier: (0, import_models.toAccessTier)(options.tier), + blobTagsString: (0, import_utils_common.toBlobTagsString)(options.tags), + sealBlob: options.sealBlob, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * Only available for BlobClient constructed with a shared key credential. @@ -70102,18 +100722,23 @@ var require_Clients = __commonJS({ * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateSasUrl(options) { - return new Promise((resolve14) => { - if (!(this.credential instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential)) { - throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + return new Promise((resolve15) => { + if (!(this.credential instanceof import_storage_common.StorageSharedKeyCredential)) { + throw new RangeError( + "Can only generate the SAS when the client is initialized with a shared key credential" + ); } - const sas = (0, BlobSASSignatureValues_js_1.generateBlobSASQueryParameters)({ - containerName: this._containerName, - blobName: this._name, - snapshotTime: this._snapshot, - versionId: this._versionId, - ...options - }, this.credential).toString(); - resolve14((0, utils_common_js_1.appendToURLQuery)(this.url, sas)); + const sas = (0, import_BlobSASSignatureValues.generateBlobSASQueryParameters)( + { + containerName: this._containerName, + blobName: this._name, + snapshotTime: this._snapshot, + versionId: this._versionId, + ...options + }, + this.credential + ).toString(); + resolve15((0, import_utils_common.appendToURLQuery)(this.url, sas)); }); } /** @@ -70129,16 +100754,21 @@ var require_Clients = __commonJS({ */ /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ generateSasStringToSign(options) { - if (!(this.credential instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential)) { - throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); - } - return (0, BlobSASSignatureValues_js_1.generateBlobSASQueryParametersInternal)({ - containerName: this._containerName, - blobName: this._name, - snapshotTime: this._snapshot, - versionId: this._versionId, - ...options - }, this.credential).stringToSign; + if (!(this.credential instanceof import_storage_common.StorageSharedKeyCredential)) { + throw new RangeError( + "Can only generate the SAS when the client is initialized with a shared key credential" + ); + } + return (0, import_BlobSASSignatureValues.generateBlobSASQueryParametersInternal)( + { + containerName: this._containerName, + blobName: this._name, + snapshotTime: this._snapshot, + versionId: this._versionId, + ...options + }, + this.credential + ).stringToSign; } /** * @@ -70152,15 +100782,19 @@ var require_Clients = __commonJS({ * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateUserDelegationSasUrl(options, userDelegationKey) { - return new Promise((resolve14) => { - const sas = (0, BlobSASSignatureValues_js_1.generateBlobSASQueryParameters)({ - containerName: this._containerName, - blobName: this._name, - snapshotTime: this._snapshot, - versionId: this._versionId, - ...options - }, userDelegationKey, this.accountName).toString(); - resolve14((0, utils_common_js_1.appendToURLQuery)(this.url, sas)); + return new Promise((resolve15) => { + const sas = (0, import_BlobSASSignatureValues.generateBlobSASQueryParameters)( + { + containerName: this._containerName, + blobName: this._name, + snapshotTime: this._snapshot, + versionId: this._versionId, + ...options + }, + userDelegationKey, + this.accountName + ).toString(); + resolve15((0, import_utils_common.appendToURLQuery)(this.url, sas)); }); } /** @@ -70176,13 +100810,17 @@ var require_Clients = __commonJS({ * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateUserDelegationSasStringToSign(options, userDelegationKey) { - return (0, BlobSASSignatureValues_js_1.generateBlobSASQueryParametersInternal)({ - containerName: this._containerName, - blobName: this._name, - snapshotTime: this._snapshot, - versionId: this._versionId, - ...options - }, userDelegationKey, this.accountName).stringToSign; + return (0, import_BlobSASSignatureValues.generateBlobSASQueryParametersInternal)( + { + containerName: this._containerName, + blobName: this._name, + snapshotTime: this._snapshot, + versionId: this._versionId, + ...options + }, + userDelegationKey, + this.accountName + ).stringToSign; } /** * Delete the immutablility policy on the blob. @@ -70190,11 +100828,17 @@ var require_Clients = __commonJS({ * @param options - Optional options to delete immutability policy on the blob. */ async deleteImmutabilityPolicy(options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobClient-deleteImmutabilityPolicy", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blobContext.deleteImmutabilityPolicy({ - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "BlobClient-deleteImmutabilityPolicy", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blobContext.deleteImmutabilityPolicy({ + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * Set immutability policy on the blob. @@ -70202,13 +100846,19 @@ var require_Clients = __commonJS({ * @param options - Optional options to set immutability policy on the blob. */ async setImmutabilityPolicy(immutabilityPolicy, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobClient-setImmutabilityPolicy", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blobContext.setImmutabilityPolicy({ - immutabilityPolicyExpiry: immutabilityPolicy.expiriesOn, - immutabilityPolicyMode: immutabilityPolicy.policyMode, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "BlobClient-setImmutabilityPolicy", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blobContext.setImmutabilityPolicy({ + immutabilityPolicyExpiry: immutabilityPolicy.expiriesOn, + immutabilityPolicyMode: immutabilityPolicy.policyMode, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * Set legal hold on the blob. @@ -70216,10 +100866,12 @@ var require_Clients = __commonJS({ * @param options - Optional options to set legal hold on the blob. */ async setLegalHold(legalHoldEnabled, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobClient-setLegalHold", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blobContext.setLegalHold(legalHoldEnabled, { - tracingOptions: updatedOptions.tracingOptions - })); + return import_tracing.tracingClient.withSpan("BlobClient-setLegalHold", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blobContext.setLegalHold(legalHoldEnabled, { + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } /** @@ -70233,15 +100885,16 @@ var require_Clients = __commonJS({ * @returns Response data for the Service Get Account Info operation. */ async getAccountInfo(options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobClient-getAccountInfo", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blobContext.getAccountInfo({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); + return import_tracing.tracingClient.withSpan("BlobClient-getAccountInfo", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blobContext.getAccountInfo({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } }; - exports2.BlobClient = BlobClient; var AppendBlobClient = class _AppendBlobClient extends BlobClient { /** * appendBlobsContext provided by protocol layer. @@ -70251,42 +100904,56 @@ var require_Clients = __commonJS({ let pipeline2; let url2; options = options || {}; - if ((0, Pipeline_js_1.isPipelineLike)(credentialOrPipelineOrContainerName)) { + if ((0, import_Pipeline.isPipelineLike)(credentialOrPipelineOrContainerName)) { url2 = urlOrConnectionString; pipeline2 = credentialOrPipelineOrContainerName; - } else if (core_util_1.isNodeLike && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential_js_1.AnonymousCredential || (0, core_auth_1.isTokenCredential)(credentialOrPipelineOrContainerName)) { + options = blobNameOrOptions; + } else if (import_core_util.isNodeLike && credentialOrPipelineOrContainerName instanceof import_storage_common.StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof import_storage_common.AnonymousCredential || (0, import_core_auth.isTokenCredential)(credentialOrPipelineOrContainerName)) { url2 = urlOrConnectionString; options = blobNameOrOptions; - pipeline2 = (0, Pipeline_js_1.newPipeline)(credentialOrPipelineOrContainerName, options); + pipeline2 = (0, import_Pipeline.newPipeline)(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { url2 = urlOrConnectionString; - pipeline2 = (0, Pipeline_js_1.newPipeline)(new AnonymousCredential_js_1.AnonymousCredential(), options); + options = blobNameOrOptions; + pipeline2 = (0, import_Pipeline.newPipeline)(new import_storage_common.AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { const containerName = credentialOrPipelineOrContainerName; const blobName = blobNameOrOptions; - const extractedCreds = (0, utils_common_js_1.extractConnectionStringParts)(urlOrConnectionString); + const extractedCreds = (0, import_utils_common.extractConnectionStringParts)(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { - if (core_util_1.isNodeLike) { - const sharedKeyCredential = new StorageSharedKeyCredential_js_1.StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url2 = (0, utils_common_js_1.appendToURLPath)((0, utils_common_js_1.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + if (import_core_util.isNodeLike) { + const sharedKeyCredential = new import_storage_common.StorageSharedKeyCredential( + extractedCreds.accountName, + extractedCreds.accountKey + ); + url2 = (0, import_utils_common.appendToURLPath)( + (0, import_utils_common.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), + encodeURIComponent(blobName) + ); if (!options.proxyOptions) { - options.proxyOptions = (0, core_rest_pipeline_1.getDefaultProxySettings)(extractedCreds.proxyUri); + options.proxyOptions = (0, import_core_rest_pipeline.getDefaultProxySettings)(extractedCreds.proxyUri); } - pipeline2 = (0, Pipeline_js_1.newPipeline)(sharedKeyCredential, options); + pipeline2 = (0, import_Pipeline.newPipeline)(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } else if (extractedCreds.kind === "SASConnString") { - url2 = (0, utils_common_js_1.appendToURLPath)((0, utils_common_js_1.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; - pipeline2 = (0, Pipeline_js_1.newPipeline)(new AnonymousCredential_js_1.AnonymousCredential(), options); + url2 = (0, import_utils_common.appendToURLPath)( + (0, import_utils_common.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), + encodeURIComponent(blobName) + ) + "?" + extractedCreds.accountSas; + pipeline2 = (0, import_Pipeline.newPipeline)(new import_storage_common.AnonymousCredential(), options); } else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + throw new Error( + "Connection string must be either an Account connection string or a SAS connection string" + ); } } else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } super(url2, pipeline2); this.appendBlobContext = this.storageClientContext.appendBlob; + this.blobClientConfig = options; } /** * Creates a new AppendBlobClient object identical to the source but with the @@ -70297,7 +100964,15 @@ var require_Clients = __commonJS({ * @returns A new AppendBlobClient object identical to the source but with the specified snapshot timestamp. */ withSnapshot(snapshot) { - return new _AppendBlobClient((0, utils_common_js_1.setURLParameter)(this.url, constants_js_1.URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? void 0 : snapshot), this.pipeline); + return new _AppendBlobClient( + (0, import_utils_common.setURLParameter)( + this.url, + import_constants5.URLConstants.Parameters.SNAPSHOT, + snapshot.length === 0 ? void 0 : snapshot + ), + this.pipeline, + this.blobClientConfig + ); } /** * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. @@ -70328,25 +101003,27 @@ var require_Clients = __commonJS({ */ async create(options = {}) { options.conditions = options.conditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("AppendBlobClient-create", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.appendBlobContext.create(0, { - abortSignal: options.abortSignal, - blobHttpHeaders: options.blobHTTPHeaders, - leaseAccessConditions: options.conditions, - metadata: options.metadata, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - immutabilityPolicyExpiry: options.immutabilityPolicy?.expiriesOn, - immutabilityPolicyMode: options.immutabilityPolicy?.policyMode, - legalHold: options.legalHold, - blobTagsString: (0, utils_common_js_1.toBlobTagsString)(options.tags), - tracingOptions: updatedOptions.tracingOptions - })); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan("AppendBlobClient-create", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.appendBlobContext.create(0, { + abortSignal: options.abortSignal, + blobHttpHeaders: options.blobHTTPHeaders, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + immutabilityPolicyExpiry: options.immutabilityPolicy?.expiriesOn, + immutabilityPolicyMode: options.immutabilityPolicy?.policyMode, + legalHold: options.legalHold, + blobTagsString: (0, import_utils_common.toBlobTagsString)(options.tags), + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } /** @@ -70357,30 +101034,36 @@ var require_Clients = __commonJS({ * @param options - */ async createIfNotExists(options = {}) { - const conditions = { ifNoneMatch: constants_js_1.ETagAny }; - return tracing_js_1.tracingClient.withSpan("AppendBlobClient-createIfNotExists", options, async (updatedOptions) => { - try { - const res = (0, utils_common_js_1.assertResponse)(await this.create({ - ...updatedOptions, - conditions - })); - return { - succeeded: true, - ...res, - _response: res._response - // _response is made non-enumerable - }; - } catch (e) { - if (e.details?.errorCode === "BlobAlreadyExists") { + const conditions = { ifNoneMatch: import_constants5.ETagAny }; + return import_tracing.tracingClient.withSpan( + "AppendBlobClient-createIfNotExists", + options, + async (updatedOptions) => { + try { + const res = (0, import_utils_common.assertResponse)( + await this.create({ + ...updatedOptions, + conditions + }) + ); return { - succeeded: false, - ...e.response?.parsedHeaders, - _response: e.response + succeeded: true, + ...res, + _response: res._response + // _response is made non-enumerable }; + } catch (e) { + if (e.details?.errorCode === "BlobAlreadyExists") { + return { + succeeded: false, + ...e.response?.parsedHeaders, + _response: e.response + }; + } + throw e; } - throw e; } - }); + ); } /** * Seals the append blob, making it read only. @@ -70389,17 +101072,19 @@ var require_Clients = __commonJS({ */ async seal(options = {}) { options.conditions = options.conditions || {}; - return tracing_js_1.tracingClient.withSpan("AppendBlobClient-seal", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.appendBlobContext.seal({ - abortSignal: options.abortSignal, - appendPositionAccessConditions: options.conditions, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - tracingOptions: updatedOptions.tracingOptions - })); + return import_tracing.tracingClient.withSpan("AppendBlobClient-seal", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.appendBlobContext.seal({ + abortSignal: options.abortSignal, + appendPositionAccessConditions: options.conditions, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } /** @@ -70441,26 +101126,42 @@ var require_Clients = __commonJS({ */ async appendBlock(body, contentLength, options = {}) { options.conditions = options.conditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("AppendBlobClient-appendBlock", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.appendBlobContext.appendBlock(contentLength, body, { - abortSignal: options.abortSignal, - appendPositionAccessConditions: options.conditions, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - requestOptions: { - onUploadProgress: options.onProgress - }, - transactionalContentMD5: options.transactionalContentMD5, - transactionalContentCrc64: options.transactionalContentCrc64, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - tracingOptions: updatedOptions.tracingOptions - })); - }); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan( + "AppendBlobClient-appendBlock", + options, + async (updatedOptions) => { + const parameters = { + abortSignal: options.abortSignal, + appendPositionAccessConditions: options.conditions, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + requestOptions: { + onUploadProgress: options.onProgress + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + }; + const uploadBodyParameters = await (0, import_utils_common.setUploadChecksumParameters)( + body, + contentLength, + parameters, + options, + this.blobClientConfig?.uploadContentChecksumAlgorithm + ); + return (0, import_utils_common.assertResponse)( + await this.appendBlobContext.appendBlock( + uploadBodyParameters.contentLength, + uploadBodyParameters.body, + parameters + ) + ); + } + ); } /** * The Append Block operation commits a new block of data to the end of an existing append blob @@ -70479,35 +101180,45 @@ var require_Clients = __commonJS({ async appendBlockFromURL(sourceURL, sourceOffset, count, options = {}) { options.conditions = options.conditions || {}; options.sourceConditions = options.sourceConditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("AppendBlobClient-appendBlockFromURL", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, { - abortSignal: options.abortSignal, - sourceRange: (0, Range_js_1.rangeToString)({ offset: sourceOffset, count }), - sourceContentMD5: options.sourceContentMD5, - sourceContentCrc64: options.sourceContentCrc64, - leaseAccessConditions: options.conditions, - appendPositionAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions?.ifMatch, - sourceIfModifiedSince: options.sourceConditions?.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions?.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions?.ifUnmodifiedSince - }, - copySourceAuthorization: (0, utils_common_js_1.httpAuthorizationToString)(options.sourceAuthorization), - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - fileRequestIntent: options.sourceShareTokenIntent, - tracingOptions: updatedOptions.tracingOptions - })); - }); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan( + "AppendBlobClient-appendBlockFromURL", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, { + abortSignal: options.abortSignal, + sourceRange: (0, import_Range.rangeToString)({ offset: sourceOffset, count }), + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + leaseAccessConditions: options.conditions, + appendPositionAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions?.ifMatch, + sourceIfModifiedSince: options.sourceConditions?.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions?.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions?.ifUnmodifiedSince + }, + copySourceAuthorization: (0, import_utils_common.httpAuthorizationToString)(options.sourceAuthorization), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + fileRequestIntent: options.sourceShareTokenIntent, + tracingOptions: updatedOptions.tracingOptions, + sourceCpkInfo: { + sourceEncryptionKey: options.sourceCustomerProvidedKey?.encryptionKey, + sourceEncryptionAlgorithm: options.sourceCustomerProvidedKey?.encryptionAlgorithm, + sourceEncryptionKeySha256: options.sourceCustomerProvidedKey?.encryptionKeySha256 + } + }) + ); + } + ); } }; - exports2.AppendBlobClient = AppendBlobClient; var BlockBlobClient = class _BlockBlobClient extends BlobClient { /** * blobContext provided by protocol layer. @@ -70524,39 +101235,51 @@ var require_Clients = __commonJS({ let pipeline2; let url2; options = options || {}; - if ((0, Pipeline_js_1.isPipelineLike)(credentialOrPipelineOrContainerName)) { + if ((0, import_Pipeline.isPipelineLike)(credentialOrPipelineOrContainerName)) { url2 = urlOrConnectionString; pipeline2 = credentialOrPipelineOrContainerName; - } else if (core_util_1.isNodeLike && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential_js_1.AnonymousCredential || (0, core_auth_1.isTokenCredential)(credentialOrPipelineOrContainerName)) { + options = blobNameOrOptions; + } else if (import_core_util.isNodeLike && credentialOrPipelineOrContainerName instanceof import_storage_common.StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof import_storage_common.AnonymousCredential || (0, import_core_auth.isTokenCredential)(credentialOrPipelineOrContainerName)) { url2 = urlOrConnectionString; options = blobNameOrOptions; - pipeline2 = (0, Pipeline_js_1.newPipeline)(credentialOrPipelineOrContainerName, options); + pipeline2 = (0, import_Pipeline.newPipeline)(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { url2 = urlOrConnectionString; if (blobNameOrOptions && typeof blobNameOrOptions !== "string") { options = blobNameOrOptions; } - pipeline2 = (0, Pipeline_js_1.newPipeline)(new AnonymousCredential_js_1.AnonymousCredential(), options); + pipeline2 = (0, import_Pipeline.newPipeline)(new import_storage_common.AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { const containerName = credentialOrPipelineOrContainerName; const blobName = blobNameOrOptions; - const extractedCreds = (0, utils_common_js_1.extractConnectionStringParts)(urlOrConnectionString); + const extractedCreds = (0, import_utils_common.extractConnectionStringParts)(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { - if (core_util_1.isNodeLike) { - const sharedKeyCredential = new StorageSharedKeyCredential_js_1.StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url2 = (0, utils_common_js_1.appendToURLPath)((0, utils_common_js_1.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + if (import_core_util.isNodeLike) { + const sharedKeyCredential = new import_storage_common.StorageSharedKeyCredential( + extractedCreds.accountName, + extractedCreds.accountKey + ); + url2 = (0, import_utils_common.appendToURLPath)( + (0, import_utils_common.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), + encodeURIComponent(blobName) + ); if (!options.proxyOptions) { - options.proxyOptions = (0, core_rest_pipeline_1.getDefaultProxySettings)(extractedCreds.proxyUri); + options.proxyOptions = (0, import_core_rest_pipeline.getDefaultProxySettings)(extractedCreds.proxyUri); } - pipeline2 = (0, Pipeline_js_1.newPipeline)(sharedKeyCredential, options); + pipeline2 = (0, import_Pipeline.newPipeline)(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } else if (extractedCreds.kind === "SASConnString") { - url2 = (0, utils_common_js_1.appendToURLPath)((0, utils_common_js_1.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; - pipeline2 = (0, Pipeline_js_1.newPipeline)(new AnonymousCredential_js_1.AnonymousCredential(), options); + url2 = (0, import_utils_common.appendToURLPath)( + (0, import_utils_common.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), + encodeURIComponent(blobName) + ) + "?" + extractedCreds.accountSas; + pipeline2 = (0, import_Pipeline.newPipeline)(new import_storage_common.AnonymousCredential(), options); } else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + throw new Error( + "Connection string must be either an Account connection string or a SAS connection string" + ); } } else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); @@ -70564,6 +101287,7 @@ var require_Clients = __commonJS({ super(url2, pipeline2); this.blockBlobContext = this.storageClientContext.blockBlob; this._blobContext = this.storageClientContext.blob; + this.blobClientConfig = options; } /** * Creates a new BlockBlobClient object identical to the source but with the @@ -70574,7 +101298,15 @@ var require_Clients = __commonJS({ * @returns A new BlockBlobClient object identical to the source but with the specified snapshot timestamp. */ withSnapshot(snapshot) { - return new _BlockBlobClient((0, utils_common_js_1.setURLParameter)(this.url, constants_js_1.URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? void 0 : snapshot), this.pipeline); + return new _BlockBlobClient( + (0, import_utils_common.setURLParameter)( + this.url, + import_constants5.URLConstants.Parameters.SNAPSHOT, + snapshot.length === 0 ? void 0 : snapshot + ), + this.pipeline, + this.blobClientConfig + ); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. @@ -70586,6 +101318,7 @@ var require_Clients = __commonJS({ * ```ts snippet:ClientsQuery * import { BlobServiceClient } from "@azure/storage-blob"; * import { DefaultAzureCredential } from "@azure/identity"; + * import { buffer } from "node:stream/consumers"; * * const account = ""; * const blobServiceClient = new BlobServiceClient( @@ -70601,22 +101334,10 @@ var require_Clients = __commonJS({ * // Query and convert a blob to a string * const queryBlockBlobResponse = await blockBlobClient.query("select from BlobStorage"); * if (queryBlockBlobResponse.readableStreamBody) { - * const downloadedBuffer = await streamToBuffer(queryBlockBlobResponse.readableStreamBody); - * const downloaded = downloadedBuffer.toString(); - * console.log(`Query blob content: ${downloaded}`); - * } - * - * async function streamToBuffer(readableStream: NodeJS.ReadableStream): Promise { - * return new Promise((resolve, reject) => { - * const chunks: Buffer[] = []; - * readableStream.on("data", (data) => { - * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); - * }); - * readableStream.on("end", () => { - * resolve(Buffer.concat(chunks)); - * }); - * readableStream.on("error", reject); - * }); + * // Read the response bytes. Use `text` from "node:stream/consumers" instead + * // if you want the response as a string directly. + * const downloadedBuffer = await buffer(queryBlockBlobResponse.readableStreamBody); + * console.log(`Query blob content: ${downloadedBuffer.toString()}`); * } * ``` * @@ -70624,28 +101345,30 @@ var require_Clients = __commonJS({ * @param options - */ async query(query, options = {}) { - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - if (!core_util_1.isNodeLike) { + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + if (!import_core_util.isNodeLike) { throw new Error("This operation currently is only supported in Node.js."); } - return tracing_js_1.tracingClient.withSpan("BlockBlobClient-query", options, async (updatedOptions) => { - const response = (0, utils_common_js_1.assertResponse)(await this._blobContext.query({ - abortSignal: options.abortSignal, - queryRequest: { - queryType: "SQL", - expression: query, - inputSerialization: (0, utils_common_js_1.toQuerySerialization)(options.inputTextConfiguration), - outputSerialization: (0, utils_common_js_1.toQuerySerialization)(options.outputTextConfiguration) - }, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - cpkInfo: options.customerProvidedKey, - tracingOptions: updatedOptions.tracingOptions - })); - return new BlobQueryResponse_js_1.BlobQueryResponse(response, { + return import_tracing.tracingClient.withSpan("BlockBlobClient-query", options, async (updatedOptions) => { + const response = (0, import_utils_common.assertResponse)( + await this._blobContext.query({ + abortSignal: options.abortSignal, + queryRequest: { + queryType: "SQL", + expression: query, + inputSerialization: (0, import_utils_common.toQuerySerialization)(options.inputTextConfiguration), + outputSerialization: (0, import_utils_common.toQuerySerialization)(options.outputTextConfiguration) + }, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + cpkInfo: options.customerProvidedKey, + tracingOptions: updatedOptions.tracingOptions + }) + ); + return new import_BlobQueryResponse.BlobQueryResponse(response, { abortSignal: options.abortSignal, onProgress: options.onProgress, onError: options.onError @@ -70695,9 +101418,9 @@ var require_Clients = __commonJS({ */ async upload(body, contentLength, options = {}) { options.conditions = options.conditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("BlockBlobClient-upload", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blockBlobContext.upload(contentLength, body, { + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan("BlockBlobClient-upload", options, async (updatedOptions) => { + const parameters = { abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, @@ -70714,10 +101437,24 @@ var require_Clients = __commonJS({ immutabilityPolicyExpiry: options.immutabilityPolicy?.expiriesOn, immutabilityPolicyMode: options.immutabilityPolicy?.policyMode, legalHold: options.legalHold, - tier: (0, models_js_1.toAccessTier)(options.tier), - blobTagsString: (0, utils_common_js_1.toBlobTagsString)(options.tags), + tier: (0, import_models.toAccessTier)(options.tier), + blobTagsString: (0, import_utils_common.toBlobTagsString)(options.tags), tracingOptions: updatedOptions.tracingOptions - })); + }; + const uploadBodyParameters = await (0, import_utils_common.setUploadChecksumParameters)( + body, + contentLength, + parameters, + options, + this.blobClientConfig?.uploadContentChecksumAlgorithm + ); + return (0, import_utils_common.assertResponse)( + await this.blockBlobContext.upload( + uploadBodyParameters.contentLength, + uploadBodyParameters.body, + parameters + ) + ); }); } /** @@ -70740,32 +101477,43 @@ var require_Clients = __commonJS({ */ async syncUploadFromURL(sourceURL, options = {}) { options.conditions = options.conditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("BlockBlobClient-syncUploadFromURL", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blockBlobContext.putBlobFromUrl(0, sourceURL, { - ...options, - blobHttpHeaders: options.blobHTTPHeaders, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions?.ifMatch, - sourceIfModifiedSince: options.sourceConditions?.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions?.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions?.ifUnmodifiedSince, - sourceIfTags: options.sourceConditions?.tagConditions - }, - cpkInfo: options.customerProvidedKey, - copySourceAuthorization: (0, utils_common_js_1.httpAuthorizationToString)(options.sourceAuthorization), - tier: (0, models_js_1.toAccessTier)(options.tier), - blobTagsString: (0, utils_common_js_1.toBlobTagsString)(options.tags), - copySourceTags: options.copySourceTags, - fileRequestIntent: options.sourceShareTokenIntent, - tracingOptions: updatedOptions.tracingOptions - })); - }); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan( + "BlockBlobClient-syncUploadFromURL", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blockBlobContext.putBlobFromUrl(0, sourceURL, { + ...options, + blobHttpHeaders: options.blobHTTPHeaders, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions?.ifMatch, + sourceIfModifiedSince: options.sourceConditions?.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions?.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions?.ifUnmodifiedSince, + sourceIfTags: options.sourceConditions?.tagConditions + }, + cpkInfo: options.customerProvidedKey, + copySourceAuthorization: (0, import_utils_common.httpAuthorizationToString)(options.sourceAuthorization), + tier: (0, import_models.toAccessTier)(options.tier), + blobTagsString: (0, import_utils_common.toBlobTagsString)(options.tags), + copySourceTags: options.copySourceTags, + fileRequestIntent: options.sourceShareTokenIntent, + tracingOptions: updatedOptions.tracingOptions, + sourceCpkInfo: { + sourceEncryptionKey: options.sourceCustomerProvidedKey?.encryptionKey, + sourceEncryptionAlgorithm: options.sourceCustomerProvidedKey?.encryptionAlgorithm, + sourceEncryptionKeySha256: options.sourceCustomerProvidedKey?.encryptionKeySha256 + } + }) + ); + } + ); } /** * Uploads the specified block to the block blob's "staging area" to be later @@ -70779,20 +101527,33 @@ var require_Clients = __commonJS({ * @returns Response data for the Block Blob Stage Block operation. */ async stageBlock(blockId, body, contentLength, options = {}) { - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("BlockBlobClient-stageBlock", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blockBlobContext.stageBlock(blockId, contentLength, body, { + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan("BlockBlobClient-stageBlock", options, async (updatedOptions) => { + const parameters = { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, requestOptions: { onUploadProgress: options.onProgress }, - transactionalContentMD5: options.transactionalContentMD5, - transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions - })); + }; + const uploadBodyParameters = await (0, import_utils_common.setUploadChecksumParameters)( + body, + contentLength, + parameters, + options, + this.blobClientConfig?.uploadContentChecksumAlgorithm + ); + return (0, import_utils_common.assertResponse)( + await this.blockBlobContext.stageBlock( + blockId, + uploadBodyParameters.contentLength, + uploadBodyParameters.body, + parameters + ) + ); }); } /** @@ -70817,21 +101578,32 @@ var require_Clients = __commonJS({ * @returns Response data for the Block Blob Stage Block From URL operation. */ async stageBlockFromURL(blockId, sourceURL, offset = 0, count, options = {}) { - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("BlockBlobClient-stageBlockFromURL", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - sourceContentMD5: options.sourceContentMD5, - sourceContentCrc64: options.sourceContentCrc64, - sourceRange: offset === 0 && !count ? void 0 : (0, Range_js_1.rangeToString)({ offset, count }), - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - copySourceAuthorization: (0, utils_common_js_1.httpAuthorizationToString)(options.sourceAuthorization), - fileRequestIntent: options.sourceShareTokenIntent, - tracingOptions: updatedOptions.tracingOptions - })); - }); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan( + "BlockBlobClient-stageBlockFromURL", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + sourceRange: offset === 0 && !count ? void 0 : (0, import_Range.rangeToString)({ offset, count }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + copySourceAuthorization: (0, import_utils_common.httpAuthorizationToString)(options.sourceAuthorization), + fileRequestIntent: options.sourceShareTokenIntent, + tracingOptions: updatedOptions.tracingOptions, + sourceCpkInfo: { + sourceEncryptionKey: options.sourceCustomerProvidedKey?.encryptionKey, + sourceEncryptionAlgorithm: options.sourceCustomerProvidedKey?.encryptionAlgorithm, + sourceEncryptionKeySha256: options.sourceCustomerProvidedKey?.encryptionKeySha256 + } + }) + ); + } + ); } /** * Writes a blob by specifying the list of block IDs that make up the blob. @@ -70847,27 +101619,36 @@ var require_Clients = __commonJS({ */ async commitBlockList(blocks, options = {}) { options.conditions = options.conditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("BlockBlobClient-commitBlockList", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.blockBlobContext.commitBlockList({ latest: blocks }, { - abortSignal: options.abortSignal, - blobHttpHeaders: options.blobHTTPHeaders, - leaseAccessConditions: options.conditions, - metadata: options.metadata, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - immutabilityPolicyExpiry: options.immutabilityPolicy?.expiriesOn, - immutabilityPolicyMode: options.immutabilityPolicy?.policyMode, - legalHold: options.legalHold, - tier: (0, models_js_1.toAccessTier)(options.tier), - blobTagsString: (0, utils_common_js_1.toBlobTagsString)(options.tags), - tracingOptions: updatedOptions.tracingOptions - })); - }); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan( + "BlockBlobClient-commitBlockList", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.blockBlobContext.commitBlockList( + { latest: blocks }, + { + abortSignal: options.abortSignal, + blobHttpHeaders: options.blobHTTPHeaders, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + immutabilityPolicyExpiry: options.immutabilityPolicy?.expiriesOn, + immutabilityPolicyMode: options.immutabilityPolicy?.policyMode, + legalHold: options.legalHold, + tier: (0, import_models.toAccessTier)(options.tier), + blobTagsString: (0, import_utils_common.toBlobTagsString)(options.tags), + tracingOptions: updatedOptions.tracingOptions + } + ) + ); + } + ); } /** * Returns the list of blocks that have been uploaded as part of a block blob @@ -70880,24 +101661,30 @@ var require_Clients = __commonJS({ * @returns Response data for the Block Blob Get Block List operation. */ async getBlockList(listType, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlockBlobClient-getBlockList", options, async (updatedOptions) => { - const res = (0, utils_common_js_1.assertResponse)(await this.blockBlobContext.getBlockList(listType, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - tracingOptions: updatedOptions.tracingOptions - })); - if (!res.committedBlocks) { - res.committedBlocks = []; - } - if (!res.uncommittedBlocks) { - res.uncommittedBlocks = []; + return import_tracing.tracingClient.withSpan( + "BlockBlobClient-getBlockList", + options, + async (updatedOptions) => { + const res = (0, import_utils_common.assertResponse)( + await this.blockBlobContext.getBlockList(listType, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + tracingOptions: updatedOptions.tracingOptions + }) + ); + if (!res.committedBlocks) { + res.committedBlocks = []; + } + if (!res.uncommittedBlocks) { + res.uncommittedBlocks = []; + } + return res; } - return res; - }); + ); } // High level functions /** @@ -70916,8 +101703,8 @@ var require_Clients = __commonJS({ * @param options - */ async uploadData(data, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlockBlobClient-uploadData", options, async (updatedOptions) => { - if (core_util_1.isNodeLike) { + return import_tracing.tracingClient.withSpan("BlockBlobClient-uploadData", options, async (updatedOptions) => { + if (import_core_util.isNodeLike) { let buffer; if (data instanceof Buffer) { buffer = data; @@ -70927,10 +101714,18 @@ var require_Clients = __commonJS({ data = data; buffer = Buffer.from(data.buffer, data.byteOffset, data.byteLength); } - return this.uploadSeekableInternal((offset, size) => buffer.slice(offset, offset + size), buffer.byteLength, updatedOptions); + return this.uploadSeekableInternal( + (offset, size) => buffer.slice(offset, offset + size), + buffer.byteLength, + updatedOptions + ); } else { const browserBlob = new Blob([data]); - return this.uploadSeekableInternal((offset, size) => browserBlob.slice(offset, offset + size), browserBlob.size, updatedOptions); + return this.uploadSeekableInternal( + (offset, size) => browserBlob.slice(offset, offset + size), + browserBlob.size, + updatedOptions + ); } }); } @@ -70954,10 +101749,18 @@ var require_Clients = __commonJS({ * @returns Response data for the Blob Upload operation. */ async uploadBrowserData(browserData, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlockBlobClient-uploadBrowserData", options, async (updatedOptions) => { - const browserBlob = new Blob([browserData]); - return this.uploadSeekableInternal((offset, size) => browserBlob.slice(offset, offset + size), browserBlob.size, updatedOptions); - }); + return import_tracing.tracingClient.withSpan( + "BlockBlobClient-uploadBrowserData", + options, + async (updatedOptions) => { + const browserBlob = new Blob([browserData]); + return this.uploadSeekableInternal( + (offset, size) => browserBlob.slice(offset, offset + size), + browserBlob.size, + updatedOptions + ); + } + ); } /** * @@ -70976,21 +101779,25 @@ var require_Clients = __commonJS({ */ async uploadSeekableInternal(bodyFactory, size, options = {}) { let blockSize = options.blockSize ?? 0; - if (blockSize < 0 || blockSize > constants_js_1.BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { - throw new RangeError(`blockSize option must be >= 0 and <= ${constants_js_1.BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES}`); + if (blockSize < 0 || blockSize > import_constants5.BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { + throw new RangeError( + `blockSize option must be >= 0 and <= ${import_constants5.BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES}` + ); } - const maxSingleShotSize = options.maxSingleShotSize ?? constants_js_1.BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES; - if (maxSingleShotSize < 0 || maxSingleShotSize > constants_js_1.BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) { - throw new RangeError(`maxSingleShotSize option must be >= 0 and <= ${constants_js_1.BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}`); + const maxSingleShotSize = options.maxSingleShotSize ?? import_constants5.BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES; + if (maxSingleShotSize < 0 || maxSingleShotSize > import_constants5.BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) { + throw new RangeError( + `maxSingleShotSize option must be >= 0 and <= ${import_constants5.BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}` + ); } if (blockSize === 0) { - if (size > constants_js_1.BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES * constants_js_1.BLOCK_BLOB_MAX_BLOCKS) { + if (size > import_constants5.BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES * import_constants5.BLOCK_BLOB_MAX_BLOCKS) { throw new RangeError(`${size} is too larger to upload to a block blob.`); } if (size > maxSingleShotSize) { - blockSize = Math.ceil(size / constants_js_1.BLOCK_BLOB_MAX_BLOCKS); - if (blockSize < constants_js_1.DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) { - blockSize = constants_js_1.DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; + blockSize = Math.ceil(size / import_constants5.BLOCK_BLOB_MAX_BLOCKS); + if (blockSize < import_constants5.DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) { + blockSize = import_constants5.DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; } } } @@ -71000,42 +101807,49 @@ var require_Clients = __commonJS({ if (!options.conditions) { options.conditions = {}; } - return tracing_js_1.tracingClient.withSpan("BlockBlobClient-uploadSeekableInternal", options, async (updatedOptions) => { - if (size <= maxSingleShotSize) { - return (0, utils_common_js_1.assertResponse)(await this.upload(bodyFactory(0, size), size, updatedOptions)); - } - const numBlocks = Math.floor((size - 1) / blockSize) + 1; - if (numBlocks > constants_js_1.BLOCK_BLOB_MAX_BLOCKS) { - throw new RangeError(`The buffer's size is too big or the BlockSize is too small;the number of blocks must be <= ${constants_js_1.BLOCK_BLOB_MAX_BLOCKS}`); - } - const blockList = []; - const blockIDPrefix = (0, core_util_2.randomUUID)(); - let transferProgress = 0; - const batch = new Batch_js_1.Batch(options.concurrency); - for (let i = 0; i < numBlocks; i++) { - batch.addOperation(async () => { - const blockID = (0, utils_common_js_1.generateBlockID)(blockIDPrefix, i); - const start = blockSize * i; - const end = i === numBlocks - 1 ? size : start + blockSize; - const contentLength = end - start; - blockList.push(blockID); - await this.stageBlock(blockID, bodyFactory(start, contentLength), contentLength, { - abortSignal: options.abortSignal, - conditions: options.conditions, - encryptionScope: options.encryptionScope, - tracingOptions: updatedOptions.tracingOptions - }); - transferProgress += contentLength; - if (options.onProgress) { - options.onProgress({ - loadedBytes: transferProgress + return import_tracing.tracingClient.withSpan( + "BlockBlobClient-uploadSeekableInternal", + options, + async (updatedOptions) => { + if (size <= maxSingleShotSize) { + return (0, import_utils_common.assertResponse)(await this.upload(bodyFactory(0, size), size, updatedOptions)); + } + const numBlocks = Math.floor((size - 1) / blockSize) + 1; + if (numBlocks > import_constants5.BLOCK_BLOB_MAX_BLOCKS) { + throw new RangeError( + `The buffer's size is too big or the BlockSize is too small;the number of blocks must be <= ${import_constants5.BLOCK_BLOB_MAX_BLOCKS}` + ); + } + const blockList = []; + const blockIDPrefix = (0, import_core_util2.randomUUID)(); + let transferProgress = 0; + const batch = new import_Batch.Batch(options.concurrency); + for (let i = 0; i < numBlocks; i++) { + batch.addOperation(async () => { + const blockID = (0, import_utils_common.generateBlockID)(blockIDPrefix, i); + const start = blockSize * i; + const end = i === numBlocks - 1 ? size : start + blockSize; + const contentLength = end - start; + blockList.push(blockID); + await this.stageBlock(blockID, bodyFactory(start, contentLength), contentLength, { + abortSignal: options.abortSignal, + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions, + contentChecksumAlgorithm: options.contentChecksumAlgorithm }); - } - }); + transferProgress += contentLength; + if (options.onProgress) { + options.onProgress({ + loadedBytes: transferProgress + }); + } + }); + } + await batch.do(); + return this.commitBlockList(blockList, updatedOptions); } - await batch.do(); - return this.commitBlockList(blockList, updatedOptions); - }); + ); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. @@ -71051,18 +101865,22 @@ var require_Clients = __commonJS({ * @returns Response data for the Blob Upload operation. */ async uploadFile(filePath, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlockBlobClient-uploadFile", options, async (updatedOptions) => { - const size = (await (0, utils_js_1.fsStat)(filePath)).size; - return this.uploadSeekableInternal((offset, count) => { - return () => (0, utils_js_1.fsCreateReadStream)(filePath, { - autoClose: true, - end: count ? offset + count - 1 : Infinity, - start: offset - }); - }, size, { - ...options, - tracingOptions: updatedOptions.tracingOptions - }); + return import_tracing.tracingClient.withSpan("BlockBlobClient-uploadFile", options, async (updatedOptions) => { + const size = (await (0, import_utils5.fsStat)(filePath)).size; + return this.uploadSeekableInternal( + (offset, count) => { + return () => (0, import_utils5.fsCreateReadStream)(filePath, { + autoClose: true, + end: count ? offset + count - 1 : Infinity, + start: offset + }); + }, + size, + { + ...options, + tracingOptions: updatedOptions.tracingOptions + } + ); }); } /** @@ -71081,52 +101899,58 @@ var require_Clients = __commonJS({ * @param options - Options to Upload Stream to Block Blob operation. * @returns Response data for the Blob Upload operation. */ - async uploadStream(stream2, bufferSize = constants_js_1.DEFAULT_BLOCK_BUFFER_SIZE_BYTES, maxConcurrency = 5, options = {}) { + async uploadStream(stream2, bufferSize = import_constants5.DEFAULT_BLOCK_BUFFER_SIZE_BYTES, maxConcurrency = 5, options = {}) { if (!options.blobHTTPHeaders) { options.blobHTTPHeaders = {}; } if (!options.conditions) { options.conditions = {}; } - return tracing_js_1.tracingClient.withSpan("BlockBlobClient-uploadStream", options, async (updatedOptions) => { - let blockNum = 0; - const blockIDPrefix = (0, core_util_2.randomUUID)(); - let transferProgress = 0; - const blockList = []; - const scheduler = new storage_common_1.BufferScheduler( - stream2, - bufferSize, - maxConcurrency, - async (body, length) => { - const blockID = (0, utils_common_js_1.generateBlockID)(blockIDPrefix, blockNum); - blockList.push(blockID); - blockNum++; - await this.stageBlock(blockID, body, length, { - customerProvidedKey: options.customerProvidedKey, - conditions: options.conditions, - encryptionScope: options.encryptionScope, + return import_tracing.tracingClient.withSpan( + "BlockBlobClient-uploadStream", + options, + async (updatedOptions) => { + let blockNum = 0; + const blockIDPrefix = (0, import_core_util2.randomUUID)(); + let transferProgress = 0; + const blockList = []; + const scheduler = new import_storage_common2.BufferScheduler( + stream2, + bufferSize, + maxConcurrency, + async (body, length) => { + const blockID = (0, import_utils_common.generateBlockID)(blockIDPrefix, blockNum); + blockList.push(blockID); + blockNum++; + await this.stageBlock(blockID, body, length, { + customerProvidedKey: options.customerProvidedKey, + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions, + contentChecksumAlgorithm: options.contentChecksumAlgorithm + }); + transferProgress += length; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress }); + } + }, + // concurrency should set a smaller value than maxConcurrency, which is helpful to + // reduce the possibility when a outgoing handler waits for stream data, in + // this situation, outgoing handlers are blocked. + // Outgoing queue shouldn't be empty. + Math.ceil(maxConcurrency / 4 * 3) + ); + await scheduler.do(); + return (0, import_utils_common.assertResponse)( + await this.commitBlockList(blockList, { + ...options, tracingOptions: updatedOptions.tracingOptions - }); - transferProgress += length; - if (options.onProgress) { - options.onProgress({ loadedBytes: transferProgress }); - } - }, - // concurrency should set a smaller value than maxConcurrency, which is helpful to - // reduce the possibility when a outgoing handler waits for stream data, in - // this situation, outgoing handlers are blocked. - // Outgoing queue shouldn't be empty. - Math.ceil(maxConcurrency / 4 * 3) - ); - await scheduler.do(); - return (0, utils_common_js_1.assertResponse)(await this.commitBlockList(blockList, { - ...options, - tracingOptions: updatedOptions.tracingOptions - })); - }); + }) + ); + } + ); } }; - exports2.BlockBlobClient = BlockBlobClient; var PageBlobClient = class _PageBlobClient extends BlobClient { /** * pageBlobsContext provided by protocol layer. @@ -71136,42 +101960,56 @@ var require_Clients = __commonJS({ let pipeline2; let url2; options = options || {}; - if ((0, Pipeline_js_1.isPipelineLike)(credentialOrPipelineOrContainerName)) { + if ((0, import_Pipeline.isPipelineLike)(credentialOrPipelineOrContainerName)) { url2 = urlOrConnectionString; pipeline2 = credentialOrPipelineOrContainerName; - } else if (core_util_1.isNodeLike && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential_js_1.AnonymousCredential || (0, core_auth_1.isTokenCredential)(credentialOrPipelineOrContainerName)) { + options = blobNameOrOptions; + } else if (import_core_util.isNodeLike && credentialOrPipelineOrContainerName instanceof import_storage_common.StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof import_storage_common.AnonymousCredential || (0, import_core_auth.isTokenCredential)(credentialOrPipelineOrContainerName)) { url2 = urlOrConnectionString; options = blobNameOrOptions; - pipeline2 = (0, Pipeline_js_1.newPipeline)(credentialOrPipelineOrContainerName, options); + pipeline2 = (0, import_Pipeline.newPipeline)(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { url2 = urlOrConnectionString; - pipeline2 = (0, Pipeline_js_1.newPipeline)(new AnonymousCredential_js_1.AnonymousCredential(), options); + options = blobNameOrOptions; + pipeline2 = (0, import_Pipeline.newPipeline)(new import_storage_common.AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { const containerName = credentialOrPipelineOrContainerName; const blobName = blobNameOrOptions; - const extractedCreds = (0, utils_common_js_1.extractConnectionStringParts)(urlOrConnectionString); + const extractedCreds = (0, import_utils_common.extractConnectionStringParts)(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { - if (core_util_1.isNodeLike) { - const sharedKeyCredential = new StorageSharedKeyCredential_js_1.StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url2 = (0, utils_common_js_1.appendToURLPath)((0, utils_common_js_1.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + if (import_core_util.isNodeLike) { + const sharedKeyCredential = new import_storage_common.StorageSharedKeyCredential( + extractedCreds.accountName, + extractedCreds.accountKey + ); + url2 = (0, import_utils_common.appendToURLPath)( + (0, import_utils_common.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), + encodeURIComponent(blobName) + ); if (!options.proxyOptions) { - options.proxyOptions = (0, core_rest_pipeline_1.getDefaultProxySettings)(extractedCreds.proxyUri); + options.proxyOptions = (0, import_core_rest_pipeline.getDefaultProxySettings)(extractedCreds.proxyUri); } - pipeline2 = (0, Pipeline_js_1.newPipeline)(sharedKeyCredential, options); + pipeline2 = (0, import_Pipeline.newPipeline)(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } else if (extractedCreds.kind === "SASConnString") { - url2 = (0, utils_common_js_1.appendToURLPath)((0, utils_common_js_1.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; - pipeline2 = (0, Pipeline_js_1.newPipeline)(new AnonymousCredential_js_1.AnonymousCredential(), options); + url2 = (0, import_utils_common.appendToURLPath)( + (0, import_utils_common.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)), + encodeURIComponent(blobName) + ) + "?" + extractedCreds.accountSas; + pipeline2 = (0, import_Pipeline.newPipeline)(new import_storage_common.AnonymousCredential(), options); } else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + throw new Error( + "Connection string must be either an Account connection string or a SAS connection string" + ); } } else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } super(url2, pipeline2); this.pageBlobContext = this.storageClientContext.pageBlob; + this.blobClientConfig = options; } /** * Creates a new PageBlobClient object identical to the source but with the @@ -71182,7 +102020,15 @@ var require_Clients = __commonJS({ * @returns A new PageBlobClient object identical to the source but with the specified snapshot timestamp. */ withSnapshot(snapshot) { - return new _PageBlobClient((0, utils_common_js_1.setURLParameter)(this.url, constants_js_1.URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? void 0 : snapshot), this.pipeline); + return new _PageBlobClient( + (0, import_utils_common.setURLParameter)( + this.url, + import_constants5.URLConstants.Parameters.SNAPSHOT, + snapshot.length === 0 ? void 0 : snapshot + ), + this.pipeline, + this.blobClientConfig + ); } /** * Creates a page blob of the specified length. Call uploadPages to upload data @@ -71195,27 +102041,29 @@ var require_Clients = __commonJS({ */ async create(size, options = {}) { options.conditions = options.conditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("PageBlobClient-create", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.pageBlobContext.create(0, size, { - abortSignal: options.abortSignal, - blobHttpHeaders: options.blobHTTPHeaders, - blobSequenceNumber: options.blobSequenceNumber, - leaseAccessConditions: options.conditions, - metadata: options.metadata, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - immutabilityPolicyExpiry: options.immutabilityPolicy?.expiriesOn, - immutabilityPolicyMode: options.immutabilityPolicy?.policyMode, - legalHold: options.legalHold, - tier: (0, models_js_1.toAccessTier)(options.tier), - blobTagsString: (0, utils_common_js_1.toBlobTagsString)(options.tags), - tracingOptions: updatedOptions.tracingOptions - })); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan("PageBlobClient-create", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.pageBlobContext.create(0, size, { + abortSignal: options.abortSignal, + blobHttpHeaders: options.blobHTTPHeaders, + blobSequenceNumber: options.blobSequenceNumber, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + immutabilityPolicyExpiry: options.immutabilityPolicy?.expiriesOn, + immutabilityPolicyMode: options.immutabilityPolicy?.policyMode, + legalHold: options.legalHold, + tier: (0, import_models.toAccessTier)(options.tier), + blobTagsString: (0, import_utils_common.toBlobTagsString)(options.tags), + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } /** @@ -71228,31 +102076,37 @@ var require_Clients = __commonJS({ * @param options - */ async createIfNotExists(size, options = {}) { - return tracing_js_1.tracingClient.withSpan("PageBlobClient-createIfNotExists", options, async (updatedOptions) => { - try { - const conditions = { ifNoneMatch: constants_js_1.ETagAny }; - const res = (0, utils_common_js_1.assertResponse)(await this.create(size, { - ...options, - conditions, - tracingOptions: updatedOptions.tracingOptions - })); - return { - succeeded: true, - ...res, - _response: res._response - // _response is made non-enumerable - }; - } catch (e) { - if (e.details?.errorCode === "BlobAlreadyExists") { + return import_tracing.tracingClient.withSpan( + "PageBlobClient-createIfNotExists", + options, + async (updatedOptions) => { + try { + const conditions = { ifNoneMatch: import_constants5.ETagAny }; + const res = (0, import_utils_common.assertResponse)( + await this.create(size, { + ...options, + conditions, + tracingOptions: updatedOptions.tracingOptions + }) + ); return { - succeeded: false, - ...e.response?.parsedHeaders, - _response: e.response + succeeded: true, + ...res, + _response: res._response + // _response is made non-enumerable }; + } catch (e) { + if (e.details?.errorCode === "BlobAlreadyExists") { + return { + succeeded: false, + ...e.response?.parsedHeaders, + _response: e.response + }; + } + throw e; } - throw e; } - }); + ); } /** * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. @@ -71266,9 +102120,9 @@ var require_Clients = __commonJS({ */ async uploadPages(body, offset, count, options = {}) { options.conditions = options.conditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("PageBlobClient-uploadPages", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.pageBlobContext.uploadPages(count, body, { + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan("PageBlobClient-uploadPages", options, async (updatedOptions) => { + const parameters = { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: { @@ -71278,14 +102132,26 @@ var require_Clients = __commonJS({ requestOptions: { onUploadProgress: options.onProgress }, - range: (0, Range_js_1.rangeToString)({ offset, count }), + range: (0, import_Range.rangeToString)({ offset, count }), sequenceNumberAccessConditions: options.conditions, - transactionalContentMD5: options.transactionalContentMD5, - transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions - })); + }; + const uploadBodyParameters = await (0, import_utils_common.setUploadChecksumParameters)( + body, + count, + parameters, + options, + this.blobClientConfig?.uploadContentChecksumAlgorithm + ); + return (0, import_utils_common.assertResponse)( + await this.pageBlobContext.uploadPages( + uploadBodyParameters.contentLength, + uploadBodyParameters.body, + parameters + ) + ); }); } /** @@ -71302,31 +102168,48 @@ var require_Clients = __commonJS({ async uploadPagesFromURL(sourceURL, sourceOffset, destOffset, count, options = {}) { options.conditions = options.conditions || {}; options.sourceConditions = options.sourceConditions || {}; - (0, models_js_1.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); - return tracing_js_1.tracingClient.withSpan("PageBlobClient-uploadPagesFromURL", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.pageBlobContext.uploadPagesFromURL(sourceURL, (0, Range_js_1.rangeToString)({ offset: sourceOffset, count }), 0, (0, Range_js_1.rangeToString)({ offset: destOffset, count }), { - abortSignal: options.abortSignal, - sourceContentMD5: options.sourceContentMD5, - sourceContentCrc64: options.sourceContentCrc64, - leaseAccessConditions: options.conditions, - sequenceNumberAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions?.ifMatch, - sourceIfModifiedSince: options.sourceConditions?.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions?.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions?.ifUnmodifiedSince - }, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - copySourceAuthorization: (0, utils_common_js_1.httpAuthorizationToString)(options.sourceAuthorization), - fileRequestIntent: options.sourceShareTokenIntent, - tracingOptions: updatedOptions.tracingOptions - })); - }); + (0, import_models.ensureCpkIfSpecified)(options.customerProvidedKey, this.isHttps); + return import_tracing.tracingClient.withSpan( + "PageBlobClient-uploadPagesFromURL", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.pageBlobContext.uploadPagesFromURL( + sourceURL, + (0, import_Range.rangeToString)({ offset: sourceOffset, count }), + 0, + (0, import_Range.rangeToString)({ offset: destOffset, count }), + { + abortSignal: options.abortSignal, + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + leaseAccessConditions: options.conditions, + sequenceNumberAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions?.ifMatch, + sourceIfModifiedSince: options.sourceConditions?.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions?.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions?.ifUnmodifiedSince + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + copySourceAuthorization: (0, import_utils_common.httpAuthorizationToString)(options.sourceAuthorization), + fileRequestIntent: options.sourceShareTokenIntent, + tracingOptions: updatedOptions.tracingOptions, + sourceCpkInfo: { + sourceEncryptionKey: options.sourceCustomerProvidedKey?.encryptionKey, + sourceEncryptionAlgorithm: options.sourceCustomerProvidedKey?.encryptionAlgorithm, + sourceEncryptionKeySha256: options.sourceCustomerProvidedKey?.encryptionKeySha256 + } + } + ) + ); + } + ); } /** * Frees the specified pages from the page blob. @@ -71339,20 +102222,22 @@ var require_Clients = __commonJS({ */ async clearPages(offset = 0, count, options = {}) { options.conditions = options.conditions || {}; - return tracing_js_1.tracingClient.withSpan("PageBlobClient-clearPages", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.pageBlobContext.clearPages(0, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - range: (0, Range_js_1.rangeToString)({ offset, count }), - sequenceNumberAccessConditions: options.conditions, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - tracingOptions: updatedOptions.tracingOptions - })); + return import_tracing.tracingClient.withSpan("PageBlobClient-clearPages", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.pageBlobContext.clearPages(0, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + range: (0, import_Range.rangeToString)({ offset, count }), + sequenceNumberAccessConditions: options.conditions, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } /** @@ -71366,19 +102251,25 @@ var require_Clients = __commonJS({ */ async getPageRanges(offset = 0, count, options = {}) { options.conditions = options.conditions || {}; - return tracing_js_1.tracingClient.withSpan("PageBlobClient-getPageRanges", options, async (updatedOptions) => { - const response = (0, utils_common_js_1.assertResponse)(await this.pageBlobContext.getPageRanges({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - range: (0, Range_js_1.rangeToString)({ offset, count }), - tracingOptions: updatedOptions.tracingOptions - })); - return (0, PageBlobRangeResponse_js_1.rangeResponseFromModel)(response); - }); + return import_tracing.tracingClient.withSpan( + "PageBlobClient-getPageRanges", + options, + async (updatedOptions) => { + const response = (0, import_utils_common.assertResponse)( + await this.pageBlobContext.getPageRanges({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + range: (0, import_Range.rangeToString)({ offset, count }), + tracingOptions: updatedOptions.tracingOptions + }) + ); + return (0, import_PageBlobRangeResponse.rangeResponseFromModel)(response); + } + ); } /** * getPageRangesSegment returns a single segment of page ranges starting from the @@ -71393,20 +102284,26 @@ var require_Clients = __commonJS({ * @param options - Options to PageBlob Get Page Ranges Segment operation. */ async listPageRangesSegment(offset = 0, count, marker, options = {}) { - return tracing_js_1.tracingClient.withSpan("PageBlobClient-getPageRangesSegment", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.pageBlobContext.getPageRanges({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - range: (0, Range_js_1.rangeToString)({ offset, count }), - marker, - maxPageSize: options.maxPageSize, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "PageBlobClient-getPageRangesSegment", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.pageBlobContext.getPageRanges({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + range: (0, import_Range.rangeToString)({ offset, count }), + marker, + maxPageSize: options.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesResponseModel} @@ -71426,7 +102323,12 @@ var require_Clients = __commonJS({ let getPageRangeItemSegmentsResponse; if (!!marker || marker === void 0) { do { - getPageRangeItemSegmentsResponse = await this.listPageRangesSegment(offset, count, marker, options); + getPageRangeItemSegmentsResponse = await this.listPageRangesSegment( + offset, + count, + marker, + options + ); marker = getPageRangeItemSegmentsResponse.continuationToken; yield await getPageRangeItemSegmentsResponse; } while (marker); @@ -71441,8 +102343,13 @@ var require_Clients = __commonJS({ */ async *listPageRangeItems(offset = 0, count, options = {}) { let marker; - for await (const getPageRangesSegment of this.listPageRangeItemSegments(offset, count, marker, options)) { - yield* (0, utils_common_js_1.ExtractPageRangeInfoItems)(getPageRangesSegment); + for await (const getPageRangesSegment of this.listPageRangeItemSegments( + offset, + count, + marker, + options + )) { + yield* (0, import_utils_common.ExtractPageRangeInfoItems)(getPageRangesSegment); } } /** @@ -71556,20 +102463,26 @@ var require_Clients = __commonJS({ */ async getPageRangesDiff(offset, count, prevSnapshot, options = {}) { options.conditions = options.conditions || {}; - return tracing_js_1.tracingClient.withSpan("PageBlobClient-getPageRangesDiff", options, async (updatedOptions) => { - const result = (0, utils_common_js_1.assertResponse)(await this.pageBlobContext.getPageRangesDiff({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - prevsnapshot: prevSnapshot, - range: (0, Range_js_1.rangeToString)({ offset, count }), - tracingOptions: updatedOptions.tracingOptions - })); - return (0, PageBlobRangeResponse_js_1.rangeResponseFromModel)(result); - }); + return import_tracing.tracingClient.withSpan( + "PageBlobClient-getPageRangesDiff", + options, + async (updatedOptions) => { + const result = (0, import_utils_common.assertResponse)( + await this.pageBlobContext.getPageRangesDiff({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + prevsnapshot: prevSnapshot, + range: (0, import_Range.rangeToString)({ offset, count }), + tracingOptions: updatedOptions.tracingOptions + }) + ); + return (0, import_PageBlobRangeResponse.rangeResponseFromModel)(result); + } + ); } /** * getPageRangesDiffSegment returns a single segment of page ranges starting from the @@ -71586,24 +102499,30 @@ var require_Clients = __commonJS({ * @param options - Options to the Page Blob Get Page Ranges Diff operation. */ async listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker, options = {}) { - return tracing_js_1.tracingClient.withSpan("PageBlobClient-getPageRangesDiffSegment", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.pageBlobContext.getPageRangesDiff({ - abortSignal: options?.abortSignal, - leaseAccessConditions: options?.conditions, - modifiedAccessConditions: { - ...options?.conditions, - ifTags: options?.conditions?.tagConditions - }, - prevsnapshot: prevSnapshotOrUrl, - range: (0, Range_js_1.rangeToString)({ - offset, - count - }), - marker, - maxPageSize: options?.maxPageSize, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "PageBlobClient-getPageRangesDiffSegment", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.pageBlobContext.getPageRangesDiff({ + abortSignal: options?.abortSignal, + leaseAccessConditions: options?.conditions, + modifiedAccessConditions: { + ...options?.conditions, + ifTags: options?.conditions?.tagConditions + }, + prevsnapshot: prevSnapshotOrUrl, + range: (0, import_Range.rangeToString)({ + offset, + count + }), + marker, + maxPageSize: options?.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesDiffResponseModel} @@ -71625,7 +102544,13 @@ var require_Clients = __commonJS({ let getPageRangeItemSegmentsResponse; if (!!marker || marker === void 0) { do { - getPageRangeItemSegmentsResponse = await this.listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker, options); + getPageRangeItemSegmentsResponse = await this.listPageRangesDiffSegment( + offset, + count, + prevSnapshotOrUrl, + marker, + options + ); marker = getPageRangeItemSegmentsResponse.continuationToken; yield await getPageRangeItemSegmentsResponse; } while (marker); @@ -71641,8 +102566,14 @@ var require_Clients = __commonJS({ */ async *listPageRangeDiffItems(offset, count, prevSnapshotOrUrl, options) { let marker; - for await (const getPageRangesSegment of this.listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker, options)) { - yield* (0, utils_common_js_1.ExtractPageRangeInfoItems)(getPageRangesSegment); + for await (const getPageRangesSegment of this.listPageRangeDiffItemSegments( + offset, + count, + prevSnapshotOrUrl, + marker, + options + )) { + yield* (0, import_utils_common.ExtractPageRangeInfoItems)(getPageRangesSegment); } } /** @@ -71749,10 +102680,16 @@ var require_Clients = __commonJS({ * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { - return this.listPageRangeDiffItemSegments(offset, count, prevSnapshot, settings.continuationToken, { - maxPageSize: settings.maxPageSize, - ...options - }); + return this.listPageRangeDiffItemSegments( + offset, + count, + prevSnapshot, + settings.continuationToken, + { + maxPageSize: settings.maxPageSize, + ...options + } + ); } }; } @@ -71768,20 +102705,26 @@ var require_Clients = __commonJS({ */ async getPageRangesDiffForManagedDisks(offset, count, prevSnapshotUrl, options = {}) { options.conditions = options.conditions || {}; - return tracing_js_1.tracingClient.withSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options, async (updatedOptions) => { - const response = (0, utils_common_js_1.assertResponse)(await this.pageBlobContext.getPageRangesDiff({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - prevSnapshotUrl, - range: (0, Range_js_1.rangeToString)({ offset, count }), - tracingOptions: updatedOptions.tracingOptions - })); - return (0, PageBlobRangeResponse_js_1.rangeResponseFromModel)(response); - }); + return import_tracing.tracingClient.withSpan( + "PageBlobClient-GetPageRangesDiffForManagedDisks", + options, + async (updatedOptions) => { + const response = (0, import_utils_common.assertResponse)( + await this.pageBlobContext.getPageRangesDiff({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + prevSnapshotUrl, + range: (0, import_Range.rangeToString)({ offset, count }), + tracingOptions: updatedOptions.tracingOptions + }) + ); + return (0, import_PageBlobRangeResponse.rangeResponseFromModel)(response); + } + ); } /** * Resizes the page blob to the specified size (which must be a multiple of 512). @@ -71793,17 +102736,19 @@ var require_Clients = __commonJS({ */ async resize(size, options = {}) { options.conditions = options.conditions || {}; - return tracing_js_1.tracingClient.withSpan("PageBlobClient-resize", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.pageBlobContext.resize(size, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - encryptionScope: options.encryptionScope, - tracingOptions: updatedOptions.tracingOptions - })); + return import_tracing.tracingClient.withSpan("PageBlobClient-resize", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.pageBlobContext.resize(size, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } /** @@ -71817,18 +102762,24 @@ var require_Clients = __commonJS({ */ async updateSequenceNumber(sequenceNumberAction, sequenceNumber, options = {}) { options.conditions = options.conditions || {}; - return tracing_js_1.tracingClient.withSpan("PageBlobClient-updateSequenceNumber", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, { - abortSignal: options.abortSignal, - blobSequenceNumber: sequenceNumber, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "PageBlobClient-updateSequenceNumber", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, { + abortSignal: options.abortSignal, + blobSequenceNumber: sequenceNumber, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. @@ -71844,34 +102795,61 @@ var require_Clients = __commonJS({ * @returns Response data for the Page Blob Copy Incremental operation. */ async startCopyIncremental(copySource, options = {}) { - return tracing_js_1.tracingClient.withSpan("PageBlobClient-startCopyIncremental", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.pageBlobContext.copyIncremental(copySource, { - abortSignal: options.abortSignal, - modifiedAccessConditions: { - ...options.conditions, - ifTags: options.conditions?.tagConditions - }, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "PageBlobClient-startCopyIncremental", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.pageBlobContext.copyIncremental(copySource, { + abortSignal: options.abortSignal, + modifiedAccessConditions: { + ...options.conditions, + ifTags: options.conditions?.tagConditions + }, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } }; - exports2.PageBlobClient = PageBlobClient; } }); // node_modules/@azure/storage-blob/dist/commonjs/BatchUtils.js var require_BatchUtils = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/BatchUtils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getBodyAsText = getBodyAsText; - exports2.utf8ByteLength = utf8ByteLength; - var utils_js_1 = require_utils6(); - var constants_js_1 = require_constants10(); + "node_modules/@azure/storage-blob/dist/commonjs/BatchUtils.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BatchUtils_exports = {}; + __export2(BatchUtils_exports, { + getBodyAsText: () => getBodyAsText, + utf8ByteLength: () => utf8ByteLength + }); + module2.exports = __toCommonJS2(BatchUtils_exports); + var import_utils5 = require_utils7(); + var import_constants5 = require_constants11(); async function getBodyAsText(batchResponse) { - let buffer = Buffer.alloc(constants_js_1.BATCH_MAX_PAYLOAD_IN_BYTES); - const responseLength = await (0, utils_js_1.streamToBuffer2)(batchResponse.readableStreamBody, buffer); + let buffer = Buffer.alloc(import_constants5.BATCH_MAX_PAYLOAD_IN_BYTES); + const responseLength = await (0, import_utils5.streamToBuffer2)( + batchResponse.readableStreamBody, + buffer + ); buffer = buffer.slice(0, responseLength); return buffer.toString(); } @@ -71883,15 +102861,34 @@ var require_BatchUtils = __commonJS({ // node_modules/@azure/storage-blob/dist/commonjs/BatchResponseParser.js var require_BatchResponseParser = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/BatchResponseParser.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BatchResponseParser = void 0; - var core_rest_pipeline_1 = require_commonjs6(); - var core_http_compat_1 = require_commonjs9(); - var constants_js_1 = require_constants10(); - var BatchUtils_js_1 = require_BatchUtils(); - var log_js_1 = require_log5(); + "node_modules/@azure/storage-blob/dist/commonjs/BatchResponseParser.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BatchResponseParser_exports = {}; + __export2(BatchResponseParser_exports, { + BatchResponseParser: () => BatchResponseParser + }); + module2.exports = __toCommonJS2(BatchResponseParser_exports); + var import_core_rest_pipeline = require_commonjs6(); + var import_core_http_compat = require_commonjs9(); + var import_constants5 = require_constants11(); + var import_BatchUtils = require_BatchUtils(); + var import_log = require_log5(); var HTTP_HEADER_DELIMITER = ": "; var SPACE_DELIMITER = " "; var NOT_FOUND = -1; @@ -71911,15 +102908,17 @@ var require_BatchResponseParser = __commonJS({ this.batchResponse = batchResponse; this.subRequests = subRequests; this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; - this.perResponsePrefix = `--${this.responseBatchBoundary}${constants_js_1.HTTP_LINE_ENDING}`; + this.perResponsePrefix = `--${this.responseBatchBoundary}${import_constants5.HTTP_LINE_ENDING}`; this.batchResponseEnding = `--${this.responseBatchBoundary}--`; } // For example of response, please refer to https://learn.microsoft.com/rest/api/storageservices/blob-batch#response async parseBatchResponse() { - if (this.batchResponse._response.status !== constants_js_1.HTTPURLConnection.HTTP_ACCEPTED) { - throw new Error(`Invalid state: batch request failed with status: '${this.batchResponse._response.status}'.`); + if (this.batchResponse._response.status !== import_constants5.HTTPURLConnection.HTTP_ACCEPTED) { + throw new Error( + `Invalid state: batch request failed with status: '${this.batchResponse._response.status}'.` + ); } - const responseBodyAsText = await (0, BatchUtils_js_1.getBodyAsText)(this.batchResponse); + const responseBodyAsText = await (0, import_BatchUtils.getBodyAsText)(this.batchResponse); const subResponses = responseBodyAsText.split(this.batchResponseEnding)[0].split(this.perResponsePrefix).slice(1); const subResponseCount = subResponses.length; if (subResponseCount !== this.subRequests.size && subResponseCount !== 1) { @@ -71931,18 +102930,18 @@ var require_BatchResponseParser = __commonJS({ for (let index2 = 0; index2 < subResponseCount; index2++) { const subResponse = subResponses[index2]; const deserializedSubResponse = {}; - deserializedSubResponse.headers = (0, core_http_compat_1.toHttpHeadersLike)((0, core_rest_pipeline_1.createHttpHeaders)()); - const responseLines = subResponse.split(`${constants_js_1.HTTP_LINE_ENDING}`); + deserializedSubResponse.headers = (0, import_core_http_compat.toHttpHeadersLike)((0, import_core_rest_pipeline.createHttpHeaders)()); + const responseLines = subResponse.split(`${import_constants5.HTTP_LINE_ENDING}`); let subRespHeaderStartFound = false; let subRespHeaderEndFound = false; let subRespFailed = false; let contentId = NOT_FOUND; for (const responseLine of responseLines) { if (!subRespHeaderStartFound) { - if (responseLine.startsWith(constants_js_1.HeaderConstants.CONTENT_ID)) { + if (responseLine.startsWith(import_constants5.HeaderConstants.CONTENT_ID)) { contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); } - if (responseLine.startsWith(constants_js_1.HTTP_VERSION_1_1)) { + if (responseLine.startsWith(import_constants5.HTTP_VERSION_1_1)) { subRespHeaderStartFound = true; const tokens = responseLine.split(SPACE_DELIMITER); deserializedSubResponse.status = parseInt(tokens[1]); @@ -71958,11 +102957,13 @@ var require_BatchResponseParser = __commonJS({ } if (!subRespHeaderEndFound) { if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { - throw new Error(`Invalid state: find non-empty line '${responseLine}' without HTTP header delimiter '${HTTP_HEADER_DELIMITER}'.`); + throw new Error( + `Invalid state: find non-empty line '${responseLine}' without HTTP header delimiter '${HTTP_HEADER_DELIMITER}'.` + ); } const tokens = responseLine.split(HTTP_HEADER_DELIMITER); deserializedSubResponse.headers.set(tokens[0], tokens[1]); - if (tokens[0] === constants_js_1.HeaderConstants.X_MS_ERROR_CODE) { + if (tokens[0] === import_constants5.HeaderConstants.X_MS_ERROR_CODE) { deserializedSubResponse.errorCode = tokens[1]; subRespFailed = true; } @@ -71977,7 +102978,9 @@ var require_BatchResponseParser = __commonJS({ deserializedSubResponse._request = this.subRequests.get(contentId); deserializedSubResponses[contentId] = deserializedSubResponse; } else { - log_js_1.logger.error(`subResponses[${index2}] is dropped as the Content-ID is not found or invalid, Content-ID: ${contentId}`); + import_log.logger.error( + `subResponses[${index2}] is dropped as the Content-ID is not found or invalid, Content-ID: ${contentId}` + ); } if (subRespFailed) { subResponsesFailedCount++; @@ -71992,21 +102995,34 @@ var require_BatchResponseParser = __commonJS({ }; } }; - exports2.BatchResponseParser = BatchResponseParser; } }); // node_modules/@azure/storage-blob/dist/commonjs/utils/Mutex.js var require_Mutex = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/utils/Mutex.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Mutex = void 0; - var MutexLockStatus; - (function(MutexLockStatus2) { - MutexLockStatus2[MutexLockStatus2["LOCKED"] = 0] = "LOCKED"; - MutexLockStatus2[MutexLockStatus2["UNLOCKED"] = 1] = "UNLOCKED"; - })(MutexLockStatus || (MutexLockStatus = {})); + "node_modules/@azure/storage-blob/dist/commonjs/utils/Mutex.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var Mutex_exports = {}; + __export2(Mutex_exports, { + Mutex: () => Mutex + }); + module2.exports = __toCommonJS2(Mutex_exports); var Mutex = class { /** * Lock for a specific key. If the lock has been acquired by another customer, then @@ -72015,14 +103031,14 @@ var require_Mutex = __commonJS({ * @param key - lock key */ static async lock(key) { - return new Promise((resolve14) => { - if (this.keys[key] === void 0 || this.keys[key] === MutexLockStatus.UNLOCKED) { - this.keys[key] = MutexLockStatus.LOCKED; - resolve14(); + return new Promise((resolve15) => { + if (this.keys[key] === void 0 || this.keys[key] === 1) { + this.keys[key] = 0; + resolve15(); } else { this.onUnlockEvent(key, () => { - this.keys[key] = MutexLockStatus.LOCKED; - resolve14(); + this.keys[key] = 0; + resolve15(); }); } }); @@ -72033,12 +103049,12 @@ var require_Mutex = __commonJS({ * @param key - */ static async unlock(key) { - return new Promise((resolve14) => { - if (this.keys[key] === MutexLockStatus.LOCKED) { + return new Promise((resolve15) => { + if (this.keys[key] === 0) { this.emitUnlockEvent(key); } delete this.keys[key]; - resolve14(); + resolve15(); }); } static keys = {}; @@ -72059,31 +103075,47 @@ var require_Mutex = __commonJS({ } } }; - exports2.Mutex = Mutex; } }); // node_modules/@azure/storage-blob/dist/commonjs/BlobBatch.js var require_BlobBatch = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/BlobBatch.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BlobBatch = void 0; - var core_util_1 = require_commonjs4(); - var core_auth_1 = require_commonjs7(); - var core_rest_pipeline_1 = require_commonjs6(); - var core_util_2 = require_commonjs4(); - var AnonymousCredential_js_1 = require_AnonymousCredential(); - var Clients_js_1 = require_Clients(); - var Mutex_js_1 = require_Mutex(); - var Pipeline_js_1 = require_Pipeline(); - var utils_common_js_1 = require_utils_common(); - var core_xml_1 = require_commonjs10(); - var constants_js_1 = require_constants10(); - var StorageSharedKeyCredential_js_1 = require_StorageSharedKeyCredential(); - var tracing_js_1 = require_tracing(); - var core_client_1 = require_commonjs8(); - var StorageSharedKeyCredentialPolicyV2_js_1 = require_StorageSharedKeyCredentialPolicyV22(); + "node_modules/@azure/storage-blob/dist/commonjs/BlobBatch.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BlobBatch_exports = {}; + __export2(BlobBatch_exports, { + BlobBatch: () => BlobBatch + }); + module2.exports = __toCommonJS2(BlobBatch_exports); + var import_core_util = require_commonjs4(); + var import_core_auth = require_commonjs7(); + var import_core_rest_pipeline = require_commonjs6(); + var import_core_util2 = require_commonjs4(); + var import_storage_common = require_commonjs12(); + var import_Clients = require_Clients(); + var import_Mutex = require_Mutex(); + var import_Pipeline = require_Pipeline(); + var import_utils_common = require_utils_common2(); + var import_core_xml = require_commonjs10(); + var import_constants5 = require_constants11(); + var import_tracing = require_tracing(); + var import_core_client = require_commonjs8(); var BlobBatch = class { batchRequest; batch = "batch"; @@ -72112,13 +103144,13 @@ var require_BlobBatch = __commonJS({ return this.batchRequest.getSubRequests(); } async addSubRequestInternal(subRequest, assembleSubRequestFunc) { - await Mutex_js_1.Mutex.lock(this.batch); + await import_Mutex.Mutex.lock(this.batch); try { this.batchRequest.preAddSubRequest(subRequest); await assembleSubRequestFunc(); this.batchRequest.postAddSubRequest(subRequest); } finally { - await Mutex_js_1.Mutex.unlock(this.batch); + await import_Mutex.Mutex.unlock(this.batch); } } setBatchType(batchType) { @@ -72126,66 +103158,90 @@ var require_BlobBatch = __commonJS({ this.batchType = batchType; } if (this.batchType !== batchType) { - throw new RangeError(`BlobBatch only supports one operation type per batch and it already is being used for ${this.batchType} operations.`); + throw new RangeError( + `BlobBatch only supports one operation type per batch and it already is being used for ${this.batchType} operations.` + ); } } async deleteBlob(urlOrBlobClient, credentialOrOptions, options) { let url2; let credential; - if (typeof urlOrBlobClient === "string" && (core_util_2.isNodeLike && credentialOrOptions instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential || credentialOrOptions instanceof AnonymousCredential_js_1.AnonymousCredential || (0, core_auth_1.isTokenCredential)(credentialOrOptions))) { + if (typeof urlOrBlobClient === "string" && (import_core_util2.isNodeLike && credentialOrOptions instanceof import_storage_common.StorageSharedKeyCredential || credentialOrOptions instanceof import_storage_common.AnonymousCredential || (0, import_core_auth.isTokenCredential)(credentialOrOptions))) { url2 = urlOrBlobClient; credential = credentialOrOptions; - } else if (urlOrBlobClient instanceof Clients_js_1.BlobClient) { + } else if (urlOrBlobClient instanceof import_Clients.BlobClient) { url2 = urlOrBlobClient.url; credential = urlOrBlobClient.credential; options = credentialOrOptions; } else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + throw new RangeError( + "Invalid arguments. Either url and credential, or BlobClient need be provided." + ); } if (!options) { options = {}; } - return tracing_js_1.tracingClient.withSpan("BatchDeleteRequest-addSubRequest", options, async (updatedOptions) => { - this.setBatchType("delete"); - await this.addSubRequestInternal({ - url: url2, - credential - }, async () => { - await new Clients_js_1.BlobClient(url2, this.batchRequest.createPipeline(credential)).delete(updatedOptions); - }); - }); + return import_tracing.tracingClient.withSpan( + "BatchDeleteRequest-addSubRequest", + options, + async (updatedOptions) => { + this.setBatchType("delete"); + await this.addSubRequestInternal( + { + url: url2, + credential + }, + async () => { + await new import_Clients.BlobClient(url2, this.batchRequest.createPipeline(credential)).delete( + updatedOptions + ); + } + ); + } + ); } async setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options) { let url2; let credential; let tier; - if (typeof urlOrBlobClient === "string" && (core_util_2.isNodeLike && credentialOrTier instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential || credentialOrTier instanceof AnonymousCredential_js_1.AnonymousCredential || (0, core_auth_1.isTokenCredential)(credentialOrTier))) { + if (typeof urlOrBlobClient === "string" && (import_core_util2.isNodeLike && credentialOrTier instanceof import_storage_common.StorageSharedKeyCredential || credentialOrTier instanceof import_storage_common.AnonymousCredential || (0, import_core_auth.isTokenCredential)(credentialOrTier))) { url2 = urlOrBlobClient; credential = credentialOrTier; tier = tierOrOptions; - } else if (urlOrBlobClient instanceof Clients_js_1.BlobClient) { + } else if (urlOrBlobClient instanceof import_Clients.BlobClient) { url2 = urlOrBlobClient.url; credential = urlOrBlobClient.credential; tier = credentialOrTier; options = tierOrOptions; } else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + throw new RangeError( + "Invalid arguments. Either url and credential, or BlobClient need be provided." + ); } if (!options) { options = {}; } - return tracing_js_1.tracingClient.withSpan("BatchSetTierRequest-addSubRequest", options, async (updatedOptions) => { - this.setBatchType("setAccessTier"); - await this.addSubRequestInternal({ - url: url2, - credential - }, async () => { - await new Clients_js_1.BlobClient(url2, this.batchRequest.createPipeline(credential)).setAccessTier(tier, updatedOptions); - }); - }); + return import_tracing.tracingClient.withSpan( + "BatchSetTierRequest-addSubRequest", + options, + async (updatedOptions) => { + this.setBatchType("setAccessTier"); + await this.addSubRequestInternal( + { + url: url2, + credential + }, + async () => { + await new import_Clients.BlobClient(url2, this.batchRequest.createPipeline(credential)).setAccessTier( + tier, + updatedOptions + ); + } + ); + } + ); } }; - exports2.BlobBatch = BlobBatch; var InnerBatchRequest = class { operationCount; body; @@ -72197,9 +103253,9 @@ var require_BlobBatch = __commonJS({ constructor() { this.operationCount = 0; this.body = ""; - const tempGuid = (0, core_util_1.randomUUID)(); + const tempGuid = (0, import_core_util.randomUUID)(); this.boundary = `batch_${tempGuid}`; - this.subRequestPrefix = `--${this.boundary}${constants_js_1.HTTP_LINE_ENDING}${constants_js_1.HeaderConstants.CONTENT_TYPE}: application/http${constants_js_1.HTTP_LINE_ENDING}${constants_js_1.HeaderConstants.CONTENT_TRANSFER_ENCODING}: binary`; + this.subRequestPrefix = `--${this.boundary}${import_constants5.HTTP_LINE_ENDING}${import_constants5.HeaderConstants.CONTENT_TYPE}: application/http${import_constants5.HTTP_LINE_ENDING}${import_constants5.HeaderConstants.CONTENT_TRANSFER_ENCODING}: binary`; this.multipartContentType = `multipart/mixed; boundary=${this.boundary}`; this.batchRequestEnding = `--${this.boundary}--`; this.subRequests = /* @__PURE__ */ new Map(); @@ -72212,30 +103268,39 @@ var require_BlobBatch = __commonJS({ * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. */ createPipeline(credential) { - const corePipeline = (0, core_rest_pipeline_1.createEmptyPipeline)(); - corePipeline.addPolicy((0, core_client_1.serializationPolicy)({ - stringifyXML: core_xml_1.stringifyXML, - serializerOptions: { - xml: { - xmlCharKey: "#" + const corePipeline = (0, import_core_rest_pipeline.createEmptyPipeline)(); + corePipeline.addPolicy( + (0, import_core_client.serializationPolicy)({ + stringifyXML: import_core_xml.stringifyXML, + serializerOptions: { + xml: { + xmlCharKey: "#" + } } - } - }), { phase: "Serialize" }); + }), + { phase: "Serialize" } + ); corePipeline.addPolicy(batchHeaderFilterPolicy()); corePipeline.addPolicy(batchRequestAssemblePolicy(this), { afterPhase: "Sign" }); - if ((0, core_auth_1.isTokenCredential)(credential)) { - corePipeline.addPolicy((0, core_rest_pipeline_1.bearerTokenAuthenticationPolicy)({ - credential, - scopes: constants_js_1.StorageOAuthScopes, - challengeCallbacks: { authorizeRequestOnChallenge: core_client_1.authorizeRequestOnTenantChallenge } - }), { phase: "Sign" }); - } else if (credential instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential) { - corePipeline.addPolicy((0, StorageSharedKeyCredentialPolicyV2_js_1.storageSharedKeyCredentialPolicy)({ - accountName: credential.accountName, - accountKey: credential.accountKey - }), { phase: "Sign" }); - } - const pipeline2 = new Pipeline_js_1.Pipeline([]); + if ((0, import_core_auth.isTokenCredential)(credential)) { + corePipeline.addPolicy( + (0, import_core_rest_pipeline.bearerTokenAuthenticationPolicy)({ + credential, + scopes: import_constants5.StorageOAuthScopes, + challengeCallbacks: { authorizeRequestOnChallenge: import_core_client.authorizeRequestOnTenantChallenge } + }), + { phase: "Sign" } + ); + } else if (credential instanceof import_storage_common.StorageSharedKeyCredential) { + corePipeline.addPolicy( + (0, import_storage_common.storageSharedKeyCredentialPolicy)({ + accountName: credential.accountName, + accountKey: credential.accountKey + }), + { phase: "Sign" } + ); + } + const pipeline2 = new import_Pipeline.Pipeline([]); pipeline2._credential = credential; pipeline2._corePipeline = corePipeline; return pipeline2; @@ -72244,23 +103309,25 @@ var require_BlobBatch = __commonJS({ this.body += [ this.subRequestPrefix, // sub request constant prefix - `${constants_js_1.HeaderConstants.CONTENT_ID}: ${this.operationCount}`, + `${import_constants5.HeaderConstants.CONTENT_ID}: ${this.operationCount}`, // sub request's content ID "", // empty line after sub request's content ID - `${request3.method.toString()} ${(0, utils_common_js_1.getURLPathAndQuery)(request3.url)} ${constants_js_1.HTTP_VERSION_1_1}${constants_js_1.HTTP_LINE_ENDING}` + `${request3.method.toString()} ${(0, import_utils_common.getURLPathAndQuery)( + request3.url + )} ${import_constants5.HTTP_VERSION_1_1}${import_constants5.HTTP_LINE_ENDING}` // sub request start line with method - ].join(constants_js_1.HTTP_LINE_ENDING); + ].join(import_constants5.HTTP_LINE_ENDING); for (const [name, value] of request3.headers) { - this.body += `${name}: ${value}${constants_js_1.HTTP_LINE_ENDING}`; + this.body += `${name}: ${value}${import_constants5.HTTP_LINE_ENDING}`; } - this.body += constants_js_1.HTTP_LINE_ENDING; + this.body += import_constants5.HTTP_LINE_ENDING; } preAddSubRequest(subRequest) { - if (this.operationCount >= constants_js_1.BATCH_MAX_REQUEST) { - throw new RangeError(`Cannot exceed ${constants_js_1.BATCH_MAX_REQUEST} sub requests in a single batch`); + if (this.operationCount >= import_constants5.BATCH_MAX_REQUEST) { + throw new RangeError(`Cannot exceed ${import_constants5.BATCH_MAX_REQUEST} sub requests in a single batch`); } - const path30 = (0, utils_common_js_1.getURLPath)(subRequest.url); + const path30 = (0, import_utils_common.getURLPath)(subRequest.url); if (!path30 || path30 === "") { throw new RangeError(`Invalid url for sub request: '${subRequest.url}'`); } @@ -72271,7 +103338,7 @@ var require_BlobBatch = __commonJS({ } // Return the http request body with assembling the ending line to the sub request body. getHttpRequestBody() { - return `${this.body}${this.batchRequestEnding}${constants_js_1.HTTP_LINE_ENDING}`; + return `${this.body}${this.batchRequestEnding}${import_constants5.HTTP_LINE_ENDING}`; } getMultipartContentType() { return this.multipartContentType; @@ -72288,7 +103355,7 @@ var require_BlobBatch = __commonJS({ return { request: request3, status: 200, - headers: (0, core_rest_pipeline_1.createHttpHeaders)() + headers: (0, import_core_rest_pipeline.createHttpHeaders)() }; } }; @@ -72299,7 +103366,7 @@ var require_BlobBatch = __commonJS({ async sendRequest(request3, next) { let xMsHeaderName = ""; for (const [name] of request3.headers) { - if ((0, utils_common_js_1.iEqual)(name, constants_js_1.HeaderConstants.X_MS_VERSION)) { + if ((0, import_utils_common.iEqual)(name, import_constants5.HeaderConstants.X_MS_VERSION)) { xMsHeaderName = name; } } @@ -72315,31 +103382,50 @@ var require_BlobBatch = __commonJS({ // node_modules/@azure/storage-blob/dist/commonjs/BlobBatchClient.js var require_BlobBatchClient = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/BlobBatchClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BlobBatchClient = void 0; - var BatchResponseParser_js_1 = require_BatchResponseParser(); - var BatchUtils_js_1 = require_BatchUtils(); - var BlobBatch_js_1 = require_BlobBatch(); - var tracing_js_1 = require_tracing(); - var AnonymousCredential_js_1 = require_AnonymousCredential(); - var StorageContextClient_js_1 = require_StorageContextClient(); - var Pipeline_js_1 = require_Pipeline(); - var utils_common_js_1 = require_utils_common(); + "node_modules/@azure/storage-blob/dist/commonjs/BlobBatchClient.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BlobBatchClient_exports = {}; + __export2(BlobBatchClient_exports, { + BlobBatchClient: () => BlobBatchClient + }); + module2.exports = __toCommonJS2(BlobBatchClient_exports); + var import_BatchResponseParser = require_BatchResponseParser(); + var import_BatchUtils = require_BatchUtils(); + var import_BlobBatch = require_BlobBatch(); + var import_tracing = require_tracing(); + var import_storage_common = require_commonjs12(); + var import_StorageContextClient = require_StorageContextClient(); + var import_Pipeline = require_Pipeline(); + var import_utils_common = require_utils_common2(); var BlobBatchClient = class { serviceOrContainerContext; constructor(url2, credentialOrPipeline, options) { let pipeline2; - if ((0, Pipeline_js_1.isPipelineLike)(credentialOrPipeline)) { + if ((0, import_Pipeline.isPipelineLike)(credentialOrPipeline)) { pipeline2 = credentialOrPipeline; } else if (!credentialOrPipeline) { - pipeline2 = (0, Pipeline_js_1.newPipeline)(new AnonymousCredential_js_1.AnonymousCredential(), options); + pipeline2 = (0, import_Pipeline.newPipeline)(new import_storage_common.AnonymousCredential(), options); } else { - pipeline2 = (0, Pipeline_js_1.newPipeline)(credentialOrPipeline, options); + pipeline2 = (0, import_Pipeline.newPipeline)(credentialOrPipeline, options); } - const storageClientContext = new StorageContextClient_js_1.StorageContextClient(url2, (0, Pipeline_js_1.getCoreClientOptions)(pipeline2)); - const path30 = (0, utils_common_js_1.getURLPath)(url2); + const storageClientContext = new import_StorageContextClient.StorageContextClient(url2, (0, import_Pipeline.getCoreClientOptions)(pipeline2)); + const path30 = (0, import_utils_common.getURLPath)(url2); if (path30 && path30 !== "/") { this.serviceOrContainerContext = storageClientContext.container; } else { @@ -72351,10 +103437,10 @@ var require_BlobBatchClient = __commonJS({ * A BlobBatch represents an aggregated set of operations on blobs. */ createBatch() { - return new BlobBatch_js_1.BlobBatch(); + return new import_BlobBatch.BlobBatch(); } async deleteBlobs(urlsOrBlobClients, credentialOrOptions, options) { - const batch = new BlobBatch_js_1.BlobBatch(); + const batch = new import_BlobBatch.BlobBatch(); for (const urlOrBlobClient of urlsOrBlobClients) { if (typeof urlOrBlobClient === "string") { await batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options); @@ -72365,12 +103451,21 @@ var require_BlobBatchClient = __commonJS({ return this.submitBatch(batch); } async setBlobsAccessTier(urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { - const batch = new BlobBatch_js_1.BlobBatch(); + const batch = new import_BlobBatch.BlobBatch(); for (const urlOrBlobClient of urlsOrBlobClients) { if (typeof urlOrBlobClient === "string") { - await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options); + await batch.setBlobAccessTier( + urlOrBlobClient, + credentialOrTier, + tierOrOptions, + options + ); } else { - await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions); + await batch.setBlobAccessTier( + urlOrBlobClient, + credentialOrTier, + tierOrOptions + ); } } return this.submitBatch(batch); @@ -72443,57 +103538,128 @@ var require_BlobBatchClient = __commonJS({ if (!batchRequest || batchRequest.getSubRequests().size === 0) { throw new RangeError("Batch request should contain one or more sub requests."); } - return tracing_js_1.tracingClient.withSpan("BlobBatchClient-submitBatch", options, async (updatedOptions) => { - const batchRequestBody = batchRequest.getHttpRequestBody(); - const rawBatchResponse = (0, utils_common_js_1.assertResponse)(await this.serviceOrContainerContext.submitBatch((0, BatchUtils_js_1.utf8ByteLength)(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, { - ...updatedOptions - })); - const batchResponseParser = new BatchResponseParser_js_1.BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); - const responseSummary = await batchResponseParser.parseBatchResponse(); - const res = { - _response: rawBatchResponse._response, - contentType: rawBatchResponse.contentType, - errorCode: rawBatchResponse.errorCode, - requestId: rawBatchResponse.requestId, - clientRequestId: rawBatchResponse.clientRequestId, - version: rawBatchResponse.version, - subResponses: responseSummary.subResponses, - subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, - subResponsesFailedCount: responseSummary.subResponsesFailedCount - }; - return res; - }); + return import_tracing.tracingClient.withSpan( + "BlobBatchClient-submitBatch", + options, + async (updatedOptions) => { + const batchRequestBody = batchRequest.getHttpRequestBody(); + const rawBatchResponse = (0, import_utils_common.assertResponse)( + await this.serviceOrContainerContext.submitBatch( + (0, import_BatchUtils.utf8ByteLength)(batchRequestBody), + batchRequest.getMultiPartContentType(), + batchRequestBody, + { + ...updatedOptions + } + ) + ); + const batchResponseParser = new import_BatchResponseParser.BatchResponseParser( + rawBatchResponse, + batchRequest.getSubRequests() + ); + const responseSummary = await batchResponseParser.parseBatchResponse(); + const res = { + _response: rawBatchResponse._response, + contentType: rawBatchResponse.contentType, + errorCode: rawBatchResponse.errorCode, + requestId: rawBatchResponse.requestId, + clientRequestId: rawBatchResponse.clientRequestId, + version: rawBatchResponse.version, + subResponses: responseSummary.subResponses, + subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, + subResponsesFailedCount: responseSummary.subResponsesFailedCount + }; + return res; + } + ); } }; - exports2.BlobBatchClient = BlobBatchClient; } }); // node_modules/@azure/storage-blob/dist/commonjs/ContainerClient.js var require_ContainerClient = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/ContainerClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ContainerClient = void 0; - var core_rest_pipeline_1 = require_commonjs6(); - var core_util_1 = require_commonjs4(); - var core_auth_1 = require_commonjs7(); - var AnonymousCredential_js_1 = require_AnonymousCredential(); - var StorageSharedKeyCredential_js_1 = require_StorageSharedKeyCredential(); - var Pipeline_js_1 = require_Pipeline(); - var StorageClient_js_1 = require_StorageClient(); - var tracing_js_1 = require_tracing(); - var utils_common_js_1 = require_utils_common(); - var BlobSASSignatureValues_js_1 = require_BlobSASSignatureValues(); - var BlobLeaseClient_js_1 = require_BlobLeaseClient(); - var Clients_js_1 = require_Clients(); - var BlobBatchClient_js_1 = require_BlobBatchClient(); - var ContainerClient = class extends StorageClient_js_1.StorageClient { + "node_modules/@azure/storage-blob/dist/commonjs/ContainerClient.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var ContainerClient_exports = {}; + __export2(ContainerClient_exports, { + ContainerClient: () => ContainerClient + }); + module2.exports = __toCommonJS2(ContainerClient_exports); + var import_core_rest_pipeline = require_commonjs6(); + var import_core_util = require_commonjs4(); + var import_core_auth = require_commonjs7(); + var import_storage_common = require_commonjs12(); + var import_Pipeline = require_Pipeline(); + var import_StorageClient = require_StorageClient(); + var import_tracing = require_tracing(); + var import_utils_common = require_utils_common2(); + var import_blobListArrowParser = require_blobListArrowParser(); + var import_blobListXmlParser = require_blobListXmlParser(); + var import_constants5 = require_constants11(); + var import_BlobSASSignatureValues = require_BlobSASSignatureValues(); + var import_BlobLeaseClient = require_BlobLeaseClient(); + var import_Clients = require_Clients(); + var import_BlobBatchClient = require_BlobBatchClient(); + function mapBlobItemInternal(blobItemInternal) { + const blobItem = { + ...blobItemInternal, + name: (0, import_utils_common.BlobNameToString)(blobItemInternal.name), + tags: (0, import_utils_common.toTags)(blobItemInternal.blobTags), + objectReplicationSourceProperties: (0, import_utils_common.parseObjectReplicationRecord)( + blobItemInternal.objectReplicationMetadata + ) + }; + return blobItem; + } + function mapBlobPrefixInternal(blobPrefixInternal) { + const blobPrefix = { + ...blobPrefixInternal, + name: (0, import_utils_common.BlobNameToString)(blobPrefixInternal.name) + }; + return blobPrefix; + } + function isApacheArrow(contentType) { + return (contentType ?? "").split(";")[0].trim().toLowerCase() === import_constants5.ApacheArrowContentType; + } + function withListSegmentResponseMetadata(base, rawResponse, parsedBody, bodyAsText = "") { + return { + ...base, + clientRequestId: rawResponse.clientRequestId, + requestId: rawResponse.requestId, + version: rawResponse.version, + date: rawResponse.date, + contentType: rawResponse.contentType, + _response: { + ...rawResponse._response, + bodyAsText, + parsedBody + } + }; + } + var ContainerClient = class extends import_StorageClient.StorageClient { /** * containerContext provided by protocol layer. */ containerContext; _containerName; + blobClientConfig; /** * The name of the container. */ @@ -72504,34 +103670,39 @@ var require_ContainerClient = __commonJS({ let pipeline2; let url2; options = options || {}; - if ((0, Pipeline_js_1.isPipelineLike)(credentialOrPipelineOrContainerName)) { + if ((0, import_Pipeline.isPipelineLike)(credentialOrPipelineOrContainerName)) { url2 = urlOrConnectionString; pipeline2 = credentialOrPipelineOrContainerName; - } else if (core_util_1.isNodeLike && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential_js_1.AnonymousCredential || (0, core_auth_1.isTokenCredential)(credentialOrPipelineOrContainerName)) { + } else if (import_core_util.isNodeLike && credentialOrPipelineOrContainerName instanceof import_storage_common.StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof import_storage_common.AnonymousCredential || (0, import_core_auth.isTokenCredential)(credentialOrPipelineOrContainerName)) { url2 = urlOrConnectionString; - pipeline2 = (0, Pipeline_js_1.newPipeline)(credentialOrPipelineOrContainerName, options); + pipeline2 = (0, import_Pipeline.newPipeline)(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { url2 = urlOrConnectionString; - pipeline2 = (0, Pipeline_js_1.newPipeline)(new AnonymousCredential_js_1.AnonymousCredential(), options); + pipeline2 = (0, import_Pipeline.newPipeline)(new import_storage_common.AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string") { const containerName = credentialOrPipelineOrContainerName; - const extractedCreds = (0, utils_common_js_1.extractConnectionStringParts)(urlOrConnectionString); + const extractedCreds = (0, import_utils_common.extractConnectionStringParts)(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { - if (core_util_1.isNodeLike) { - const sharedKeyCredential = new StorageSharedKeyCredential_js_1.StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url2 = (0, utils_common_js_1.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)); + if (import_core_util.isNodeLike) { + const sharedKeyCredential = new import_storage_common.StorageSharedKeyCredential( + extractedCreds.accountName, + extractedCreds.accountKey + ); + url2 = (0, import_utils_common.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)); if (!options.proxyOptions) { - options.proxyOptions = (0, core_rest_pipeline_1.getDefaultProxySettings)(extractedCreds.proxyUri); + options.proxyOptions = (0, import_core_rest_pipeline.getDefaultProxySettings)(extractedCreds.proxyUri); } - pipeline2 = (0, Pipeline_js_1.newPipeline)(sharedKeyCredential, options); + pipeline2 = (0, import_Pipeline.newPipeline)(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } else if (extractedCreds.kind === "SASConnString") { - url2 = (0, utils_common_js_1.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)) + "?" + extractedCreds.accountSas; - pipeline2 = (0, Pipeline_js_1.newPipeline)(new AnonymousCredential_js_1.AnonymousCredential(), options); + url2 = (0, import_utils_common.appendToURLPath)(extractedCreds.url, encodeURIComponent(containerName)) + "?" + extractedCreds.accountSas; + pipeline2 = (0, import_Pipeline.newPipeline)(new import_storage_common.AnonymousCredential(), options); } else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + throw new Error( + "Connection string must be either an Account connection string or a SAS connection string" + ); } } else { throw new Error("Expecting non-empty strings for containerName parameter"); @@ -72539,6 +103710,7 @@ var require_ContainerClient = __commonJS({ super(url2, pipeline2); this._containerName = this.getContainerNameFromUrl(); this.containerContext = this.storageClientContext.container; + this.blobClientConfig = options; } /** * Creates a new container under the specified account. If the container with @@ -72568,8 +103740,10 @@ var require_ContainerClient = __commonJS({ * ``` */ async create(options = {}) { - return tracing_js_1.tracingClient.withSpan("ContainerClient-create", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.containerContext.create(updatedOptions)); + return import_tracing.tracingClient.withSpan("ContainerClient-create", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.containerContext.create(updatedOptions) + ); }); } /** @@ -72581,27 +103755,31 @@ var require_ContainerClient = __commonJS({ * @param options - */ async createIfNotExists(options = {}) { - return tracing_js_1.tracingClient.withSpan("ContainerClient-createIfNotExists", options, async (updatedOptions) => { - try { - const res = await this.create(updatedOptions); - return { - succeeded: true, - ...res, - _response: res._response - // _response is made non-enumerable - }; - } catch (e) { - if (e.details?.errorCode === "ContainerAlreadyExists") { + return import_tracing.tracingClient.withSpan( + "ContainerClient-createIfNotExists", + options, + async (updatedOptions) => { + try { + const res = await this.create(updatedOptions); return { - succeeded: false, - ...e.response?.parsedHeaders, - _response: e.response + succeeded: true, + ...res, + _response: res._response + // _response is made non-enumerable }; - } else { - throw e; + } catch (e) { + if (e.details?.errorCode === "ContainerAlreadyExists") { + return { + succeeded: false, + ...e.response?.parsedHeaders, + _response: e.response + }; + } else { + throw e; + } } } - }); + ); } /** * Returns true if the Azure container resource represented by this client exists; false otherwise. @@ -72613,7 +103791,7 @@ var require_ContainerClient = __commonJS({ * @param options - */ async exists(options = {}) { - return tracing_js_1.tracingClient.withSpan("ContainerClient-exists", options, async (updatedOptions) => { + return import_tracing.tracingClient.withSpan("ContainerClient-exists", options, async (updatedOptions) => { try { await this.getProperties({ abortSignal: options.abortSignal, @@ -72635,7 +103813,11 @@ var require_ContainerClient = __commonJS({ * @returns A new BlobClient object for the given blob name. */ getBlobClient(blobName) { - return new Clients_js_1.BlobClient((0, utils_common_js_1.appendToURLPath)(this.url, (0, utils_common_js_1.EscapePath)(blobName)), this.pipeline); + return new import_Clients.BlobClient( + (0, import_utils_common.appendToURLPath)(this.url, (0, import_utils_common.EscapePath)(blobName)), + this.pipeline, + this.blobClientConfig + ); } /** * Creates an {@link AppendBlobClient} @@ -72643,7 +103825,11 @@ var require_ContainerClient = __commonJS({ * @param blobName - An append blob name */ getAppendBlobClient(blobName) { - return new Clients_js_1.AppendBlobClient((0, utils_common_js_1.appendToURLPath)(this.url, (0, utils_common_js_1.EscapePath)(blobName)), this.pipeline); + return new import_Clients.AppendBlobClient( + (0, import_utils_common.appendToURLPath)(this.url, (0, import_utils_common.EscapePath)(blobName)), + this.pipeline, + this.blobClientConfig + ); } /** * Creates a {@link BlockBlobClient} @@ -72673,7 +103859,11 @@ var require_ContainerClient = __commonJS({ * ``` */ getBlockBlobClient(blobName) { - return new Clients_js_1.BlockBlobClient((0, utils_common_js_1.appendToURLPath)(this.url, (0, utils_common_js_1.EscapePath)(blobName)), this.pipeline); + return new import_Clients.BlockBlobClient( + (0, import_utils_common.appendToURLPath)(this.url, (0, import_utils_common.EscapePath)(blobName)), + this.pipeline, + this.blobClientConfig + ); } /** * Creates a {@link PageBlobClient} @@ -72681,7 +103871,11 @@ var require_ContainerClient = __commonJS({ * @param blobName - A page blob name */ getPageBlobClient(blobName) { - return new Clients_js_1.PageBlobClient((0, utils_common_js_1.appendToURLPath)(this.url, (0, utils_common_js_1.EscapePath)(blobName)), this.pipeline); + return new import_Clients.PageBlobClient( + (0, import_utils_common.appendToURLPath)(this.url, (0, import_utils_common.EscapePath)(blobName)), + this.pipeline, + this.blobClientConfig + ); } /** * Returns all user-defined metadata and system properties for the specified @@ -72699,13 +103893,19 @@ var require_ContainerClient = __commonJS({ if (!options.conditions) { options.conditions = {}; } - return tracing_js_1.tracingClient.withSpan("ContainerClient-getProperties", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.containerContext.getProperties({ - abortSignal: options.abortSignal, - ...options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "ContainerClient-getProperties", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.containerContext.getProperties({ + abortSignal: options.abortSignal, + ...options.conditions, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * Marks the specified container for deletion. The container and any blobs @@ -72718,13 +103918,15 @@ var require_ContainerClient = __commonJS({ if (!options.conditions) { options.conditions = {}; } - return tracing_js_1.tracingClient.withSpan("ContainerClient-delete", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.containerContext.delete({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); + return import_tracing.tracingClient.withSpan("ContainerClient-delete", options, async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.containerContext.delete({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions + }) + ); }); } /** @@ -72735,25 +103937,29 @@ var require_ContainerClient = __commonJS({ * @param options - Options to Container Delete operation. */ async deleteIfExists(options = {}) { - return tracing_js_1.tracingClient.withSpan("ContainerClient-deleteIfExists", options, async (updatedOptions) => { - try { - const res = await this.delete(updatedOptions); - return { - succeeded: true, - ...res, - _response: res._response - }; - } catch (e) { - if (e.details?.errorCode === "ContainerNotFound") { + return import_tracing.tracingClient.withSpan( + "ContainerClient-deleteIfExists", + options, + async (updatedOptions) => { + try { + const res = await this.delete(updatedOptions); return { - succeeded: false, - ...e.response?.parsedHeaders, - _response: e.response + succeeded: true, + ...res, + _response: res._response }; + } catch (e) { + if (e.details?.errorCode === "ContainerNotFound") { + return { + succeeded: false, + ...e.response?.parsedHeaders, + _response: e.response + }; + } + throw e; } - throw e; } - }); + ); } /** * Sets one or more user-defined name-value pairs for the specified container. @@ -72772,17 +103978,25 @@ var require_ContainerClient = __commonJS({ options.conditions = {}; } if (options.conditions.ifUnmodifiedSince) { - throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); + throw new RangeError( + "the IfUnmodifiedSince must have their default values because they are ignored by the blob service" + ); } - return tracing_js_1.tracingClient.withSpan("ContainerClient-setMetadata", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.containerContext.setMetadata({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata, - modifiedAccessConditions: options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "ContainerClient-setMetadata", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.containerContext.setMetadata({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata, + modifiedAccessConditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * Gets the permissions for the specified container. The permissions indicate @@ -72799,44 +104013,50 @@ var require_ContainerClient = __commonJS({ if (!options.conditions) { options.conditions = {}; } - return tracing_js_1.tracingClient.withSpan("ContainerClient-getAccessPolicy", options, async (updatedOptions) => { - const response = (0, utils_common_js_1.assertResponse)(await this.containerContext.getAccessPolicy({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); - const res = { - _response: response._response, - blobPublicAccess: response.blobPublicAccess, - date: response.date, - etag: response.etag, - errorCode: response.errorCode, - lastModified: response.lastModified, - requestId: response.requestId, - clientRequestId: response.clientRequestId, - signedIdentifiers: [], - version: response.version - }; - for (const identifier of response) { - let accessPolicy = void 0; - if (identifier.accessPolicy) { - accessPolicy = { - permissions: identifier.accessPolicy.permissions - }; - if (identifier.accessPolicy.expiresOn) { - accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); - } - if (identifier.accessPolicy.startsOn) { - accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); + return import_tracing.tracingClient.withSpan( + "ContainerClient-getAccessPolicy", + options, + async (updatedOptions) => { + const response = (0, import_utils_common.assertResponse)( + await this.containerContext.getAccessPolicy({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions + }) + ); + const res = { + _response: response._response, + blobPublicAccess: response.blobPublicAccess, + date: response.date, + etag: response.etag, + errorCode: response.errorCode, + lastModified: response.lastModified, + requestId: response.requestId, + clientRequestId: response.clientRequestId, + signedIdentifiers: [], + version: response.version + }; + for (const identifier of response) { + let accessPolicy = void 0; + if (identifier.accessPolicy) { + accessPolicy = { + permissions: identifier.accessPolicy.permissions + }; + if (identifier.accessPolicy.expiresOn) { + accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); + } + if (identifier.accessPolicy.startsOn) { + accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); + } } + res.signedIdentifiers.push({ + accessPolicy, + id: identifier.id + }); } - res.signedIdentifiers.push({ - accessPolicy, - id: identifier.id - }); + return res; } - return res; - }); + ); } /** * Sets the permissions for the specified container. The permissions indicate @@ -72857,27 +104077,33 @@ var require_ContainerClient = __commonJS({ */ async setAccessPolicy(access, containerAcl, options = {}) { options.conditions = options.conditions || {}; - return tracing_js_1.tracingClient.withSpan("ContainerClient-setAccessPolicy", options, async (updatedOptions) => { - const acl = []; - for (const identifier of containerAcl || []) { - acl.push({ - accessPolicy: { - expiresOn: identifier.accessPolicy.expiresOn ? (0, utils_common_js_1.truncatedISO8061Date)(identifier.accessPolicy.expiresOn) : "", - permissions: identifier.accessPolicy.permissions, - startsOn: identifier.accessPolicy.startsOn ? (0, utils_common_js_1.truncatedISO8061Date)(identifier.accessPolicy.startsOn) : "" - }, - id: identifier.id - }); + return import_tracing.tracingClient.withSpan( + "ContainerClient-setAccessPolicy", + options, + async (updatedOptions) => { + const acl = []; + for (const identifier of containerAcl || []) { + acl.push({ + accessPolicy: { + expiresOn: identifier.accessPolicy.expiresOn ? (0, import_utils_common.truncatedISO8061Date)(identifier.accessPolicy.expiresOn) : "", + permissions: identifier.accessPolicy.permissions, + startsOn: identifier.accessPolicy.startsOn ? (0, import_utils_common.truncatedISO8061Date)(identifier.accessPolicy.startsOn) : "" + }, + id: identifier.id + }); + } + return (0, import_utils_common.assertResponse)( + await this.containerContext.setAccessPolicy({ + abortSignal: options.abortSignal, + access, + containerAcl: acl, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions + }) + ); } - return (0, utils_common_js_1.assertResponse)(await this.containerContext.setAccessPolicy({ - abortSignal: options.abortSignal, - access, - containerAcl: acl, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); - }); + ); } /** * Get a {@link BlobLeaseClient} that manages leases on the container. @@ -72886,7 +104112,7 @@ var require_ContainerClient = __commonJS({ * @returns A new BlobLeaseClient object for managing leases on the container. */ getBlobLeaseClient(proposeLeaseId) { - return new BlobLeaseClient_js_1.BlobLeaseClient(this, proposeLeaseId); + return new import_BlobLeaseClient.BlobLeaseClient(this, proposeLeaseId); } /** * Creates a new block blob, or updates the content of an existing block blob. @@ -72911,14 +104137,18 @@ var require_ContainerClient = __commonJS({ * @returns Block Blob upload response data and the corresponding BlockBlobClient instance. */ async uploadBlockBlob(blobName, body, contentLength, options = {}) { - return tracing_js_1.tracingClient.withSpan("ContainerClient-uploadBlockBlob", options, async (updatedOptions) => { - const blockBlobClient = this.getBlockBlobClient(blobName); - const response = await blockBlobClient.upload(body, contentLength, updatedOptions); - return { - blockBlobClient, - response - }; - }); + return import_tracing.tracingClient.withSpan( + "ContainerClient-uploadBlockBlob", + options, + async (updatedOptions) => { + const blockBlobClient = this.getBlockBlobClient(blobName); + const response = await blockBlobClient.upload(body, contentLength, updatedOptions); + return { + blockBlobClient, + response + }; + } + ); } /** * Marks the specified blob or snapshot for deletion. The blob is later deleted @@ -72932,7 +104162,7 @@ var require_ContainerClient = __commonJS({ * @returns Block blob deletion response data. */ async deleteBlob(blobName, options = {}) { - return tracing_js_1.tracingClient.withSpan("ContainerClient-deleteBlob", options, async (updatedOptions) => { + return import_tracing.tracingClient.withSpan("ContainerClient-deleteBlob", options, async (updatedOptions) => { let blobClient = this.getBlobClient(blobName); if (options.versionId) { blobClient = blobClient.withVersion(options.versionId); @@ -72951,34 +104181,100 @@ var require_ContainerClient = __commonJS({ * @param options - Options to Container List Blob Flat Segment operation. */ async listBlobFlatSegment(marker, options = {}) { - return tracing_js_1.tracingClient.withSpan("ContainerClient-listBlobFlatSegment", options, async (updatedOptions) => { - const response = (0, utils_common_js_1.assertResponse)(await this.containerContext.listBlobFlatSegment({ + return import_tracing.tracingClient.withSpan( + "ContainerClient-listBlobFlatSegment", + options, + async (updatedOptions) => { + if ((0, import_utils_common.resolveResponseFormat)(options.responseFormat) === import_storage_common.StorageResponseFormat.Arrow) { + return this.listBlobFlatSegmentApacheArrow(marker, { + ...options, + tracingOptions: updatedOptions.tracingOptions + }); + } + const response = (0, import_utils_common.assertResponse)( + await this.containerContext.listBlobFlatSegment({ + marker, + ...options, + tracingOptions: updatedOptions.tracingOptions + }) + ); + const wrappedResponse = { + ...response, + _response: { + ...response._response, + parsedBody: (0, import_utils_common.ConvertInternalResponseOfListBlobFlat)(response._response.parsedBody) + }, + // _response is made non-enumerable + segment: { + ...response.segment, + blobItems: response.segment.blobItems.map(mapBlobItemInternal) + } + }; + return wrappedResponse; + } + ); + } + /** + * Lists a single segment of blobs using the Apache Arrow response format. The service + * returns a raw stream that is either Apache Arrow or XML (when the account does not + * support Apache Arrow); both formats are parsed here and produce the same result. + * + * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. + * @param options - Options to Container List Blob Flat Segment operation. + */ + async listBlobFlatSegmentApacheArrow(marker, options) { + const rawResponse = (0, import_utils_common.assertResponse)( + await this.containerContext.listBlobFlatSegmentApacheArrow({ marker, - ...options, - tracingOptions: updatedOptions.tracingOptions - })); - const wrappedResponse = { - ...response, - _response: { - ...response._response, - parsedBody: (0, utils_common_js_1.ConvertInternalResponseOfListBlobFlat)(response._response.parsedBody) + ...options + }) + ); + if (!isApacheArrow(rawResponse.contentType)) { + const { parsed: internalResponse2, bodyAsText } = await (0, import_blobListXmlParser.deserializeListBlobFlatSegmentXml)(rawResponse); + return withListSegmentResponseMetadata( + { + ...internalResponse2, + segment: { + ...internalResponse2.segment, + blobItems: (internalResponse2.segment?.blobItems ?? []).map(mapBlobItemInternal) + } }, - // _response is made non-enumerable + rawResponse, + (0, import_utils_common.ConvertInternalResponseOfListBlobFlat)(internalResponse2), + bodyAsText + ); + } + const parsed = await (0, import_blobListArrowParser.parseBlobListArrowResponse)(rawResponse); + const serviceUrl = new URL(this.url); + const containerPath = serviceUrl.pathname.replace(/\/+$/, ""); + serviceUrl.pathname = containerPath.slice(0, containerPath.lastIndexOf("/") + 1); + serviceUrl.search = ""; + serviceUrl.hash = ""; + const serviceEndpoint = serviceUrl.toString(); + const internalResponse = { + serviceEndpoint, + containerName: this.containerName, + prefix: options.prefix, + marker, + maxPageSize: options.maxPageSize, + segment: { blobItems: parsed.blobItems }, + continuationToken: parsed.nextMarker + }; + return withListSegmentResponseMetadata( + { + serviceEndpoint, + containerName: this.containerName, + prefix: options.prefix, + marker, + maxPageSize: options.maxPageSize, segment: { - ...response.segment, - blobItems: response.segment.blobItems.map((blobItemInternal) => { - const blobItem = { - ...blobItemInternal, - name: (0, utils_common_js_1.BlobNameToString)(blobItemInternal.name), - tags: (0, utils_common_js_1.toTags)(blobItemInternal.blobTags), - objectReplicationSourceProperties: (0, utils_common_js_1.parseObjectReplicationRecord)(blobItemInternal.objectReplicationMetadata) - }; - return blobItem; - }) - } - }; - return wrappedResponse; - }); + blobItems: parsed.blobItems.map(mapBlobItemInternal) + }, + continuationToken: parsed.nextMarker + }, + rawResponse, + (0, import_utils_common.ConvertInternalResponseOfListBlobFlat)(internalResponse) + ); } /** * listBlobHierarchySegment returns a single segment of blobs starting from @@ -72992,41 +104288,106 @@ var require_ContainerClient = __commonJS({ * @param options - Options to Container List Blob Hierarchy Segment operation. */ async listBlobHierarchySegment(delimiter, marker, options = {}) { - return tracing_js_1.tracingClient.withSpan("ContainerClient-listBlobHierarchySegment", options, async (updatedOptions) => { - const response = (0, utils_common_js_1.assertResponse)(await this.containerContext.listBlobHierarchySegment(delimiter, { + return import_tracing.tracingClient.withSpan( + "ContainerClient-listBlobHierarchySegment", + options, + async (updatedOptions) => { + if ((0, import_utils_common.resolveResponseFormat)(options.responseFormat) === import_storage_common.StorageResponseFormat.Arrow) { + return this.listBlobHierarchySegmentApacheArrow(delimiter, marker, { + ...options, + tracingOptions: updatedOptions.tracingOptions + }); + } + const response = (0, import_utils_common.assertResponse)( + await this.containerContext.listBlobHierarchySegment(delimiter, { + marker, + ...options, + tracingOptions: updatedOptions.tracingOptions + }) + ); + const wrappedResponse = { + ...response, + _response: { + ...response._response, + parsedBody: (0, import_utils_common.ConvertInternalResponseOfListBlobHierarchy)(response._response.parsedBody) + }, + // _response is made non-enumerable + segment: { + ...response.segment, + blobItems: response.segment.blobItems.map(mapBlobItemInternal), + blobPrefixes: response.segment.blobPrefixes?.map(mapBlobPrefixInternal) + } + }; + return wrappedResponse; + } + ); + } + /** + * Lists a single segment of blobs by hierarchy using the Apache Arrow response format. + * The service returns a raw stream that is either Apache Arrow or XML (when the account + * does not support Apache Arrow); both formats are parsed here and produce the same result. + * + * @param delimiter - The character or string used to define the virtual hierarchy + * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. + * @param options - Options to Container List Blob Hierarchy Segment operation. + */ + async listBlobHierarchySegmentApacheArrow(delimiter, marker, options) { + const rawResponse = (0, import_utils_common.assertResponse)( + await this.containerContext.listBlobHierarchySegmentApacheArrow(delimiter, { marker, - ...options, - tracingOptions: updatedOptions.tracingOptions - })); - const wrappedResponse = { - ...response, - _response: { - ...response._response, - parsedBody: (0, utils_common_js_1.ConvertInternalResponseOfListBlobHierarchy)(response._response.parsedBody) + ...options + }) + ); + if (!isApacheArrow(rawResponse.contentType)) { + const { parsed: internalResponse2, bodyAsText } = await (0, import_blobListXmlParser.deserializeListBlobHierarchySegmentXml)(rawResponse); + return withListSegmentResponseMetadata( + { + ...internalResponse2, + segment: { + ...internalResponse2.segment, + blobItems: (internalResponse2.segment?.blobItems ?? []).map(mapBlobItemInternal), + blobPrefixes: internalResponse2.segment?.blobPrefixes?.map(mapBlobPrefixInternal) + } }, - // _response is made non-enumerable + rawResponse, + (0, import_utils_common.ConvertInternalResponseOfListBlobHierarchy)(internalResponse2), + bodyAsText + ); + } + const parsed = await (0, import_blobListArrowParser.parseBlobListArrowResponse)(rawResponse); + const serviceUrl = new URL(this.url); + const containerPath = serviceUrl.pathname.replace(/\/+$/, ""); + serviceUrl.pathname = containerPath.slice(0, containerPath.lastIndexOf("/") + 1); + serviceUrl.search = ""; + serviceUrl.hash = ""; + const serviceEndpoint = serviceUrl.toString(); + const internalResponse = { + serviceEndpoint, + containerName: this.containerName, + prefix: options.prefix, + marker, + maxPageSize: options.maxPageSize, + delimiter, + segment: { blobItems: parsed.blobItems, blobPrefixes: parsed.blobPrefixes }, + continuationToken: parsed.nextMarker + }; + return withListSegmentResponseMetadata( + { + serviceEndpoint, + containerName: this.containerName, + prefix: options.prefix, + marker, + maxPageSize: options.maxPageSize, + delimiter, segment: { - ...response.segment, - blobItems: response.segment.blobItems.map((blobItemInternal) => { - const blobItem = { - ...blobItemInternal, - name: (0, utils_common_js_1.BlobNameToString)(blobItemInternal.name), - tags: (0, utils_common_js_1.toTags)(blobItemInternal.blobTags), - objectReplicationSourceProperties: (0, utils_common_js_1.parseObjectReplicationRecord)(blobItemInternal.objectReplicationMetadata) - }; - return blobItem; - }), - blobPrefixes: response.segment.blobPrefixes?.map((blobPrefixInternal) => { - const blobPrefix = { - ...blobPrefixInternal, - name: (0, utils_common_js_1.BlobNameToString)(blobPrefixInternal.name) - }; - return blobPrefix; - }) - } - }; - return wrappedResponse; - }); + blobItems: parsed.blobItems.map(mapBlobItemInternal), + blobPrefixes: parsed.blobPrefixes.map(mapBlobPrefixInternal) + }, + continuationToken: parsed.nextMarker + }, + rawResponse, + (0, import_utils_common.ConvertInternalResponseOfListBlobHierarchy)(internalResponse) + ); } /** * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse @@ -73131,6 +104492,11 @@ var require_ContainerClient = __commonJS({ * @returns An asyncIterableIterator that supports paging. */ listBlobsFlat(options = {}) { + if (options.endBefore !== void 0 && (0, import_utils_common.resolveResponseFormat)(options.responseFormat) !== import_storage_common.StorageResponseFormat.Arrow) { + throw new RangeError( + "The 'endBefore' option is only supported when 'responseFormat' is StorageResponseFormat.Arrow." + ); + } const include = []; if (options.includeCopy) { include.push("copy"); @@ -73211,7 +104577,11 @@ var require_ContainerClient = __commonJS({ let listBlobsHierarchySegmentResponse; if (!!marker || marker === void 0) { do { - listBlobsHierarchySegmentResponse = await this.listBlobHierarchySegment(delimiter, marker, options); + listBlobsHierarchySegmentResponse = await this.listBlobHierarchySegment( + delimiter, + marker, + options + ); marker = listBlobsHierarchySegmentResponse.continuationToken; yield await listBlobsHierarchySegmentResponse; } while (marker); @@ -73225,7 +104595,11 @@ var require_ContainerClient = __commonJS({ */ async *listItemsByHierarchy(delimiter, options = {}) { let marker; - for await (const listBlobsHierarchySegmentResponse of this.listHierarchySegments(delimiter, marker, options)) { + for await (const listBlobsHierarchySegmentResponse of this.listHierarchySegments( + delimiter, + marker, + options + )) { const segment = listBlobsHierarchySegmentResponse.segment; if (segment.blobPrefixes) { for (const prefix of segment.blobPrefixes) { @@ -73339,6 +104713,11 @@ var require_ContainerClient = __commonJS({ if (delimiter === "") { throw new RangeError("delimiter should contain one or more characters"); } + if (options.endBefore !== void 0 && (0, import_utils_common.resolveResponseFormat)(options.responseFormat) !== import_storage_common.StorageResponseFormat.Arrow) { + throw new RangeError( + "The 'endBefore' option is only supported when 'responseFormat' is StorageResponseFormat.Arrow." + ); + } const include = []; if (options.includeCopy) { include.push("copy"); @@ -73420,28 +104799,34 @@ var require_ContainerClient = __commonJS({ * @param options - Options to find blobs by tags. */ async findBlobsByTagsSegment(tagFilterSqlExpression, marker, options = {}) { - return tracing_js_1.tracingClient.withSpan("ContainerClient-findBlobsByTagsSegment", options, async (updatedOptions) => { - const response = (0, utils_common_js_1.assertResponse)(await this.containerContext.filterBlobs({ - abortSignal: options.abortSignal, - where: tagFilterSqlExpression, - marker, - maxPageSize: options.maxPageSize, - tracingOptions: updatedOptions.tracingOptions - })); - const wrappedResponse = { - ...response, - _response: response._response, - // _response is made non-enumerable - blobs: response.blobs.map((blob) => { - let tagValue = ""; - if (blob.tags?.blobTagSet.length === 1) { - tagValue = blob.tags.blobTagSet[0].value; - } - return { ...blob, tags: (0, utils_common_js_1.toTags)(blob.tags), tagValue }; - }) - }; - return wrappedResponse; - }); + return import_tracing.tracingClient.withSpan( + "ContainerClient-findBlobsByTagsSegment", + options, + async (updatedOptions) => { + const response = (0, import_utils_common.assertResponse)( + await this.containerContext.filterBlobs({ + abortSignal: options.abortSignal, + where: tagFilterSqlExpression, + marker, + maxPageSize: options.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + }) + ); + const wrappedResponse = { + ...response, + _response: response._response, + // _response is made non-enumerable + blobs: response.blobs.map((blob) => { + let tagValue = ""; + if (blob.tags?.blobTagSet.length === 1) { + tagValue = blob.tags.blobTagSet[0].value; + } + return { ...blob, tags: (0, import_utils_common.toTags)(blob.tags), tagValue }; + }) + }; + return wrappedResponse; + } + ); } /** * Returns an AsyncIterableIterator for ContainerFindBlobsByTagsSegmentResponse. @@ -73481,7 +104866,11 @@ var require_ContainerClient = __commonJS({ */ async *findBlobsByTagsItems(tagFilterSqlExpression, options = {}) { let marker; - for await (const segment of this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)) { + for await (const segment of this.findBlobsByTagsSegments( + tagFilterSqlExpression, + marker, + options + )) { yield* segment.blobs; } } @@ -73602,12 +104991,18 @@ var require_ContainerClient = __commonJS({ * @returns Response data for the Service Get Account Info operation. */ async getAccountInfo(options = {}) { - return tracing_js_1.tracingClient.withSpan("ContainerClient-getAccountInfo", options, async (updatedOptions) => { - return (0, utils_common_js_1.assertResponse)(await this.containerContext.getAccountInfo({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "ContainerClient-getAccountInfo", + options, + async (updatedOptions) => { + return (0, import_utils_common.assertResponse)( + await this.containerContext.getAccountInfo({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } getContainerNameFromUrl() { let containerName; @@ -73615,7 +105010,7 @@ var require_ContainerClient = __commonJS({ const parsedUrl = new URL(this.url); if (parsedUrl.hostname.split(".")[1] === "blob") { containerName = parsedUrl.pathname.split("/")[1]; - } else if ((0, utils_common_js_1.isIpEndpointStyle)(parsedUrl)) { + } else if ((0, import_utils_common.isIpEndpointStyle)(parsedUrl)) { containerName = parsedUrl.pathname.split("/")[2]; } else { containerName = parsedUrl.pathname.split("/")[1]; @@ -73641,15 +105036,20 @@ var require_ContainerClient = __commonJS({ * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateSasUrl(options) { - return new Promise((resolve14) => { - if (!(this.credential instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential)) { - throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + return new Promise((resolve15) => { + if (!(this.credential instanceof import_storage_common.StorageSharedKeyCredential)) { + throw new RangeError( + "Can only generate the SAS when the client is initialized with a shared key credential" + ); } - const sas = (0, BlobSASSignatureValues_js_1.generateBlobSASQueryParameters)({ - containerName: this._containerName, - ...options - }, this.credential).toString(); - resolve14((0, utils_common_js_1.appendToURLQuery)(this.url, sas)); + const sas = (0, import_BlobSASSignatureValues.generateBlobSASQueryParameters)( + { + containerName: this._containerName, + ...options + }, + this.credential + ).toString(); + resolve15((0, import_utils_common.appendToURLQuery)(this.url, sas)); }); } /** @@ -73665,13 +105065,18 @@ var require_ContainerClient = __commonJS({ */ /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ generateSasStringToSign(options) { - if (!(this.credential instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential)) { - throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + if (!(this.credential instanceof import_storage_common.StorageSharedKeyCredential)) { + throw new RangeError( + "Can only generate the SAS when the client is initialized with a shared key credential" + ); } - return (0, BlobSASSignatureValues_js_1.generateBlobSASQueryParametersInternal)({ - containerName: this._containerName, - ...options - }, this.credential).stringToSign; + return (0, import_BlobSASSignatureValues.generateBlobSASQueryParametersInternal)( + { + containerName: this._containerName, + ...options + }, + this.credential + ).stringToSign; } /** * Generates a Blob Container Service Shared Access Signature (SAS) URI based on the client properties @@ -73684,12 +105089,16 @@ var require_ContainerClient = __commonJS({ * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateUserDelegationSasUrl(options, userDelegationKey) { - return new Promise((resolve14) => { - const sas = (0, BlobSASSignatureValues_js_1.generateBlobSASQueryParameters)({ - containerName: this._containerName, - ...options - }, userDelegationKey, this.accountName).toString(); - resolve14((0, utils_common_js_1.appendToURLQuery)(this.url, sas)); + return new Promise((resolve15) => { + const sas = (0, import_BlobSASSignatureValues.generateBlobSASQueryParameters)( + { + containerName: this._containerName, + ...options + }, + userDelegationKey, + this.accountName + ).toString(); + resolve15((0, import_utils_common.appendToURLQuery)(this.url, sas)); }); } /** @@ -73703,10 +105112,14 @@ var require_ContainerClient = __commonJS({ * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateUserDelegationSasStringToSign(options, userDelegationKey) { - return (0, BlobSASSignatureValues_js_1.generateBlobSASQueryParametersInternal)({ - containerName: this._containerName, - ...options - }, userDelegationKey, this.accountName).stringToSign; + return (0, import_BlobSASSignatureValues.generateBlobSASQueryParametersInternal)( + { + containerName: this._containerName, + ...options + }, + userDelegationKey, + this.accountName + ).stringToSign; } /** * Creates a BlobBatchClient object to conduct batch operations. @@ -73716,19 +105129,37 @@ var require_ContainerClient = __commonJS({ * @returns A new BlobBatchClient object for this container. */ getBlobBatchClient() { - return new BlobBatchClient_js_1.BlobBatchClient(this.url, this.pipeline); + return new import_BlobBatchClient.BlobBatchClient(this.url, this.pipeline); } }; - exports2.ContainerClient = ContainerClient; } }); // node_modules/@azure/storage-blob/dist/commonjs/sas/AccountSASPermissions.js var require_AccountSASPermissions = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/sas/AccountSASPermissions.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AccountSASPermissions = void 0; + "node_modules/@azure/storage-blob/dist/commonjs/sas/AccountSASPermissions.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var AccountSASPermissions_exports = {}; + __export2(AccountSASPermissions_exports, { + AccountSASPermissions: () => AccountSASPermissions + }); + module2.exports = __toCommonJS2(AccountSASPermissions_exports); var AccountSASPermissions = class _AccountSASPermissions { /** * Parse initializes the AccountSASPermissions fields from a string. @@ -73939,16 +105370,34 @@ var require_AccountSASPermissions = __commonJS({ return permissions.join(""); } }; - exports2.AccountSASPermissions = AccountSASPermissions; } }); // node_modules/@azure/storage-blob/dist/commonjs/sas/AccountSASResourceTypes.js var require_AccountSASResourceTypes = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/sas/AccountSASResourceTypes.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AccountSASResourceTypes = void 0; + "node_modules/@azure/storage-blob/dist/commonjs/sas/AccountSASResourceTypes.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var AccountSASResourceTypes_exports = {}; + __export2(AccountSASResourceTypes_exports, { + AccountSASResourceTypes: () => AccountSASResourceTypes + }); + module2.exports = __toCommonJS2(AccountSASResourceTypes_exports); var AccountSASResourceTypes = class _AccountSASResourceTypes { /** * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an @@ -74007,16 +105456,34 @@ var require_AccountSASResourceTypes = __commonJS({ return resourceTypes.join(""); } }; - exports2.AccountSASResourceTypes = AccountSASResourceTypes; } }); // node_modules/@azure/storage-blob/dist/commonjs/sas/AccountSASServices.js var require_AccountSASServices = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/sas/AccountSASServices.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AccountSASServices = void 0; + "node_modules/@azure/storage-blob/dist/commonjs/sas/AccountSASServices.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var AccountSASServices_exports = {}; + __export2(AccountSASServices_exports, { + AccountSASServices: () => AccountSASServices + }); + module2.exports = __toCommonJS2(AccountSASServices_exports); var AccountSASServices = class _AccountSASServices { /** * Creates an {@link AccountSASServices} from the specified services string. This method will throw an @@ -74083,29 +105550,47 @@ var require_AccountSASServices = __commonJS({ return services.join(""); } }; - exports2.AccountSASServices = AccountSASServices; } }); // node_modules/@azure/storage-blob/dist/commonjs/sas/AccountSASSignatureValues.js var require_AccountSASSignatureValues = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/sas/AccountSASSignatureValues.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.generateAccountSASQueryParameters = generateAccountSASQueryParameters; - exports2.generateAccountSASQueryParametersInternal = generateAccountSASQueryParametersInternal; - var AccountSASPermissions_js_1 = require_AccountSASPermissions(); - var AccountSASResourceTypes_js_1 = require_AccountSASResourceTypes(); - var AccountSASServices_js_1 = require_AccountSASServices(); - var SasIPRange_js_1 = require_SasIPRange(); - var SASQueryParameters_js_1 = require_SASQueryParameters(); - var constants_js_1 = require_constants10(); - var utils_common_js_1 = require_utils_common(); - function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { + "node_modules/@azure/storage-blob/dist/commonjs/sas/AccountSASSignatureValues.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var AccountSASSignatureValues_exports = {}; + __export2(AccountSASSignatureValues_exports, { + generateAccountSASQueryParameters: () => generateAccountSASQueryParameters2, + generateAccountSASQueryParametersInternal: () => generateAccountSASQueryParametersInternal + }); + module2.exports = __toCommonJS2(AccountSASSignatureValues_exports); + var import_AccountSASPermissions = require_AccountSASPermissions(); + var import_AccountSASResourceTypes = require_AccountSASResourceTypes(); + var import_AccountSASServices = require_AccountSASServices(); + var import_SasIPRange = require_SasIPRange(); + var import_SASQueryParameters = require_SASQueryParameters(); + var import_constants5 = require_constants11(); + var import_utils_common = require_utils_common2(); + function generateAccountSASQueryParameters2(accountSASSignatureValues, sharedKeyCredential) { return generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential).sasQueryParameters; } function generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential) { - const version = accountSASSignatureValues.version ? accountSASSignatureValues.version : constants_js_1.SERVICE_VERSION; + const version = accountSASSignatureValues.version ? accountSASSignatureValues.version : import_constants5.SERVICE_VERSION; if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.setImmutabilityPolicy && version < "2020-08-04") { throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); } @@ -74124,9 +105609,13 @@ var require_AccountSASSignatureValues = __commonJS({ if (accountSASSignatureValues.encryptionScope && version < "2020-12-06") { throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS."); } - const parsedPermissions = AccountSASPermissions_js_1.AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); - const parsedServices = AccountSASServices_js_1.AccountSASServices.parse(accountSASSignatureValues.services).toString(); - const parsedResourceTypes = AccountSASResourceTypes_js_1.AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); + const parsedPermissions = import_AccountSASPermissions.AccountSASPermissions.parse( + accountSASSignatureValues.permissions.toString() + ); + const parsedServices = import_AccountSASServices.AccountSASServices.parse(accountSASSignatureValues.services).toString(); + const parsedResourceTypes = import_AccountSASResourceTypes.AccountSASResourceTypes.parse( + accountSASSignatureValues.resourceTypes + ).toString(); let stringToSign; if (version >= "2020-12-06") { stringToSign = [ @@ -74134,9 +105623,9 @@ var require_AccountSASSignatureValues = __commonJS({ parsedPermissions, parsedServices, parsedResourceTypes, - accountSASSignatureValues.startsOn ? (0, utils_common_js_1.truncatedISO8061Date)(accountSASSignatureValues.startsOn, false) : "", - (0, utils_common_js_1.truncatedISO8061Date)(accountSASSignatureValues.expiresOn, false), - accountSASSignatureValues.ipRange ? (0, SasIPRange_js_1.ipRangeToString)(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.startsOn ? (0, import_utils_common.truncatedISO8061Date)(accountSASSignatureValues.startsOn, false) : "", + (0, import_utils_common.truncatedISO8061Date)(accountSASSignatureValues.expiresOn, false), + accountSASSignatureValues.ipRange ? (0, import_SasIPRange.ipRangeToString)(accountSASSignatureValues.ipRange) : "", accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", version, accountSASSignatureValues.encryptionScope ? accountSASSignatureValues.encryptionScope : "", @@ -74149,9 +105638,9 @@ var require_AccountSASSignatureValues = __commonJS({ parsedPermissions, parsedServices, parsedResourceTypes, - accountSASSignatureValues.startsOn ? (0, utils_common_js_1.truncatedISO8061Date)(accountSASSignatureValues.startsOn, false) : "", - (0, utils_common_js_1.truncatedISO8061Date)(accountSASSignatureValues.expiresOn, false), - accountSASSignatureValues.ipRange ? (0, SasIPRange_js_1.ipRangeToString)(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.startsOn ? (0, import_utils_common.truncatedISO8061Date)(accountSASSignatureValues.startsOn, false) : "", + (0, import_utils_common.truncatedISO8061Date)(accountSASSignatureValues.expiresOn, false), + accountSASSignatureValues.ipRange ? (0, import_SasIPRange.ipRangeToString)(accountSASSignatureValues.ipRange) : "", accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", version, "" @@ -74160,7 +105649,28 @@ var require_AccountSASSignatureValues = __commonJS({ } const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return { - sasQueryParameters: new SASQueryParameters_js_1.SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, accountSASSignatureValues.encryptionScope), + sasQueryParameters: new import_SASQueryParameters.SASQueryParameters( + version, + signature, + parsedPermissions.toString(), + parsedServices, + parsedResourceTypes, + accountSASSignatureValues.protocol, + accountSASSignatureValues.startsOn, + accountSASSignatureValues.expiresOn, + accountSASSignatureValues.ipRange, + void 0, + void 0, + void 0, + void 0, + void 0, + void 0, + void 0, + void 0, + void 0, + void 0, + accountSASSignatureValues.encryptionScope + ), stringToSign }; } @@ -74169,30 +105679,56 @@ var require_AccountSASSignatureValues = __commonJS({ // node_modules/@azure/storage-blob/dist/commonjs/BlobServiceClient.js var require_BlobServiceClient = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/BlobServiceClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BlobServiceClient = void 0; - var core_auth_1 = require_commonjs7(); - var core_rest_pipeline_1 = require_commonjs6(); - var core_util_1 = require_commonjs4(); - var Pipeline_js_1 = require_Pipeline(); - var ContainerClient_js_1 = require_ContainerClient(); - var utils_common_js_1 = require_utils_common(); - var StorageSharedKeyCredential_js_1 = require_StorageSharedKeyCredential(); - var AnonymousCredential_js_1 = require_AnonymousCredential(); - var utils_common_js_2 = require_utils_common(); - var tracing_js_1 = require_tracing(); - var BlobBatchClient_js_1 = require_BlobBatchClient(); - var StorageClient_js_1 = require_StorageClient(); - var AccountSASPermissions_js_1 = require_AccountSASPermissions(); - var AccountSASSignatureValues_js_1 = require_AccountSASSignatureValues(); - var AccountSASServices_js_1 = require_AccountSASServices(); - var BlobServiceClient = class _BlobServiceClient extends StorageClient_js_1.StorageClient { + "node_modules/@azure/storage-blob/dist/commonjs/BlobServiceClient.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var BlobServiceClient_exports = {}; + __export2(BlobServiceClient_exports, { + BlobServiceClient: () => BlobServiceClient + }); + module2.exports = __toCommonJS2(BlobServiceClient_exports); + var import_core_auth = require_commonjs7(); + var import_core_rest_pipeline = require_commonjs6(); + var import_core_util = require_commonjs4(); + var import_Pipeline = require_Pipeline(); + var import_ContainerClient = require_ContainerClient(); + var import_utils_common = require_utils_common2(); + var import_storage_common = require_commonjs12(); + var import_utils_common2 = require_utils_common2(); + var import_tracing = require_tracing(); + var import_BlobBatchClient = require_BlobBatchClient(); + var import_StorageClient = require_StorageClient(); + var import_AccountSASPermissions = require_AccountSASPermissions(); + var import_AccountSASSignatureValues = require_AccountSASSignatureValues(); + var import_AccountSASServices = require_AccountSASServices(); + function isBlobGetUserDelegationKeyParameters(parameter) { + if (!parameter || typeof parameter !== "object") { + return false; + } + const castParameter = parameter; + return castParameter.expiresOn instanceof Date; + } + var BlobServiceClient = class _BlobServiceClient extends import_StorageClient.StorageClient { /** * serviceContext provided by protocol layer. */ serviceContext; + blobClientConfig; /** * * Creates an instance of BlobServiceClient from connection string. @@ -74207,36 +105743,47 @@ var require_BlobServiceClient = __commonJS({ */ static fromConnectionString(connectionString, options) { options = options || {}; - const extractedCreds = (0, utils_common_js_1.extractConnectionStringParts)(connectionString); + const extractedCreds = (0, import_utils_common.extractConnectionStringParts)(connectionString); if (extractedCreds.kind === "AccountConnString") { - if (core_util_1.isNodeLike) { - const sharedKeyCredential = new StorageSharedKeyCredential_js_1.StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + if (import_core_util.isNodeLike) { + const sharedKeyCredential = new import_storage_common.StorageSharedKeyCredential( + extractedCreds.accountName, + extractedCreds.accountKey + ); if (!options.proxyOptions) { - options.proxyOptions = (0, core_rest_pipeline_1.getDefaultProxySettings)(extractedCreds.proxyUri); + options.proxyOptions = (0, import_core_rest_pipeline.getDefaultProxySettings)(extractedCreds.proxyUri); } - const pipeline2 = (0, Pipeline_js_1.newPipeline)(sharedKeyCredential, options); + const pipeline2 = (0, import_Pipeline.newPipeline)(sharedKeyCredential, options); return new _BlobServiceClient(extractedCreds.url, pipeline2); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } else if (extractedCreds.kind === "SASConnString") { - const pipeline2 = (0, Pipeline_js_1.newPipeline)(new AnonymousCredential_js_1.AnonymousCredential(), options); - return new _BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline2); + const pipeline2 = (0, import_Pipeline.newPipeline)(new import_storage_common.AnonymousCredential(), options); + return new _BlobServiceClient( + extractedCreds.url + "?" + extractedCreds.accountSas, + pipeline2, + options + ); } else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + throw new Error( + "Connection string must be either an Account connection string or a SAS connection string" + ); } } constructor(url2, credentialOrPipeline, options) { + options = options ?? {}; let pipeline2; - if ((0, Pipeline_js_1.isPipelineLike)(credentialOrPipeline)) { + if ((0, import_Pipeline.isPipelineLike)(credentialOrPipeline)) { pipeline2 = credentialOrPipeline; - } else if (core_util_1.isNodeLike && credentialOrPipeline instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential || credentialOrPipeline instanceof AnonymousCredential_js_1.AnonymousCredential || (0, core_auth_1.isTokenCredential)(credentialOrPipeline)) { - pipeline2 = (0, Pipeline_js_1.newPipeline)(credentialOrPipeline, options); + } else if (import_core_util.isNodeLike && credentialOrPipeline instanceof import_storage_common.StorageSharedKeyCredential || credentialOrPipeline instanceof import_storage_common.AnonymousCredential || (0, import_core_auth.isTokenCredential)(credentialOrPipeline)) { + pipeline2 = (0, import_Pipeline.newPipeline)(credentialOrPipeline, options); } else { - pipeline2 = (0, Pipeline_js_1.newPipeline)(new AnonymousCredential_js_1.AnonymousCredential(), options); + pipeline2 = (0, import_Pipeline.newPipeline)(new import_storage_common.AnonymousCredential(), options); } super(url2, pipeline2); this.serviceContext = this.storageClientContext.service; + this.blobClientConfig = options; } /** * Creates a {@link ContainerClient} object @@ -74260,7 +105807,11 @@ var require_BlobServiceClient = __commonJS({ * ``` */ getContainerClient(containerName) { - return new ContainerClient_js_1.ContainerClient((0, utils_common_js_1.appendToURLPath)(this.url, encodeURIComponent(containerName)), this.pipeline); + return new import_ContainerClient.ContainerClient( + (0, import_utils_common.appendToURLPath)(this.url, encodeURIComponent(containerName)), + this.pipeline, + this.blobClientConfig + ); } /** * Create a Blob container. @see https://learn.microsoft.com/rest/api/storageservices/create-container @@ -74270,14 +105821,18 @@ var require_BlobServiceClient = __commonJS({ * @returns Container creation response and the corresponding container client. */ async createContainer(containerName, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobServiceClient-createContainer", options, async (updatedOptions) => { - const containerClient = this.getContainerClient(containerName); - const containerCreateResponse = await containerClient.create(updatedOptions); - return { - containerClient, - containerCreateResponse - }; - }); + return import_tracing.tracingClient.withSpan( + "BlobServiceClient-createContainer", + options, + async (updatedOptions) => { + const containerClient = this.getContainerClient(containerName); + const containerCreateResponse = await containerClient.create(updatedOptions); + return { + containerClient, + containerCreateResponse + }; + } + ); } /** * Deletes a Blob container. @@ -74287,10 +105842,14 @@ var require_BlobServiceClient = __commonJS({ * @returns Container deletion response. */ async deleteContainer(containerName, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobServiceClient-deleteContainer", options, async (updatedOptions) => { - const containerClient = this.getContainerClient(containerName); - return containerClient.delete(updatedOptions); - }); + return import_tracing.tracingClient.withSpan( + "BlobServiceClient-deleteContainer", + options, + async (updatedOptions) => { + const containerClient = this.getContainerClient(containerName); + return containerClient.delete(updatedOptions); + } + ); } /** * Restore a previously deleted Blob container. @@ -74302,16 +105861,24 @@ var require_BlobServiceClient = __commonJS({ * @returns Container deletion response. */ async undeleteContainer(deletedContainerName, deletedContainerVersion, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobServiceClient-undeleteContainer", options, async (updatedOptions) => { - const containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName); - const containerContext = containerClient["storageClientContext"].container; - const containerUndeleteResponse = (0, utils_common_js_2.assertResponse)(await containerContext.restore({ - deletedContainerName, - deletedContainerVersion, - tracingOptions: updatedOptions.tracingOptions - })); - return { containerClient, containerUndeleteResponse }; - }); + return import_tracing.tracingClient.withSpan( + "BlobServiceClient-undeleteContainer", + options, + async (updatedOptions) => { + const containerClient = this.getContainerClient( + options.destinationContainerName || deletedContainerName + ); + const containerContext = containerClient["storageClientContext"].container; + const containerUndeleteResponse = (0, import_utils_common2.assertResponse)( + await containerContext.restore({ + deletedContainerName, + deletedContainerVersion, + tracingOptions: updatedOptions.tracingOptions + }) + ); + return { containerClient, containerUndeleteResponse }; + } + ); } /** * Gets the properties of a storage account’s Blob service, including properties @@ -74322,12 +105889,18 @@ var require_BlobServiceClient = __commonJS({ * @returns Response data for the Service Get Properties operation. */ async getProperties(options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobServiceClient-getProperties", options, async (updatedOptions) => { - return (0, utils_common_js_2.assertResponse)(await this.serviceContext.getProperties({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "BlobServiceClient-getProperties", + options, + async (updatedOptions) => { + return (0, import_utils_common2.assertResponse)( + await this.serviceContext.getProperties({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * Sets properties for a storage account’s Blob service endpoint, including properties @@ -74339,12 +105912,18 @@ var require_BlobServiceClient = __commonJS({ * @returns Response data for the Service Set Properties operation. */ async setProperties(properties, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobServiceClient-setProperties", options, async (updatedOptions) => { - return (0, utils_common_js_2.assertResponse)(await this.serviceContext.setProperties(properties, { - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "BlobServiceClient-setProperties", + options, + async (updatedOptions) => { + return (0, import_utils_common2.assertResponse)( + await this.serviceContext.setProperties(properties, { + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * Retrieves statistics related to replication for the Blob service. It is only @@ -74356,12 +105935,18 @@ var require_BlobServiceClient = __commonJS({ * @returns Response data for the Service Get Statistics operation. */ async getStatistics(options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobServiceClient-getStatistics", options, async (updatedOptions) => { - return (0, utils_common_js_2.assertResponse)(await this.serviceContext.getStatistics({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "BlobServiceClient-getStatistics", + options, + async (updatedOptions) => { + return (0, import_utils_common2.assertResponse)( + await this.serviceContext.getStatistics({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * The Get Account Information operation returns the sku name and account kind @@ -74374,12 +105959,18 @@ var require_BlobServiceClient = __commonJS({ * @returns Response data for the Service Get Account Info operation. */ async getAccountInfo(options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobServiceClient-getAccountInfo", options, async (updatedOptions) => { - return (0, utils_common_js_2.assertResponse)(await this.serviceContext.getAccountInfo({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "BlobServiceClient-getAccountInfo", + options, + async (updatedOptions) => { + return (0, import_utils_common2.assertResponse)( + await this.serviceContext.getAccountInfo({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * Returns a list of the containers under the specified account. @@ -74396,15 +105987,21 @@ var require_BlobServiceClient = __commonJS({ * @returns Response data for the Service List Container Segment operation. */ async listContainersSegment(marker, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobServiceClient-listContainersSegment", options, async (updatedOptions) => { - return (0, utils_common_js_2.assertResponse)(await this.serviceContext.listContainersSegment({ - abortSignal: options.abortSignal, - marker, - ...options, - include: typeof options.include === "string" ? [options.include] : options.include, - tracingOptions: updatedOptions.tracingOptions - })); - }); + return import_tracing.tracingClient.withSpan( + "BlobServiceClient-listContainersSegment", + options, + async (updatedOptions) => { + return (0, import_utils_common2.assertResponse)( + await this.serviceContext.listContainersSegment({ + abortSignal: options.abortSignal, + marker, + ...options, + include: typeof options.include === "string" ? [options.include] : options.include, + tracingOptions: updatedOptions.tracingOptions + }) + ); + } + ); } /** * The Filter Blobs operation enables callers to list blobs across all containers whose tags @@ -74425,28 +106022,34 @@ var require_BlobServiceClient = __commonJS({ * @param options - Options to find blobs by tags. */ async findBlobsByTagsSegment(tagFilterSqlExpression, marker, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobServiceClient-findBlobsByTagsSegment", options, async (updatedOptions) => { - const response = (0, utils_common_js_2.assertResponse)(await this.serviceContext.filterBlobs({ - abortSignal: options.abortSignal, - where: tagFilterSqlExpression, - marker, - maxPageSize: options.maxPageSize, - tracingOptions: updatedOptions.tracingOptions - })); - const wrappedResponse = { - ...response, - _response: response._response, - // _response is made non-enumerable - blobs: response.blobs.map((blob) => { - let tagValue = ""; - if (blob.tags?.blobTagSet.length === 1) { - tagValue = blob.tags.blobTagSet[0].value; - } - return { ...blob, tags: (0, utils_common_js_1.toTags)(blob.tags), tagValue }; - }) - }; - return wrappedResponse; - }); + return import_tracing.tracingClient.withSpan( + "BlobServiceClient-findBlobsByTagsSegment", + options, + async (updatedOptions) => { + const response = (0, import_utils_common2.assertResponse)( + await this.serviceContext.filterBlobs({ + abortSignal: options.abortSignal, + where: tagFilterSqlExpression, + marker, + maxPageSize: options.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + }) + ); + const wrappedResponse = { + ...response, + _response: response._response, + // _response is made non-enumerable + blobs: response.blobs.map((blob) => { + let tagValue = ""; + if (blob.tags?.blobTagSet.length === 1) { + tagValue = blob.tags.blobTagSet[0].value; + } + return { ...blob, tags: (0, import_utils_common.toTags)(blob.tags), tagValue }; + }) + }; + return wrappedResponse; + } + ); } /** * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. @@ -74486,7 +106089,11 @@ var require_BlobServiceClient = __commonJS({ */ async *findBlobsByTagsItems(tagFilterSqlExpression, options = {}) { let marker; - for await (const segment of this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)) { + for await (const segment of this.findBlobsByTagsSegments( + tagFilterSqlExpression, + marker, + options + )) { yield* segment.blobs; } } @@ -74741,46 +106348,57 @@ var require_BlobServiceClient = __commonJS({ } }; } - /** - * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). - * - * Retrieves a user delegation key for the Blob service. This is only a valid operation when using - * bearer token authentication. - * - * @see https://learn.microsoft.com/rest/api/storageservices/get-user-delegation-key - * - * @param startsOn - The start time for the user delegation SAS. Must be within 7 days of the current time - * @param expiresOn - The end time for the user delegation SAS. Must be within 7 days of the current time - */ - async getUserDelegationKey(startsOn, expiresOn, options = {}) { - return tracing_js_1.tracingClient.withSpan("BlobServiceClient-getUserDelegationKey", options, async (updatedOptions) => { - const response = (0, utils_common_js_2.assertResponse)(await this.serviceContext.getUserDelegationKey({ - startsOn: (0, utils_common_js_2.truncatedISO8061Date)(startsOn, false), - expiresOn: (0, utils_common_js_2.truncatedISO8061Date)(expiresOn, false) - }, { - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - const userDelegationKey = { - signedObjectId: response.signedObjectId, - signedTenantId: response.signedTenantId, - signedStartsOn: new Date(response.signedStartsOn), - signedExpiresOn: new Date(response.signedExpiresOn), - signedService: response.signedService, - signedVersion: response.signedVersion, - value: response.value - }; - const res = { - _response: response._response, - requestId: response.requestId, - clientRequestId: response.clientRequestId, - version: response.version, - date: response.date, - errorCode: response.errorCode, - ...userDelegationKey - }; - return res; - }); + async getUserDelegationKey(startsOnOrParam, expiresOnOrOption, options = {}) { + let startsOn = startsOnOrParam; + let expiresOn = expiresOnOrOption; + let userDelegationTid = void 0; + let getUserDelegationKeyOptions = options; + if (isBlobGetUserDelegationKeyParameters(startsOnOrParam)) { + startsOn = startsOnOrParam.startsOn; + expiresOn = startsOnOrParam.expiresOn; + userDelegationTid = startsOnOrParam.delegatedUserTenantId; + getUserDelegationKeyOptions = expiresOnOrOption; + getUserDelegationKeyOptions = getUserDelegationKeyOptions ?? {}; + } + return import_tracing.tracingClient.withSpan( + "BlobServiceClient-getUserDelegationKey", + getUserDelegationKeyOptions, + async (updatedOptions) => { + const response = (0, import_utils_common2.assertResponse)( + await this.serviceContext.getUserDelegationKey( + { + startsOn: (0, import_utils_common2.truncatedISO8061Date)(startsOn, false), + expiresOn: (0, import_utils_common2.truncatedISO8061Date)(expiresOn, false), + delegatedUserTid: userDelegationTid + }, + { + abortSignal: getUserDelegationKeyOptions.abortSignal, + tracingOptions: updatedOptions.tracingOptions + } + ) + ); + const userDelegationKey = { + signedObjectId: response.signedObjectId, + signedTenantId: response.signedTenantId, + signedStartsOn: new Date(response.signedStartsOn), + signedExpiresOn: new Date(response.signedExpiresOn), + signedService: response.signedService, + signedVersion: response.signedVersion, + signedDelegatedUserTenantId: response.signedDelegatedUserTenantId, + value: response.value + }; + const res = { + _response: response._response, + requestId: response.requestId, + clientRequestId: response.clientRequestId, + version: response.version, + date: response.date, + errorCode: response.errorCode, + ...userDelegationKey + }; + return res; + } + ); } /** * Creates a BlobBatchClient object to conduct batch operations. @@ -74790,7 +106408,7 @@ var require_BlobServiceClient = __commonJS({ * @returns A new BlobBatchClient object for this service. */ getBlobBatchClient() { - return new BlobBatchClient_js_1.BlobBatchClient(this.url, this.pipeline); + return new import_BlobBatchClient.BlobBatchClient(this.url, this.pipeline); } /** * Only available for BlobServiceClient constructed with a shared key credential. @@ -74806,22 +106424,27 @@ var require_BlobServiceClient = __commonJS({ * @param options - Optional parameters. * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ - generateAccountSasUrl(expiresOn, permissions = AccountSASPermissions_js_1.AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { - if (!(this.credential instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential)) { - throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + generateAccountSasUrl(expiresOn, permissions = import_AccountSASPermissions.AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { + if (!(this.credential instanceof import_storage_common.StorageSharedKeyCredential)) { + throw RangeError( + "Can only generate the account SAS when the client is initialized with a shared key credential" + ); } if (expiresOn === void 0) { const now = /* @__PURE__ */ new Date(); expiresOn = new Date(now.getTime() + 3600 * 1e3); } - const sas = (0, AccountSASSignatureValues_js_1.generateAccountSASQueryParameters)({ - permissions, - expiresOn, - resourceTypes, - services: AccountSASServices_js_1.AccountSASServices.parse("b").toString(), - ...options - }, this.credential).toString(); - return (0, utils_common_js_1.appendToURLQuery)(this.url, sas); + const sas = (0, import_AccountSASSignatureValues.generateAccountSASQueryParameters)( + { + permissions, + expiresOn, + resourceTypes, + services: import_AccountSASServices.AccountSASServices.parse("b").toString(), + ...options + }, + this.credential + ).toString(); + return (0, import_utils_common.appendToURLQuery)(this.url, sas); } /** * Only available for BlobServiceClient constructed with a shared key credential. @@ -74837,124 +106460,135 @@ var require_BlobServiceClient = __commonJS({ * @param options - Optional parameters. * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ - generateSasStringToSign(expiresOn, permissions = AccountSASPermissions_js_1.AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { - if (!(this.credential instanceof StorageSharedKeyCredential_js_1.StorageSharedKeyCredential)) { - throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + generateSasStringToSign(expiresOn, permissions = import_AccountSASPermissions.AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { + if (!(this.credential instanceof import_storage_common.StorageSharedKeyCredential)) { + throw RangeError( + "Can only generate the account SAS when the client is initialized with a shared key credential" + ); } if (expiresOn === void 0) { const now = /* @__PURE__ */ new Date(); expiresOn = new Date(now.getTime() + 3600 * 1e3); } - return (0, AccountSASSignatureValues_js_1.generateAccountSASQueryParametersInternal)({ - permissions, - expiresOn, - resourceTypes, - services: AccountSASServices_js_1.AccountSASServices.parse("b").toString(), - ...options - }, this.credential).stringToSign; + return (0, import_AccountSASSignatureValues.generateAccountSASQueryParametersInternal)( + { + permissions, + expiresOn, + resourceTypes, + services: import_AccountSASServices.AccountSASServices.parse("b").toString(), + ...options + }, + this.credential + ).stringToSign; } }; - exports2.BlobServiceClient = BlobServiceClient; - } -}); - -// node_modules/@azure/storage-blob/dist/commonjs/BatchResponse.js -var require_BatchResponse = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/BatchResponse.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); } }); // node_modules/@azure/storage-blob/dist/commonjs/generatedModels.js var require_generatedModels = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/generatedModels.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.KnownEncryptionAlgorithmType = void 0; - var KnownEncryptionAlgorithmType; - (function(KnownEncryptionAlgorithmType2) { + "node_modules/@azure/storage-blob/dist/commonjs/generatedModels.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var generatedModels_exports = {}; + __export2(generatedModels_exports, { + KnownEncryptionAlgorithmType: () => KnownEncryptionAlgorithmType + }); + module2.exports = __toCommonJS2(generatedModels_exports); + var KnownEncryptionAlgorithmType = /* @__PURE__ */ ((KnownEncryptionAlgorithmType2) => { KnownEncryptionAlgorithmType2["AES256"] = "AES256"; - })(KnownEncryptionAlgorithmType || (exports2.KnownEncryptionAlgorithmType = KnownEncryptionAlgorithmType = {})); + return KnownEncryptionAlgorithmType2; + })(KnownEncryptionAlgorithmType || {}); } }); // node_modules/@azure/storage-blob/dist/commonjs/index.js var require_commonjs15 = __commonJS({ - "node_modules/@azure/storage-blob/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = exports2.RestError = exports2.BaseRequestPolicy = exports2.StorageOAuthScopes = exports2.newPipeline = exports2.isPipelineLike = exports2.Pipeline = exports2.getBlobServiceAccountAudience = exports2.StorageBlobAudience = exports2.PremiumPageBlobTier = exports2.BlockBlobTier = exports2.generateBlobSASQueryParameters = exports2.generateAccountSASQueryParameters = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var core_rest_pipeline_1 = require_commonjs6(); - Object.defineProperty(exports2, "RestError", { enumerable: true, get: function() { - return core_rest_pipeline_1.RestError; - } }); - tslib_1.__exportStar(require_BlobServiceClient(), exports2); - tslib_1.__exportStar(require_Clients(), exports2); - tslib_1.__exportStar(require_ContainerClient(), exports2); - tslib_1.__exportStar(require_BlobLeaseClient(), exports2); - tslib_1.__exportStar(require_AccountSASPermissions(), exports2); - tslib_1.__exportStar(require_AccountSASResourceTypes(), exports2); - tslib_1.__exportStar(require_AccountSASServices(), exports2); - var AccountSASSignatureValues_js_1 = require_AccountSASSignatureValues(); - Object.defineProperty(exports2, "generateAccountSASQueryParameters", { enumerable: true, get: function() { - return AccountSASSignatureValues_js_1.generateAccountSASQueryParameters; - } }); - tslib_1.__exportStar(require_BlobBatch(), exports2); - tslib_1.__exportStar(require_BlobBatchClient(), exports2); - tslib_1.__exportStar(require_BatchResponse(), exports2); - tslib_1.__exportStar(require_BlobSASPermissions(), exports2); - var BlobSASSignatureValues_js_1 = require_BlobSASSignatureValues(); - Object.defineProperty(exports2, "generateBlobSASQueryParameters", { enumerable: true, get: function() { - return BlobSASSignatureValues_js_1.generateBlobSASQueryParameters; - } }); - tslib_1.__exportStar(require_StorageBrowserPolicyFactory2(), exports2); - tslib_1.__exportStar(require_ContainerSASPermissions(), exports2); - tslib_1.__exportStar(require_AnonymousCredential(), exports2); - tslib_1.__exportStar(require_Credential(), exports2); - tslib_1.__exportStar(require_StorageSharedKeyCredential(), exports2); - var models_js_1 = require_models2(); - Object.defineProperty(exports2, "BlockBlobTier", { enumerable: true, get: function() { - return models_js_1.BlockBlobTier; - } }); - Object.defineProperty(exports2, "PremiumPageBlobTier", { enumerable: true, get: function() { - return models_js_1.PremiumPageBlobTier; - } }); - Object.defineProperty(exports2, "StorageBlobAudience", { enumerable: true, get: function() { - return models_js_1.StorageBlobAudience; - } }); - Object.defineProperty(exports2, "getBlobServiceAccountAudience", { enumerable: true, get: function() { - return models_js_1.getBlobServiceAccountAudience; - } }); - var Pipeline_js_1 = require_Pipeline(); - Object.defineProperty(exports2, "Pipeline", { enumerable: true, get: function() { - return Pipeline_js_1.Pipeline; - } }); - Object.defineProperty(exports2, "isPipelineLike", { enumerable: true, get: function() { - return Pipeline_js_1.isPipelineLike; - } }); - Object.defineProperty(exports2, "newPipeline", { enumerable: true, get: function() { - return Pipeline_js_1.newPipeline; - } }); - Object.defineProperty(exports2, "StorageOAuthScopes", { enumerable: true, get: function() { - return Pipeline_js_1.StorageOAuthScopes; - } }); - tslib_1.__exportStar(require_StorageRetryPolicyFactory(), exports2); - var RequestPolicy_js_1 = require_RequestPolicy(); - Object.defineProperty(exports2, "BaseRequestPolicy", { enumerable: true, get: function() { - return RequestPolicy_js_1.BaseRequestPolicy; - } }); - tslib_1.__exportStar(require_AnonymousCredentialPolicy(), exports2); - tslib_1.__exportStar(require_CredentialPolicy(), exports2); - tslib_1.__exportStar(require_StorageRetryPolicyFactory(), exports2); - tslib_1.__exportStar(require_StorageSharedKeyCredentialPolicy(), exports2); - tslib_1.__exportStar(require_SASQueryParameters(), exports2); - tslib_1.__exportStar(require_generatedModels(), exports2); - var log_js_1 = require_log5(); - Object.defineProperty(exports2, "logger", { enumerable: true, get: function() { - return log_js_1.logger; - } }); + "node_modules/@azure/storage-blob/dist/commonjs/index.js"(exports2, module2) { + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var src_exports = {}; + __export2(src_exports, { + AnonymousCredential: () => import_storage_common2.AnonymousCredential, + AnonymousCredentialPolicy: () => import_storage_common2.AnonymousCredentialPolicy, + BaseRequestPolicy: () => import_storage_common2.BaseRequestPolicy, + BlockBlobTier: () => import_models.BlockBlobTier, + Credential: () => import_storage_common2.Credential, + CredentialPolicy: () => import_storage_common2.CredentialPolicy, + Pipeline: () => import_Pipeline.Pipeline, + PremiumPageBlobTier: () => import_models.PremiumPageBlobTier, + RestError: () => import_core_rest_pipeline.RestError, + StorageBlobAudience: () => import_models.StorageBlobAudience, + StorageBrowserPolicy: () => import_storage_common2.StorageBrowserPolicy, + StorageBrowserPolicyFactory: () => import_storage_common2.StorageBrowserPolicyFactory, + StorageOAuthScopes: () => import_Pipeline.StorageOAuthScopes, + StorageResponseFormat: () => import_storage_common.StorageResponseFormat, + StorageRetryPolicy: () => import_storage_common2.StorageRetryPolicy, + StorageRetryPolicyFactory: () => import_storage_common2.StorageRetryPolicyFactory, + StorageRetryPolicyType: () => import_storage_common2.StorageRetryPolicyType, + StorageSharedKeyCredential: () => import_storage_common2.StorageSharedKeyCredential, + StorageSharedKeyCredentialPolicy: () => import_storage_common2.StorageSharedKeyCredentialPolicy, + generateAccountSASQueryParameters: () => import_AccountSASSignatureValues.generateAccountSASQueryParameters, + generateBlobSASQueryParameters: () => import_BlobSASSignatureValues.generateBlobSASQueryParameters, + getBlobServiceAccountAudience: () => import_models.getBlobServiceAccountAudience, + isPipelineLike: () => import_Pipeline.isPipelineLike, + isRestError: () => import_core_rest_pipeline.isRestError, + logger: () => import_log.logger, + newPipeline: () => import_Pipeline.newPipeline + }); + module2.exports = __toCommonJS2(src_exports); + var import_core_rest_pipeline = require_commonjs6(); + __reExport(src_exports, require_BlobServiceClient(), module2.exports); + __reExport(src_exports, require_Clients(), module2.exports); + __reExport(src_exports, require_ContainerClient(), module2.exports); + __reExport(src_exports, require_BlobLeaseClient(), module2.exports); + __reExport(src_exports, require_AccountSASPermissions(), module2.exports); + __reExport(src_exports, require_AccountSASResourceTypes(), module2.exports); + __reExport(src_exports, require_AccountSASServices(), module2.exports); + var import_AccountSASSignatureValues = require_AccountSASSignatureValues(); + __reExport(src_exports, require_BlobBatch(), module2.exports); + __reExport(src_exports, require_BlobBatchClient(), module2.exports); + __reExport(src_exports, require_BlobSASPermissions(), module2.exports); + var import_BlobSASSignatureValues = require_BlobSASSignatureValues(); + __reExport(src_exports, require_ContainerSASPermissions(), module2.exports); + var import_models = require_models2(); + var import_storage_common = require_commonjs12(); + var import_Pipeline = require_Pipeline(); + var import_storage_common2 = require_commonjs12(); + __reExport(src_exports, require_SASQueryParameters(), module2.exports); + __reExport(src_exports, require_generatedModels(), module2.exports); + var import_log = require_log5(); } }); @@ -75085,11 +106719,11 @@ var require_uploadUtils = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -75105,7 +106739,7 @@ var require_uploadUtils = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -75113,7 +106747,7 @@ var require_uploadUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.UploadProgress = void 0; exports2.uploadCacheArchiveSDK = uploadCacheArchiveSDK; - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); var storage_blob_1 = require_commonjs15(); var errors_1 = require_errors2(); var UploadProgress = class { @@ -75155,7 +106789,7 @@ var require_uploadUtils = __commonJS({ const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); const elapsedTime = Date.now() - this.startTime; const uploadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1); - core31.info(`Sent ${transferredBytes} of ${this.contentLength} (${percentage}%), ${uploadSpeed} MBs/sec`); + core29.info(`Sent ${transferredBytes} of ${this.contentLength} (${percentage}%), ${uploadSpeed} MBs/sec`); if (this.isDone()) { this.displayedComplete = true; } @@ -75198,10 +106832,10 @@ var require_uploadUtils = __commonJS({ exports2.UploadProgress = UploadProgress; function uploadCacheArchiveSDK(signedUploadURL, archivePath, options) { return __awaiter2(this, void 0, void 0, function* () { - var _a2; + var _a6; const blobClient = new storage_blob_1.BlobClient(signedUploadURL); const blockBlobClient = blobClient.getBlockBlobClient(); - const uploadProgress = new UploadProgress((_a2 = options === null || options === void 0 ? void 0 : options.archiveSizeBytes) !== null && _a2 !== void 0 ? _a2 : 0); + const uploadProgress = new UploadProgress((_a6 = options === null || options === void 0 ? void 0 : options.archiveSizeBytes) !== null && _a6 !== void 0 ? _a6 : 0); const uploadOptions = { blockSize: options === null || options === void 0 ? void 0 : options.uploadChunkSize, concurrency: options === null || options === void 0 ? void 0 : options.uploadConcurrency, @@ -75212,14 +106846,14 @@ var require_uploadUtils = __commonJS({ }; try { uploadProgress.startDisplayTimer(); - core31.debug(`BlobClient: ${blobClient.name}:${blobClient.accountName}:${blobClient.containerName}`); + core29.debug(`BlobClient: ${blobClient.name}:${blobClient.accountName}:${blobClient.containerName}`); const response = yield blockBlobClient.uploadFile(archivePath, uploadOptions); if (response._response.status >= 400) { throw new errors_1.InvalidResponseError(`uploadCacheArchiveSDK: upload failed with status code ${response._response.status}`); } return response; } catch (error3) { - core31.warning(`uploadCacheArchiveSDK: internal error uploading cache archive: ${error3.message}`); + core29.warning(`uploadCacheArchiveSDK: internal error uploading cache archive: ${error3.message}`); throw error3; } finally { uploadProgress.stopDisplayTimer(); @@ -75272,11 +106906,11 @@ var require_requestUtils = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -75292,7 +106926,7 @@ var require_requestUtils = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -75304,7 +106938,7 @@ var require_requestUtils = __commonJS({ exports2.retry = retry2; exports2.retryTypedResponse = retryTypedResponse; exports2.retryHttpClientResponse = retryHttpClientResponse; - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); var http_client_1 = require_lib(); var constants_1 = require_constants7(); function isSuccessStatusCode(statusCode) { @@ -75332,7 +106966,7 @@ var require_requestUtils = __commonJS({ } function sleep(milliseconds) { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14) => setTimeout(resolve14, milliseconds)); + return new Promise((resolve15) => setTimeout(resolve15, milliseconds)); }); } function retry2(name_1, method_1, getStatusCode_1) { @@ -75362,9 +106996,9 @@ var require_requestUtils = __commonJS({ isRetryable = isRetryableStatusCode(statusCode); errorMessage = `Cache service responded with ${statusCode}`; } - core31.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); + core29.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); if (!isRetryable) { - core31.debug(`${name} - Error is not retryable`); + core29.debug(`${name} - Error is not retryable`); break; } yield sleep(delay2); @@ -75407,7 +107041,7 @@ var require_requestUtils = __commonJS({ }); // node_modules/@azure/abort-controller/dist/index.js -var require_dist5 = __commonJS({ +var require_dist4 = __commonJS({ "node_modules/@azure/abort-controller/dist/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); @@ -75489,7 +107123,7 @@ var require_dist5 = __commonJS({ } abortedMap.set(signal, true); } - var AbortError = class extends Error { + var AbortError2 = class extends Error { constructor(message) { super(message); this.name = "AbortError"; @@ -75545,7 +107179,7 @@ var require_dist5 = __commonJS({ } }; exports2.AbortController = AbortController2; - exports2.AbortError = AbortError; + exports2.AbortError = AbortError2; exports2.AbortSignal = AbortSignal2; } }); @@ -75593,11 +107227,11 @@ var require_downloadUtils = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -75613,7 +107247,7 @@ var require_downloadUtils = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -75623,20 +107257,20 @@ var require_downloadUtils = __commonJS({ exports2.downloadCacheHttpClient = downloadCacheHttpClient; exports2.downloadCacheHttpClientConcurrent = downloadCacheHttpClientConcurrent; exports2.downloadCacheStorageSDK = downloadCacheStorageSDK; - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); var http_client_1 = require_lib(); var storage_blob_1 = require_commonjs15(); var buffer = __importStar2(require("buffer")); - var fs32 = __importStar2(require("fs")); + var fs34 = __importStar2(require("fs")); var stream2 = __importStar2(require("stream")); - var util3 = __importStar2(require("util")); + var util4 = __importStar2(require("util")); var utils = __importStar2(require_cacheUtils()); var constants_1 = require_constants7(); var requestUtils_1 = require_requestUtils(); - var abort_controller_1 = require_dist5(); + var abort_controller_1 = require_dist4(); function pipeResponseToStream(response, output) { return __awaiter2(this, void 0, void 0, function* () { - const pipeline2 = util3.promisify(stream2.pipeline); + const pipeline2 = util4.promisify(stream2.pipeline); yield pipeline2(response.message, output); }); } @@ -75661,7 +107295,7 @@ var require_downloadUtils = __commonJS({ this.segmentIndex = this.segmentIndex + 1; this.segmentSize = segmentSize; this.receivedBytes = 0; - core31.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); + core29.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); } /** * Sets the number of bytes received for the current segment. @@ -75695,7 +107329,7 @@ var require_downloadUtils = __commonJS({ const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); const elapsedTime = Date.now() - this.startTime; const downloadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1); - core31.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); + core29.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); if (this.isDone()) { this.displayedComplete = true; } @@ -75738,14 +107372,14 @@ var require_downloadUtils = __commonJS({ exports2.DownloadProgress = DownloadProgress; function downloadCacheHttpClient(archiveLocation, archivePath) { return __awaiter2(this, void 0, void 0, function* () { - const writeStream = fs32.createWriteStream(archivePath); + const writeStream = fs34.createWriteStream(archivePath); const httpClient = new http_client_1.HttpClient("actions/cache"); const downloadResponse = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCache", () => __awaiter2(this, void 0, void 0, function* () { return httpClient.get(archiveLocation); })); downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => { downloadResponse.message.destroy(); - core31.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); + core29.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); }); yield pipeResponseToStream(downloadResponse, writeStream); const contentLengthHeader = downloadResponse.message.headers["content-length"]; @@ -75756,14 +107390,14 @@ var require_downloadUtils = __commonJS({ throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); } } else { - core31.debug("Unable to validate download, no Content-Length header"); + core29.debug("Unable to validate download, no Content-Length header"); } }); } function downloadCacheHttpClientConcurrent(archiveLocation, archivePath, options) { return __awaiter2(this, void 0, void 0, function* () { - var _a2; - const archiveDescriptor = yield fs32.promises.open(archivePath, "w"); + var _a6; + const archiveDescriptor = yield fs34.promises.open(archivePath, "w"); const httpClient = new http_client_1.HttpClient("actions/cache", void 0, { socketTimeout: options.timeoutInMs, keepAlive: true @@ -75810,7 +107444,7 @@ var require_downloadUtils = __commonJS({ while (nextDownload = downloads.pop()) { activeDownloads[nextDownload.offset] = nextDownload.promiseGetter(); actives++; - if (actives >= ((_a2 = options.downloadConcurrency) !== null && _a2 !== void 0 ? _a2 : 10)) { + if (actives >= ((_a6 = options.downloadConcurrency) !== null && _a6 !== void 0 ? _a6 : 10)) { yield waitAndWrite(); } } @@ -75863,7 +107497,7 @@ var require_downloadUtils = __commonJS({ } function downloadCacheStorageSDK(archiveLocation, archivePath, options) { return __awaiter2(this, void 0, void 0, function* () { - var _a2; + var _a6; const client = new storage_blob_1.BlockBlobClient(archiveLocation, void 0, { retryOptions: { // Override the timeout used when downloading each 4 MB chunk @@ -75872,14 +107506,14 @@ var require_downloadUtils = __commonJS({ } }); const properties = yield client.getProperties(); - const contentLength = (_a2 = properties.contentLength) !== null && _a2 !== void 0 ? _a2 : -1; + const contentLength = (_a6 = properties.contentLength) !== null && _a6 !== void 0 ? _a6 : -1; if (contentLength < 0) { - core31.debug("Unable to determine content length, downloading file with http-client..."); + core29.debug("Unable to determine content length, downloading file with http-client..."); yield downloadCacheHttpClient(archiveLocation, archivePath); } else { const maxSegmentSize = Math.min(134217728, buffer.constants.MAX_LENGTH); const downloadProgress = new DownloadProgress(contentLength); - const fd = fs32.openSync(archivePath, "w"); + const fd = fs34.openSync(archivePath, "w"); try { downloadProgress.startDisplayTimer(); const controller = new abort_controller_1.AbortController(); @@ -75897,20 +107531,20 @@ var require_downloadUtils = __commonJS({ controller.abort(); throw new Error("Aborting cache download as the download time exceeded the timeout."); } else if (Buffer.isBuffer(result)) { - fs32.writeFileSync(fd, result); + fs34.writeFileSync(fd, result); } } } finally { downloadProgress.stopDisplayTimer(); - fs32.closeSync(fd); + fs34.closeSync(fd); } } }); } var promiseWithTimeout = (timeoutMs, promise) => __awaiter2(void 0, void 0, void 0, function* () { let timeoutHandle; - const timeoutPromise = new Promise((resolve14) => { - timeoutHandle = setTimeout(() => resolve14("timeout"), timeoutMs); + const timeoutPromise = new Promise((resolve15) => { + timeoutHandle = setTimeout(() => resolve15("timeout"), timeoutMs); }); return Promise.race([promise, timeoutPromise]).then((result) => { clearTimeout(timeoutHandle); @@ -75964,7 +107598,7 @@ var require_options = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getUploadOptions = getUploadOptions; exports2.getDownloadOptions = getDownloadOptions; - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); function getUploadOptions(copy) { const result = { useAzureSdk: false, @@ -75984,9 +107618,9 @@ var require_options = __commonJS({ } result.uploadConcurrency = !isNaN(Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) ? Math.min(32, Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) : result.uploadConcurrency; result.uploadChunkSize = !isNaN(Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"])) ? Math.min(128 * 1024 * 1024, Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"]) * 1024 * 1024) : result.uploadChunkSize; - core31.debug(`Use Azure SDK: ${result.useAzureSdk}`); - core31.debug(`Upload concurrency: ${result.uploadConcurrency}`); - core31.debug(`Upload chunk size: ${result.uploadChunkSize}`); + core29.debug(`Use Azure SDK: ${result.useAzureSdk}`); + core29.debug(`Upload concurrency: ${result.uploadConcurrency}`); + core29.debug(`Upload chunk size: ${result.uploadChunkSize}`); return result; } function getDownloadOptions(copy) { @@ -76022,12 +107656,12 @@ var require_options = __commonJS({ if (segmentDownloadTimeoutMins && !isNaN(Number(segmentDownloadTimeoutMins)) && isFinite(Number(segmentDownloadTimeoutMins))) { result.segmentTimeoutInMs = Number(segmentDownloadTimeoutMins) * 60 * 1e3; } - core31.debug(`Use Azure SDK: ${result.useAzureSdk}`); - core31.debug(`Download concurrency: ${result.downloadConcurrency}`); - core31.debug(`Request timeout (ms): ${result.timeoutInMs}`); - core31.debug(`Cache segment download timeout mins env var: ${process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]}`); - core31.debug(`Segment download timeout (ms): ${result.segmentTimeoutInMs}`); - core31.debug(`Lookup only: ${result.lookupOnly}`); + core29.debug(`Use Azure SDK: ${result.useAzureSdk}`); + core29.debug(`Download concurrency: ${result.downloadConcurrency}`); + core29.debug(`Request timeout (ms): ${result.timeoutInMs}`); + core29.debug(`Cache segment download timeout mins env var: ${process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]}`); + core29.debug(`Segment download timeout (ms): ${result.segmentTimeoutInMs}`); + core29.debug(`Lookup only: ${result.lookupOnly}`); return result; } } @@ -76090,7 +107724,7 @@ var require_package = __commonJS({ "node_modules/@actions/cache/package.json"(exports2, module2) { module2.exports = { name: "@actions/cache", - version: "5.2.0", + version: "5.3.0", preview: true, description: "Actions cache lib", keywords: [ @@ -76127,22 +107761,22 @@ var require_package = __commonJS({ url: "https://github.com/actions/toolkit/issues" }, dependencies: { - "@actions/core": "^2.0.0", + "@actions/core": "^2.0.3", "@actions/exec": "^2.0.0", "@actions/glob": "^0.5.1", - "@protobuf-ts/runtime-rpc": "^2.11.1", "@actions/http-client": "^3.0.2", "@actions/io": "^2.0.0", "@azure/abort-controller": "^1.1.0", - "@azure/core-rest-pipeline": "^1.22.0", - "@azure/storage-blob": "^12.29.1", + "@azure/core-rest-pipeline": "^1.25.0", + "@azure/storage-blob": "^12.34.0", + "@protobuf-ts/runtime-rpc": "^2.11.1", semver: "^6.3.1" }, devDependencies: { - "@types/node": "^24.1.0", - "@types/semver": "^6.0.0", - "@protobuf-ts/plugin": "^2.9.4", - typescript: "^5.2.2" + "@protobuf-ts/plugin": "^2.11.1", + "@types/node": "^24.13.6", + "@types/semver": "^6.2.7", + typescript: "^5.9.3" }, overrides: { "uri-js": "npm:uri-js-replace@^1.0.1", @@ -76208,11 +107842,11 @@ var require_cacheHttpClient = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -76228,7 +107862,7 @@ var require_cacheHttpClient = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -76238,10 +107872,10 @@ var require_cacheHttpClient = __commonJS({ exports2.downloadCache = downloadCache; exports2.reserveCache = reserveCache; exports2.saveCache = saveCache5; - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); var http_client_1 = require_lib(); var auth_1 = require_auth(); - var fs32 = __importStar2(require("fs")); + var fs34 = __importStar2(require("fs")); var url_1 = require("url"); var utils = __importStar2(require_cacheUtils()); var uploadUtils_1 = require_uploadUtils(); @@ -76257,7 +107891,7 @@ var require_cacheHttpClient = __commonJS({ throw new Error("Cache Service Url not found, unable to restore cache."); } const url2 = `${baseUrl}_apis/artifactcache/${resource}`; - core31.debug(`Resource Url: ${url2}`); + core29.debug(`Resource Url: ${url2}`); return url2; } function createAcceptHeader(type, apiVersion) { @@ -76278,7 +107912,7 @@ var require_cacheHttpClient = __commonJS({ } function getCacheEntry(keys, paths, options) { return __awaiter2(this, void 0, void 0, function* () { - var _a2; + var _a6; const httpClient = createHttpClient(); const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); const resource = `cache?keys=${encodeURIComponent(keys.join(","))}&version=${version}`; @@ -76286,13 +107920,13 @@ var require_cacheHttpClient = __commonJS({ return httpClient.getJson(getCacheApiUrl(resource)); })); if (response.statusCode === 204) { - if (core31.isDebug()) { + if (core29.isDebug()) { yield printCachesListForDiagnostics(keys[0], httpClient, version); } return null; } if (!(0, requestUtils_1.isSuccessStatusCode)(response.statusCode)) { - const errorMessage = (_a2 = response.error) === null || _a2 === void 0 ? void 0 : _a2.message; + const errorMessage = (_a6 = response.error) === null || _a6 === void 0 ? void 0 : _a6.message; if (errorMessage === null || errorMessage === void 0 ? void 0 : errorMessage.includes(constants_1.CacheReadDeniedMessagePrefix)) { throw new Error(errorMessage); } @@ -76303,9 +107937,9 @@ var require_cacheHttpClient = __commonJS({ if (!cacheDownloadUrl) { throw new Error("Cache not found."); } - core31.setSecret(cacheDownloadUrl); - core31.debug(`Cache Result:`); - core31.debug(JSON.stringify(cacheResult)); + core29.setSecret(cacheDownloadUrl); + core29.debug(`Cache Result:`); + core29.debug(JSON.stringify(cacheResult)); return cacheResult; }); } @@ -76319,10 +107953,10 @@ var require_cacheHttpClient = __commonJS({ const cacheListResult = response.result; const totalCount = cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.totalCount; if (totalCount && totalCount > 0) { - core31.debug(`No matching cache found for cache key '${key}', version '${version} and scope ${process.env["GITHUB_REF"]}. There exist one or more cache(s) with similar key but they have different version or scope. See more info on cache matching here: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key + core29.debug(`No matching cache found for cache key '${key}', version '${version} and scope ${process.env["GITHUB_REF"]}. There exist one or more cache(s) with similar key but they have different version or scope. See more info on cache matching here: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key Other caches with similar key:`); for (const cacheEntry of (cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.artifactCaches) || []) { - core31.debug(`Cache Key: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheKey}, Cache Version: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheVersion}, Cache Scope: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.scope}, Cache Created: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.creationTime}`); + core29.debug(`Cache Key: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheKey}, Cache Version: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheVersion}, Cache Scope: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.scope}, Cache Created: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.creationTime}`); } } } @@ -76365,7 +107999,7 @@ Other caches with similar key:`); } function uploadChunk(httpClient, resourceUrl, openStream, start, end) { return __awaiter2(this, void 0, void 0, function* () { - core31.debug(`Uploading chunk of size ${end - start + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); + core29.debug(`Uploading chunk of size ${end - start + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); const additionalHeaders = { "Content-Type": "application/octet-stream", "Content-Range": getContentRange(start, end) @@ -76382,12 +108016,12 @@ Other caches with similar key:`); return __awaiter2(this, void 0, void 0, function* () { const fileSize = utils.getArchiveFileSizeInBytes(archivePath); const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); - const fd = fs32.openSync(archivePath, "r"); + const fd = fs34.openSync(archivePath, "r"); const uploadOptions = (0, options_1.getUploadOptions)(options); const concurrency = utils.assertDefined("uploadConcurrency", uploadOptions.uploadConcurrency); const maxChunkSize = utils.assertDefined("uploadChunkSize", uploadOptions.uploadChunkSize); const parallelUploads = [...new Array(concurrency).keys()]; - core31.debug("Awaiting all uploads"); + core29.debug("Awaiting all uploads"); let offset = 0; try { yield Promise.all(parallelUploads.map(() => __awaiter2(this, void 0, void 0, function* () { @@ -76396,7 +108030,7 @@ Other caches with similar key:`); const start = offset; const end = offset + chunkSize - 1; offset += maxChunkSize; - yield uploadChunk(httpClient, resourceUrl, () => fs32.createReadStream(archivePath, { + yield uploadChunk(httpClient, resourceUrl, () => fs34.createReadStream(archivePath, { fd, start, end, @@ -76407,7 +108041,7 @@ Other caches with similar key:`); } }))); } finally { - fs32.closeSync(fd); + fs34.closeSync(fd); } return; }); @@ -76430,16 +108064,16 @@ Other caches with similar key:`); yield (0, uploadUtils_1.uploadCacheArchiveSDK)(signedUploadURL, archivePath, options); } else { const httpClient = createHttpClient(); - core31.debug("Upload cache"); + core29.debug("Upload cache"); yield uploadFile(httpClient, cacheId, archivePath, options); - core31.debug("Commiting cache"); + core29.debug("Commiting cache"); const cacheSize = utils.getArchiveFileSizeInBytes(archivePath); - core31.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); + core29.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); if (!(0, requestUtils_1.isSuccessStatusCode)(commitCacheResponse.statusCode)) { throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); } - core31.info("Cache saved successfully"); + core29.info("Cache saved successfully"); } }); } @@ -77524,9 +109158,9 @@ var require_json_format_contract = __commonJS({ } exports2.jsonWriteOptions = jsonWriteOptions; function mergeJsonOptions(a, b) { - var _a2, _b; + var _a6, _b2; let c = Object.assign(Object.assign({}, a), b); - c.typeRegistry = [...(_a2 = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a2 !== void 0 ? _a2 : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; + c.typeRegistry = [...(_a6 = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a6 !== void 0 ? _a6 : [], ...(_b2 = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b2 !== void 0 ? _b2 : []]; return c; } exports2.mergeJsonOptions = mergeJsonOptions; @@ -77612,23 +109246,23 @@ var require_reflection_info = __commonJS({ RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); function normalizeFieldInfo(field) { - var _a2, _b, _c, _d; - field.localName = (_a2 = field.localName) !== null && _a2 !== void 0 ? _a2 : lower_camel_case_1.lowerCamelCase(field.name); - field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); - field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; - field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; + var _a6, _b2, _c2, _d2; + field.localName = (_a6 = field.localName) !== null && _a6 !== void 0 ? _a6 : lower_camel_case_1.lowerCamelCase(field.name); + field.jsonName = (_b2 = field.jsonName) !== null && _b2 !== void 0 ? _b2 : lower_camel_case_1.lowerCamelCase(field.name); + field.repeat = (_c2 = field.repeat) !== null && _c2 !== void 0 ? _c2 : RepeatType.NO; + field.opt = (_d2 = field.opt) !== null && _d2 !== void 0 ? _d2 : field.repeat ? false : field.oneof ? false : field.kind == "message"; return field; } exports2.normalizeFieldInfo = normalizeFieldInfo; function readFieldOptions(messageType, fieldName, extensionName, extensionType) { - var _a2; - const options = (_a2 = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a2 === void 0 ? void 0 : _a2.options; + var _a6; + const options = (_a6 = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a6 === void 0 ? void 0 : _a6.options; return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; } exports2.readFieldOptions = readFieldOptions; function readFieldOption(messageType, fieldName, extensionName, extensionType) { - var _a2; - const options = (_a2 = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a2 === void 0 ? void 0 : _a2.options; + var _a6; + const options = (_a6 = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a6 === void 0 ? void 0 : _a6.options; if (!options) { return void 0; } @@ -77724,8 +109358,8 @@ var require_reflection_type_check = __commonJS({ var oneof_1 = require_oneof(); var ReflectionTypeCheck = class { constructor(info8) { - var _a2; - this.fields = (_a2 = info8.fields) !== null && _a2 !== void 0 ? _a2 : []; + var _a6; + this.fields = (_a6 = info8.fields) !== null && _a6 !== void 0 ? _a6 : []; } prepare() { if (this.data) @@ -77975,10 +109609,10 @@ var require_reflection_json_reader = __commonJS({ this.info = info8; } prepare() { - var _a2; + var _a6; if (this.fMap === void 0) { this.fMap = {}; - const fieldsInput = (_a2 = this.info.fields) !== null && _a2 !== void 0 ? _a2 : []; + const fieldsInput = (_a6 = this.info.fields) !== null && _a6 !== void 0 ? _a6 : []; for (const field of fieldsInput) { this.fMap[field.name] = field; this.fMap[field.jsonName] = field; @@ -78269,8 +109903,8 @@ var require_reflection_json_writer = __commonJS({ var assert_1 = require_assert(); var ReflectionJsonWriter = class { constructor(info8) { - var _a2; - this.fields = (_a2 = info8.fields) !== null && _a2 !== void 0 ? _a2 : []; + var _a6; + this.fields = (_a6 = info8.fields) !== null && _a6 !== void 0 ? _a6 : []; } /** * Converts the message to a JSON object, based on the field descriptors. @@ -78527,9 +110161,9 @@ var require_reflection_binary_reader = __commonJS({ this.info = info8; } prepare() { - var _a2; + var _a6; if (!this.fieldNoToField) { - const fieldsInput = (_a2 = this.info.fields) !== null && _a2 !== void 0 ? _a2 : []; + const fieldsInput = (_a6 = this.info.fields) !== null && _a6 !== void 0 ? _a6 : []; this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); } } @@ -79197,9 +110831,9 @@ var require_message_type = __commonJS({ * This is equivalent to `JSON.stringify(T.toJson(t))` */ toJsonString(message, options) { - var _a2; + var _a6; let value = this.toJson(message, options); - return JSON.stringify(value, null, (_a2 = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a2 !== void 0 ? _a2 : 0); + return JSON.stringify(value, null, (_a6 = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a6 !== void 0 ? _a6 : 0); } /** * Write the message to binary format. @@ -79525,26 +111159,26 @@ var require_reflection_info2 = __commonJS({ exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; var runtime_1 = require_commonjs16(); function normalizeMethodInfo(method, service) { - var _a2, _b, _c; + var _a6, _b2, _c2; let m = method; m.service = service; - m.localName = (_a2 = m.localName) !== null && _a2 !== void 0 ? _a2 : runtime_1.lowerCamelCase(m.name); + m.localName = (_a6 = m.localName) !== null && _a6 !== void 0 ? _a6 : runtime_1.lowerCamelCase(m.name); m.serverStreaming = !!m.serverStreaming; m.clientStreaming = !!m.clientStreaming; - m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; - m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; + m.options = (_b2 = m.options) !== null && _b2 !== void 0 ? _b2 : {}; + m.idempotency = (_c2 = m.idempotency) !== null && _c2 !== void 0 ? _c2 : void 0; return m; } exports2.normalizeMethodInfo = normalizeMethodInfo; function readMethodOptions(service, methodName, extensionName, extensionType) { - var _a2; - const options = (_a2 = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a2 === void 0 ? void 0 : _a2.options; + var _a6; + const options = (_a6 = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a6 === void 0 ? void 0 : _a6.options; return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; } exports2.readMethodOptions = readMethodOptions; function readMethodOption(service, methodName, extensionName, extensionType) { - var _a2; - const options = (_a2 = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a2 === void 0 ? void 0 : _a2.options; + var _a6; + const options = (_a6 = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a6 === void 0 ? void 0 : _a6.options; if (!options) { return void 0; } @@ -79704,8 +111338,8 @@ var require_deferred = __commonJS({ */ constructor(preventUnhandledRejectionWarning = true) { this._state = DeferredState.PENDING; - this._promise = new Promise((resolve14, reject) => { - this._resolve = resolve14; + this._promise = new Promise((resolve15, reject) => { + this._resolve = resolve15; this._reject = reject; }); if (preventUnhandledRejectionWarning) { @@ -79920,11 +111554,11 @@ var require_unary_call = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -79940,7 +111574,7 @@ var require_unary_call = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -79989,11 +111623,11 @@ var require_server_streaming_call = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -80009,7 +111643,7 @@ var require_server_streaming_call = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -80059,11 +111693,11 @@ var require_client_streaming_call = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -80079,7 +111713,7 @@ var require_client_streaming_call = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -80128,11 +111762,11 @@ var require_duplex_streaming_call = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -80148,7 +111782,7 @@ var require_duplex_streaming_call = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -80196,11 +111830,11 @@ var require_test_transport = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -80216,7 +111850,7 @@ var require_test_transport = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -80267,8 +111901,8 @@ var require_test_transport = __commonJS({ } // Creates a promise for response headers from the mock data. promiseHeaders() { - var _a2; - const headers = (_a2 = this.data.headers) !== null && _a2 !== void 0 ? _a2 : _TestTransport.defaultHeaders; + var _a6; + const headers = (_a6 = this.data.headers) !== null && _a6 !== void 0 ? _a6 : _TestTransport.defaultHeaders; return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); } // Creates a promise for a single, valid, message from the mock data. @@ -80343,14 +111977,14 @@ var require_test_transport = __commonJS({ } // Creates a promise for response status from the mock data. promiseStatus() { - var _a2; - const status = (_a2 = this.data.status) !== null && _a2 !== void 0 ? _a2 : _TestTransport.defaultStatus; + var _a6; + const status = (_a6 = this.data.status) !== null && _a6 !== void 0 ? _a6 : _TestTransport.defaultStatus; return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); } // Creates a promise for response trailers from the mock data. promiseTrailers() { - var _a2; - const trailers = (_a2 = this.data.trailers) !== null && _a2 !== void 0 ? _a2 : _TestTransport.defaultTrailers; + var _a6; + const trailers = (_a6 = this.data.trailers) !== null && _a6 !== void 0 ? _a6 : _TestTransport.defaultTrailers; return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); } maybeSuppressUncaught(...promise) { @@ -80365,8 +111999,8 @@ var require_test_transport = __commonJS({ return rpc_options_1.mergeRpcOptions({}, options); } unary(method, input, options) { - var _a2; - const requestHeaders = (_a2 = options.meta) !== null && _a2 !== void 0 ? _a2 : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_2) => { + var _a6; + const requestHeaders = (_a6 = options.meta) !== null && _a6 !== void 0 ? _a6 : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_2) => { }).then(delay2(this.responseDelay, options.abort)).then((_2) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_2) => { }).then(delay2(this.afterResponseDelay, options.abort)).then((_2) => this.promiseStatus()), trailersPromise = responsePromise.catch((_2) => { }).then(delay2(this.afterResponseDelay, options.abort)).then((_2) => this.promiseTrailers()); @@ -80375,16 +112009,16 @@ var require_test_transport = __commonJS({ return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); } serverStreaming(method, input, options) { - var _a2; - const requestHeaders = (_a2 = options.meta) !== null && _a2 !== void 0 ? _a2 : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + var _a6; + const requestHeaders = (_a6 = options.meta) !== null && _a6 !== void 0 ? _a6 : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); this.maybeSuppressUncaught(statusPromise, trailersPromise); this.lastInput = { single: input }; return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); } clientStreaming(method, options) { - var _a2; - const requestHeaders = (_a2 = options.meta) !== null && _a2 !== void 0 ? _a2 : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_2) => { + var _a6; + const requestHeaders = (_a6 = options.meta) !== null && _a6 !== void 0 ? _a6 : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_2) => { }).then(delay2(this.responseDelay, options.abort)).then((_2) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_2) => { }).then(delay2(this.afterResponseDelay, options.abort)).then((_2) => this.promiseStatus()), trailersPromise = responsePromise.catch((_2) => { }).then(delay2(this.afterResponseDelay, options.abort)).then((_2) => this.promiseTrailers()); @@ -80393,8 +112027,8 @@ var require_test_transport = __commonJS({ return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); } duplex(method, options) { - var _a2; - const requestHeaders = (_a2 = options.meta) !== null && _a2 !== void 0 ? _a2 : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + var _a6; + const requestHeaders = (_a6 = options.meta) !== null && _a6 !== void 0 ? _a6 : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); this.maybeSuppressUncaught(statusPromise, trailersPromise); this.lastInput = new TestInputStream(this.data, options.abort); @@ -80413,11 +112047,11 @@ var require_test_transport = __commonJS({ responseTrailer: "test" }; function delay2(ms, abort) { - return (v) => new Promise((resolve14, reject) => { + return (v) => new Promise((resolve15, reject) => { if (abort === null || abort === void 0 ? void 0 : abort.aborted) { reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); } else { - const id = setTimeout(() => resolve14(v), ms); + const id = setTimeout(() => resolve15(v), ms); if (abort) { abort.addEventListener("abort", (ev) => { clearTimeout(id); @@ -80470,10 +112104,10 @@ var require_rpc_interceptor = __commonJS({ exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; var runtime_1 = require_commonjs16(); function stackIntercept(kind, transport, method, options, input) { - var _a2, _b, _c, _d; + var _a6, _b2, _c2, _d2; if (kind == "unary") { let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); - for (const curr of ((_a2 = options.interceptors) !== null && _a2 !== void 0 ? _a2 : []).filter((i) => i.interceptUnary).reverse()) { + for (const curr of ((_a6 = options.interceptors) !== null && _a6 !== void 0 ? _a6 : []).filter((i) => i.interceptUnary).reverse()) { const next = tail; tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); } @@ -80481,7 +112115,7 @@ var require_rpc_interceptor = __commonJS({ } if (kind == "serverStreaming") { let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); - for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { + for (const curr of ((_b2 = options.interceptors) !== null && _b2 !== void 0 ? _b2 : []).filter((i) => i.interceptServerStreaming).reverse()) { const next = tail; tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); } @@ -80489,7 +112123,7 @@ var require_rpc_interceptor = __commonJS({ } if (kind == "clientStreaming") { let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); - for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { + for (const curr of ((_c2 = options.interceptors) !== null && _c2 !== void 0 ? _c2 : []).filter((i) => i.interceptClientStreaming).reverse()) { const next = tail; tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); } @@ -80497,7 +112131,7 @@ var require_rpc_interceptor = __commonJS({ } if (kind == "duplex") { let tail = (mtd, opt) => transport.duplex(mtd, opt); - for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { + for (const curr of ((_d2 = options.interceptors) !== null && _d2 !== void 0 ? _d2 : []).filter((i) => i.interceptDuplex).reverse()) { const next = tail; tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); } @@ -80820,7 +112454,7 @@ var require_cachemetadata = __commonJS({ }); // node_modules/@actions/cache/lib/generated/results/api/v1/cache.js -var require_cache3 = __commonJS({ +var require_cache5 = __commonJS({ "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); @@ -81305,7 +112939,7 @@ var require_cache_twirp_client = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; - var cache_1 = require_cache3(); + var cache_1 = require_cache5(); var CacheServiceClientJSON = class { constructor(rpc) { this.rpc = rpc; @@ -81373,7 +113007,7 @@ var require_cache_twirp_client = __commonJS({ }); // node_modules/@actions/cache/lib/internal/shared/util.js -var require_util10 = __commonJS({ +var require_util8 = __commonJS({ "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); @@ -81415,11 +113049,11 @@ var require_cacheTwirpClient = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -81435,7 +113069,7 @@ var require_cacheTwirpClient = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -81450,7 +113084,7 @@ var require_cacheTwirpClient = __commonJS({ var auth_1 = require_auth(); var http_client_1 = require_lib(); var cache_twirp_client_1 = require_cache_twirp_client(); - var util_1 = require_util10(); + var util_1 = require_util8(); var CacheServiceClient = class { constructor(userAgent2, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { this.maxAttempts = 5; @@ -81575,7 +113209,7 @@ var require_cacheTwirpClient = __commonJS({ } sleep(milliseconds) { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14) => setTimeout(resolve14, milliseconds)); + return new Promise((resolve15) => setTimeout(resolve15, milliseconds)); }); } getExponentialRetryTimeMilliseconds(attempt) { @@ -81640,11 +113274,11 @@ var require_tar = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -81660,7 +113294,7 @@ var require_tar = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -81669,8 +113303,9 @@ var require_tar = __commonJS({ exports2.listTar = listTar; exports2.extractTar = extractTar3; exports2.createTar = createTar; + var core29 = __importStar2(require_core()); var exec_1 = require_exec(); - var io9 = __importStar2(require_io()); + var io10 = __importStar2(require_io()); var fs_1 = require("fs"); var path30 = __importStar2(require("path")); var utils = __importStar2(require_cacheUtils()); @@ -81690,12 +113325,12 @@ var require_tar = __commonJS({ break; } case "darwin": { - const gnuTar = yield io9.which("gtar", false); + const gnuTar = yield io10.which("gtar", false); if (gnuTar) { return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; } else { return { - path: yield io9.which("tar", true), + path: yield io10.which("tar", true), type: constants_1.ArchiveToolType.BSD }; } @@ -81704,7 +113339,7 @@ var require_tar = __commonJS({ break; } return { - path: yield io9.which("tar", true), + path: yield io10.which("tar", true), type: constants_1.ArchiveToolType.GNU }; }); @@ -81721,7 +113356,7 @@ var require_tar = __commonJS({ args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path30.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path30.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path30.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); break; case "extract": - args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path30.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path30.sep}`, "g"), "/")); + args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path30.sep}`, "g"), "/"), "-P", "-C", BSD_TAR_ZSTD ? quoteAbsolutePath(workingDirectory) : workingDirectory.replace(new RegExp(`\\${path30.sep}`, "g"), "/")); break; case "list": args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path30.sep}`, "g"), "/"), "-P"); @@ -81752,15 +113387,18 @@ var require_tar = __commonJS({ } else { args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; } - if (BSD_TAR_ZSTD) { - return args; - } - return [args.join(" ")]; + return { + commands: BSD_TAR_ZSTD ? args : [args.join(" ")], + requiresTempDirectory: BSD_TAR_ZSTD && type !== "create" + }; }); } function getWorkingDirectory() { - var _a2; - return (_a2 = process.env["GITHUB_WORKSPACE"]) !== null && _a2 !== void 0 ? _a2 : process.cwd(); + var _a6; + return (_a6 = process.env["GITHUB_WORKSPACE"]) !== null && _a6 !== void 0 ? _a6 : process.cwd(); + } + function quoteAbsolutePath(filePath) { + return `"${path30.resolve(filePath).replace(new RegExp(`\\${path30.sep}`, "g"), "/")}"`; } function getDecompressionProgram(tarPath, compressionMethod, archivePath) { return __awaiter2(this, void 0, void 0, function* () { @@ -81770,17 +113408,13 @@ var require_tar = __commonJS({ return BSD_TAR_ZSTD ? [ "zstd -d --long=30 --force -o", constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path30.sep}`, "g"), "/") + quoteAbsolutePath(archivePath) ] : [ "--use-compress-program", IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" ]; case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -d --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path30.sep}`, "g"), "/") - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; + return BSD_TAR_ZSTD ? ["zstd -d --force -o", constants_1.TarFilename, quoteAbsolutePath(archivePath)] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; default: return ["-z"]; } @@ -81825,24 +113459,39 @@ var require_tar = __commonJS({ } }); } + function execReadCommands(archivePath, compressionMethod, type) { + return __awaiter2(this, void 0, void 0, function* () { + const { commands, requiresTempDirectory } = yield getCommands(compressionMethod, type, archivePath); + const tempDirectory = requiresTempDirectory ? yield utils.createTempDirectory() : void 0; + try { + yield execCommands(commands, tempDirectory); + } finally { + if (tempDirectory) { + try { + yield io10.rmRF(tempDirectory); + } catch (error3) { + core29.debug(`Failed to delete temporary tar directory: ${error3}`); + } + } + } + }); + } function listTar(archivePath, compressionMethod) { return __awaiter2(this, void 0, void 0, function* () { - const commands = yield getCommands(compressionMethod, "list", archivePath); - yield execCommands(commands); + yield execReadCommands(archivePath, compressionMethod, "list"); }); } function extractTar3(archivePath, compressionMethod) { return __awaiter2(this, void 0, void 0, function* () { const workingDirectory = getWorkingDirectory(); - yield io9.mkdirP(workingDirectory); - const commands = yield getCommands(compressionMethod, "extract", archivePath); - yield execCommands(commands); + yield io10.mkdirP(workingDirectory); + yield execReadCommands(archivePath, compressionMethod, "extract"); }); } function createTar(archiveFolder, sourceDirectories, compressionMethod) { return __awaiter2(this, void 0, void 0, function* () { (0, fs_1.writeFileSync)(path30.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); - const commands = yield getCommands(compressionMethod, "create"); + const { commands } = yield getCommands(compressionMethod, "create"); yield execCommands(commands, archiveFolder); }); } @@ -81850,7 +113499,7 @@ var require_tar = __commonJS({ }); // node_modules/@actions/cache/lib/cache.js -var require_cache4 = __commonJS({ +var require_cache6 = __commonJS({ "node_modules/@actions/cache/lib/cache.js"(exports2) { "use strict"; var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { @@ -81892,11 +113541,11 @@ var require_cache4 = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -81912,7 +113561,7 @@ var require_cache4 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -81922,7 +113571,7 @@ var require_cache4 = __commonJS({ exports2.isFeatureAvailable = isFeatureAvailable; exports2.restoreCache = restoreCache5; exports2.saveCache = saveCache5; - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); var path30 = __importStar2(require("path")); var utils = __importStar2(require_cacheUtils()); var cacheHttpClient = __importStar2(require_cacheHttpClient()); @@ -82000,12 +113649,12 @@ var require_cache4 = __commonJS({ function restoreCache5(paths_1, primaryKey_1, restoreKeys_1, options_1) { return __awaiter2(this, arguments, void 0, function* (paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core31.debug(`Cache service version: ${cacheServiceVersion}`); + core29.debug(`Cache service version: ${cacheServiceVersion}`); checkPaths(paths); const cacheMode = (0, config_1.getCacheMode)(); if (!(0, config_1.isCacheReadable)(cacheMode)) { - core31.info(`Cache restore skipped: the effective cache-mode '${cacheMode}' does not permit reads.`); - core31.debug(`Skipped restore for paths [${paths.join(", ")}] with primary key '${primaryKey}'.`); + core29.info(`Cache restore skipped: the effective cache-mode '${cacheMode}' does not permit reads.`); + core29.debug(`Skipped restore for paths [${paths.join(", ")}] with primary key '${primaryKey}'.`); return void 0; } switch (cacheServiceVersion) { @@ -82019,11 +113668,11 @@ var require_cache4 = __commonJS({ } function restoreCacheV1(paths_1, primaryKey_1, restoreKeys_1, options_1) { return __awaiter2(this, arguments, void 0, function* (paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { - var _a2; + var _a6; restoreKeys = restoreKeys || []; const keys = [primaryKey, ...restoreKeys]; - core31.debug("Resolved Keys:"); - core31.debug(JSON.stringify(keys)); + core29.debug("Resolved Keys:"); + core29.debug(JSON.stringify(keys)); if (keys.length > 10) { throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); } @@ -82040,7 +113689,7 @@ var require_cache4 = __commonJS({ enableCrossOsArchive }); } catch (error3) { - const errorMessage = (_a2 = error3 === null || error3 === void 0 ? void 0 : error3.message) !== null && _a2 !== void 0 ? _a2 : ""; + const errorMessage = (_a6 = error3 === null || error3 === void 0 ? void 0 : error3.message) !== null && _a6 !== void 0 ? _a6 : ""; if (errorMessage.includes(exports2.CACHE_READ_DENIED_PREFIX)) { throw new CacheReadDeniedError(errorMessage); } @@ -82050,19 +113699,19 @@ var require_cache4 = __commonJS({ return void 0; } if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core31.info("Lookup only - skipping download"); + core29.info("Lookup only - skipping download"); return cacheEntry.cacheKey; } archivePath = path30.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core31.debug(`Archive Path: ${archivePath}`); + core29.debug(`Archive Path: ${archivePath}`); yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); - if (core31.isDebug()) { + if (core29.isDebug()) { yield (0, tar_1.listTar)(archivePath, compressionMethod); } const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core31.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + core29.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core31.info("Cache restored successfully"); + core29.info("Cache restored successfully"); return cacheEntry.cacheKey; } catch (error3) { const typedError = error3; @@ -82070,16 +113719,16 @@ var require_cache4 = __commonJS({ throw error3; } else { if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core31.error(`Failed to restore: ${error3.message}`); + core29.error(`Failed to restore: ${error3.message}`); } else { - core31.warning(`Failed to restore: ${error3.message}`); + core29.warning(`Failed to restore: ${error3.message}`); } } } finally { try { yield utils.unlinkFile(archivePath); } catch (error3) { - core31.debug(`Failed to delete archive: ${error3}`); + core29.debug(`Failed to delete archive: ${error3}`); } } return void 0; @@ -82087,12 +113736,12 @@ var require_cache4 = __commonJS({ } function restoreCacheV2(paths_1, primaryKey_1, restoreKeys_1, options_1) { return __awaiter2(this, arguments, void 0, function* (paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { - var _a2; + var _a6; options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); restoreKeys = restoreKeys || []; const keys = [primaryKey, ...restoreKeys]; - core31.debug("Resolved Keys:"); - core31.debug(JSON.stringify(keys)); + core29.debug("Resolved Keys:"); + core29.debug(JSON.stringify(keys)); if (keys.length > 10) { throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); } @@ -82112,37 +113761,37 @@ var require_cache4 = __commonJS({ try { response = yield twirpClient.GetCacheEntryDownloadURL(request3); } catch (error3) { - const errorMessage = (_a2 = error3 === null || error3 === void 0 ? void 0 : error3.message) !== null && _a2 !== void 0 ? _a2 : ""; + const errorMessage = (_a6 = error3 === null || error3 === void 0 ? void 0 : error3.message) !== null && _a6 !== void 0 ? _a6 : ""; if (errorMessage.includes(exports2.CACHE_READ_DENIED_PREFIX)) { throw new CacheReadDeniedError(errorMessage); } throw error3; } if (!response.ok) { - core31.debug(`Cache not found for version ${request3.version} of keys: ${keys.join(", ")}`); + core29.debug(`Cache not found for version ${request3.version} of keys: ${keys.join(", ")}`); return void 0; } const isRestoreKeyMatch = request3.key !== response.matchedKey; if (isRestoreKeyMatch) { - core31.info(`Cache hit for restore-key: ${response.matchedKey}`); + core29.info(`Cache hit for restore-key: ${response.matchedKey}`); } else { - core31.info(`Cache hit for: ${response.matchedKey}`); + core29.info(`Cache hit for: ${response.matchedKey}`); } if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core31.info("Lookup only - skipping download"); + core29.info("Lookup only - skipping download"); return response.matchedKey; } archivePath = path30.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core31.debug(`Archive path: ${archivePath}`); - core31.debug(`Starting download of archive to: ${archivePath}`); + core29.debug(`Archive path: ${archivePath}`); + core29.debug(`Starting download of archive to: ${archivePath}`); yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core31.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - if (core31.isDebug()) { + core29.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + if (core29.isDebug()) { yield (0, tar_1.listTar)(archivePath, compressionMethod); } yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core31.info("Cache restored successfully"); + core29.info("Cache restored successfully"); return response.matchedKey; } catch (error3) { const typedError = error3; @@ -82150,9 +113799,9 @@ var require_cache4 = __commonJS({ throw error3; } else { if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core31.error(`Failed to restore: ${error3.message}`); + core29.error(`Failed to restore: ${error3.message}`); } else { - core31.warning(`Failed to restore: ${error3.message}`); + core29.warning(`Failed to restore: ${error3.message}`); } } } finally { @@ -82161,7 +113810,7 @@ var require_cache4 = __commonJS({ yield utils.unlinkFile(archivePath); } } catch (error3) { - core31.debug(`Failed to delete archive: ${error3}`); + core29.debug(`Failed to delete archive: ${error3}`); } } return void 0; @@ -82170,13 +113819,13 @@ var require_cache4 = __commonJS({ function saveCache5(paths_1, key_1, options_1) { return __awaiter2(this, arguments, void 0, function* (paths, key, options, enableCrossOsArchive = false) { const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core31.debug(`Cache service version: ${cacheServiceVersion}`); + core29.debug(`Cache service version: ${cacheServiceVersion}`); checkPaths(paths); checkKey(key); const cacheMode = (0, config_1.getCacheMode)(); if (!(0, config_1.isCacheWritable)(cacheMode)) { - core31.info(`Cache save skipped: the effective cache-mode '${cacheMode}' does not permit writes.`); - core31.debug(`Skipped save for paths [${paths.join(", ")}] with key '${key}'.`); + core29.info(`Cache save skipped: the effective cache-mode '${cacheMode}' does not permit writes.`); + core29.debug(`Skipped save for paths [${paths.join(", ")}] with key '${key}'.`); return -1; } switch (cacheServiceVersion) { @@ -82190,68 +113839,68 @@ var require_cache4 = __commonJS({ } function saveCacheV1(paths_1, key_1, options_1) { return __awaiter2(this, arguments, void 0, function* (paths, key, options, enableCrossOsArchive = false) { - var _a2, _b, _c, _d, _e; + var _a6, _b2, _c2, _d2, _e2; const compressionMethod = yield utils.getCompressionMethod(); let cacheId = -1; const cachePaths = yield utils.resolvePaths(paths); - core31.debug("Cache Paths:"); - core31.debug(`${JSON.stringify(cachePaths)}`); + core29.debug("Cache Paths:"); + core29.debug(`${JSON.stringify(cachePaths)}`); if (cachePaths.length === 0) { throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); } const archiveFolder = yield utils.createTempDirectory(); const archivePath = path30.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core31.debug(`Archive Path: ${archivePath}`); + core29.debug(`Archive Path: ${archivePath}`); try { yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core31.isDebug()) { + if (core29.isDebug()) { yield (0, tar_1.listTar)(archivePath, compressionMethod); } const fileSizeLimit = 10 * 1024 * 1024 * 1024; const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core31.debug(`File Size: ${archiveFileSize}`); + core29.debug(`File Size: ${archiveFileSize}`); if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); } - core31.debug("Reserving Cache"); + core29.debug("Reserving Cache"); const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { compressionMethod, enableCrossOsArchive, cacheSize: archiveFileSize }); - if ((_a2 = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a2 === void 0 ? void 0 : _a2.cacheId) { - cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; + if ((_a6 = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a6 === void 0 ? void 0 : _a6.cacheId) { + cacheId = (_b2 = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b2 === void 0 ? void 0 : _b2.cacheId; } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { - throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); + throw new Error((_d2 = (_c2 = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c2 === void 0 ? void 0 : _c2.message) !== null && _d2 !== void 0 ? _d2 : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); } else { - const detailMessage = (_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message; + const detailMessage = (_e2 = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e2 === void 0 ? void 0 : _e2.message; if (detailMessage === null || detailMessage === void 0 ? void 0 : detailMessage.startsWith(exports2.CACHE_WRITE_DENIED_PREFIX)) { throw new CacheWriteDeniedError(`Unable to reserve cache with key ${key}. More details: ${detailMessage}`); } throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${detailMessage}`); } - core31.debug(`Saving Cache (ID: ${cacheId})`); + core29.debug(`Saving Cache (ID: ${cacheId})`); yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); } catch (error3) { const typedError = error3; if (typedError.name === ValidationError.name) { throw error3; } else if (typedError.name === CacheWriteDeniedError.name) { - core31.warning(`Failed to save: ${typedError.message}`); + core29.warning(`Failed to save: ${typedError.message}`); } else if (typedError.name === ReserveCacheError2.name) { - core31.info(`Failed to save: ${typedError.message}`); + core29.info(`Failed to save: ${typedError.message}`); } else { if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core31.error(`Failed to save: ${typedError.message}`); + core29.error(`Failed to save: ${typedError.message}`); } else { - core31.warning(`Failed to save: ${typedError.message}`); + core29.warning(`Failed to save: ${typedError.message}`); } } } finally { try { yield utils.unlinkFile(archivePath); } catch (error3) { - core31.debug(`Failed to delete archive: ${error3}`); + core29.debug(`Failed to delete archive: ${error3}`); } } return cacheId; @@ -82259,29 +113908,29 @@ var require_cache4 = __commonJS({ } function saveCacheV2(paths_1, key_1, options_1) { return __awaiter2(this, arguments, void 0, function* (paths, key, options, enableCrossOsArchive = false) { - var _a2; + var _a6; options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); const compressionMethod = yield utils.getCompressionMethod(); const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); let cacheId = -1; const cachePaths = yield utils.resolvePaths(paths); - core31.debug("Cache Paths:"); - core31.debug(`${JSON.stringify(cachePaths)}`); + core29.debug("Cache Paths:"); + core29.debug(`${JSON.stringify(cachePaths)}`); if (cachePaths.length === 0) { throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); } const archiveFolder = yield utils.createTempDirectory(); const archivePath = path30.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core31.debug(`Archive Path: ${archivePath}`); + core29.debug(`Archive Path: ${archivePath}`); try { yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core31.isDebug()) { + if (core29.isDebug()) { yield (0, tar_1.listTar)(archivePath, compressionMethod); } const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core31.debug(`File Size: ${archiveFileSize}`); + core29.debug(`File Size: ${archiveFileSize}`); options.archiveSizeBytes = archiveFileSize; - core31.debug("Reserving Cache"); + core29.debug("Reserving Cache"); const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); const request3 = { key, @@ -82292,20 +113941,20 @@ var require_cache4 = __commonJS({ const response = yield twirpClient.CreateCacheEntry(request3); if (!response.ok) { if (response.message && !response.message.startsWith(exports2.CACHE_WRITE_DENIED_PREFIX)) { - core31.warning(`Cache reservation failed: ${response.message}`); + core29.warning(`Cache reservation failed: ${response.message}`); } throw new Error(response.message || "Response was not ok"); } signedUploadUrl = response.signedUploadUrl; } catch (error3) { - core31.debug(`Failed to reserve cache: ${error3}`); - const errorMessage = (_a2 = error3 === null || error3 === void 0 ? void 0 : error3.message) !== null && _a2 !== void 0 ? _a2 : ""; + core29.debug(`Failed to reserve cache: ${error3}`); + const errorMessage = (_a6 = error3 === null || error3 === void 0 ? void 0 : error3.message) !== null && _a6 !== void 0 ? _a6 : ""; if (errorMessage.startsWith(exports2.CACHE_WRITE_DENIED_PREFIX)) { throw new CacheWriteDeniedError(`Unable to reserve cache with key ${key}. More details: ${errorMessage}`); } throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); } - core31.debug(`Attempting to upload cache located at: ${archivePath}`); + core29.debug(`Attempting to upload cache located at: ${archivePath}`); yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); const finalizeRequest = { key, @@ -82313,7 +113962,7 @@ var require_cache4 = __commonJS({ sizeBytes: `${archiveFileSize}` }; const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); - core31.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); + core29.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); if (!finalizeResponse.ok) { if (finalizeResponse.message) { throw new FinalizeCacheError(finalizeResponse.message); @@ -82326,23 +113975,23 @@ var require_cache4 = __commonJS({ if (typedError.name === ValidationError.name) { throw error3; } else if (typedError.name === CacheWriteDeniedError.name) { - core31.warning(`Failed to save: ${typedError.message}`); + core29.warning(`Failed to save: ${typedError.message}`); } else if (typedError.name === ReserveCacheError2.name) { - core31.info(`Failed to save: ${typedError.message}`); + core29.info(`Failed to save: ${typedError.message}`); } else if (typedError.name === FinalizeCacheError.name) { - core31.warning(typedError.message); + core29.warning(typedError.message); } else { if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core31.error(`Failed to save: ${typedError.message}`); + core29.error(`Failed to save: ${typedError.message}`); } else { - core31.warning(`Failed to save: ${typedError.message}`); + core29.warning(`Failed to save: ${typedError.message}`); } } } finally { try { yield utils.unlinkFile(archivePath); } catch (error3) { - core31.debug(`Failed to delete archive: ${error3}`); + core29.debug(`Failed to delete archive: ${error3}`); } } return cacheId; @@ -82394,11 +114043,11 @@ var require_manifest = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -82414,7 +114063,7 @@ var require_manifest = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -82423,21 +114072,21 @@ var require_manifest = __commonJS({ exports2._findMatch = _findMatch; exports2._getOsVersion = _getOsVersion; exports2._readLinuxVersionFile = _readLinuxVersionFile; - var semver11 = __importStar2(require_semver2()); + var semver13 = __importStar2(require_semver2()); var core_1 = require_core(); - var os7 = require("os"); + var os8 = require("os"); var cp = require("child_process"); - var fs32 = require("fs"); + var fs34 = require("fs"); function _findMatch(versionSpec, stable, candidates, archFilter) { return __awaiter2(this, void 0, void 0, function* () { - const platFilter = os7.platform(); + const platFilter = os8.platform(); let result; let match2; let file; for (const candidate of candidates) { const version = candidate.version; (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); - if (semver11.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { + if (semver13.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { file = candidate.files.find((item) => { (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); let chk = item.arch === archFilter && item.platform === platFilter; @@ -82446,7 +114095,7 @@ var require_manifest = __commonJS({ if (osVersion === item.platform_version) { chk = true; } else { - chk = semver11.satisfies(osVersion, item.platform_version); + chk = semver13.satisfies(osVersion, item.platform_version); } } return chk; @@ -82466,7 +114115,7 @@ var require_manifest = __commonJS({ }); } function _getOsVersion() { - const plat = os7.platform(); + const plat = os8.platform(); let version = ""; if (plat === "darwin") { version = cp.execSync("sw_vers -productVersion").toString(); @@ -82489,10 +114138,10 @@ var require_manifest = __commonJS({ const lsbReleaseFile = "/etc/lsb-release"; const osReleaseFile = "/etc/os-release"; let contents = ""; - if (fs32.existsSync(lsbReleaseFile)) { - contents = fs32.readFileSync(lsbReleaseFile).toString(); - } else if (fs32.existsSync(osReleaseFile)) { - contents = fs32.readFileSync(osReleaseFile).toString(); + if (fs34.existsSync(lsbReleaseFile)) { + contents = fs34.readFileSync(lsbReleaseFile).toString(); + } else if (fs34.existsSync(osReleaseFile)) { + contents = fs34.readFileSync(osReleaseFile).toString(); } return contents; } @@ -82542,11 +114191,11 @@ var require_retry_helper = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -82562,14 +114211,14 @@ var require_retry_helper = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.RetryHelper = void 0; - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); var RetryHelper = class { constructor(maxAttempts, minSeconds, maxSeconds) { if (maxAttempts < 1) { @@ -82592,10 +114241,10 @@ var require_retry_helper = __commonJS({ if (isRetryable && !isRetryable(err)) { throw err; } - core31.info(err.message); + core29.info(err.message); } const seconds = this.getSleepAmount(); - core31.info(`Waiting ${seconds} seconds before trying again`); + core29.info(`Waiting ${seconds} seconds before trying again`); yield this.sleep(seconds); attempt++; } @@ -82607,7 +114256,7 @@ var require_retry_helper = __commonJS({ } sleep(seconds) { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14) => setTimeout(resolve14, seconds * 1e3)); + return new Promise((resolve15) => setTimeout(resolve15, seconds * 1e3)); }); } }; @@ -82658,11 +114307,11 @@ var require_tool_cache = __commonJS({ })(); var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -82678,7 +114327,7 @@ var require_tool_cache = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -82698,17 +114347,17 @@ var require_tool_cache = __commonJS({ exports2.findFromManifest = findFromManifest; exports2.isExplicitVersion = isExplicitVersion; exports2.evaluateVersions = evaluateVersions; - var core31 = __importStar2(require_core()); - var io9 = __importStar2(require_io()); + var core29 = __importStar2(require_core()); + var io10 = __importStar2(require_io()); var crypto3 = __importStar2(require("crypto")); - var fs32 = __importStar2(require("fs")); + var fs34 = __importStar2(require("fs")); var mm = __importStar2(require_manifest()); - var os7 = __importStar2(require("os")); + var os8 = __importStar2(require("os")); var path30 = __importStar2(require("path")); var httpm = __importStar2(require_lib()); - var semver11 = __importStar2(require_semver2()); + var semver13 = __importStar2(require_semver2()); var stream2 = __importStar2(require("stream")); - var util3 = __importStar2(require("util")); + var util4 = __importStar2(require("util")); var assert_1 = require("assert"); var exec_1 = require_exec(); var retry_helper_1 = require_retry_helper(); @@ -82726,9 +114375,9 @@ var require_tool_cache = __commonJS({ function downloadTool3(url2, dest, auth2, headers) { return __awaiter2(this, void 0, void 0, function* () { dest = dest || path30.join(_getTempDirectory(), crypto3.randomUUID()); - yield io9.mkdirP(path30.dirname(dest)); - core31.debug(`Downloading ${url2}`); - core31.debug(`Destination ${dest}`); + yield io10.mkdirP(path30.dirname(dest)); + core29.debug(`Downloading ${url2}`); + core29.debug(`Destination ${dest}`); const maxAttempts = 3; const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); @@ -82747,14 +114396,14 @@ var require_tool_cache = __commonJS({ } function downloadToolAttempt(url2, dest, auth2, headers) { return __awaiter2(this, void 0, void 0, function* () { - if (fs32.existsSync(dest)) { + if (fs34.existsSync(dest)) { throw new Error(`Destination file path ${dest} already exists`); } const http = new httpm.HttpClient(userAgent2, [], { allowRetries: false }); if (auth2) { - core31.debug("set auth"); + core29.debug("set auth"); if (headers === void 0) { headers = {}; } @@ -82763,25 +114412,25 @@ var require_tool_cache = __commonJS({ const response = yield http.get(url2, headers); if (response.message.statusCode !== 200) { const err = new HTTPError2(response.message.statusCode); - core31.debug(`Failed to download from "${url2}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); + core29.debug(`Failed to download from "${url2}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); throw err; } - const pipeline2 = util3.promisify(stream2.pipeline); + const pipeline2 = util4.promisify(stream2.pipeline); const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); const readStream = responseMessageFactory(); let succeeded = false; try { - yield pipeline2(readStream, fs32.createWriteStream(dest)); - core31.debug("download complete"); + yield pipeline2(readStream, fs34.createWriteStream(dest)); + core29.debug("download complete"); succeeded = true; return dest; } finally { if (!succeeded) { - core31.debug("download failed"); + core29.debug("download failed"); try { - yield io9.rmRF(dest); + yield io10.rmRF(dest); } catch (err) { - core31.debug(`Failed to delete '${dest}'. ${err.message}`); + core29.debug(`Failed to delete '${dest}'. ${err.message}`); } } } @@ -82796,7 +114445,7 @@ var require_tool_cache = __commonJS({ process.chdir(dest); if (_7zPath) { try { - const logLevel = core31.isDebug() ? "-bb1" : "-bb0"; + const logLevel = core29.isDebug() ? "-bb1" : "-bb0"; const args = [ "x", // eXtract files with full paths @@ -82834,7 +114483,7 @@ var require_tool_cache = __commonJS({ silent: true }; try { - const powershellPath = yield io9.which("powershell", true); + const powershellPath = yield io10.which("powershell", true); yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); } finally { process.chdir(originalCwd); @@ -82849,7 +114498,7 @@ var require_tool_cache = __commonJS({ throw new Error("parameter 'file' is required"); } dest = yield _createExtractFolder(dest); - core31.debug("Checking tar --version"); + core29.debug("Checking tar --version"); let versionOutput = ""; yield (0, exec_1.exec)("tar --version", [], { ignoreReturnCode: true, @@ -82859,7 +114508,7 @@ var require_tool_cache = __commonJS({ stderr: (data) => versionOutput += data.toString() } }); - core31.debug(versionOutput.trim()); + core29.debug(versionOutput.trim()); const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); let args; if (flags instanceof Array) { @@ -82867,7 +114516,7 @@ var require_tool_cache = __commonJS({ } else { args = [flags]; } - if (core31.isDebug() && !flags.includes("v")) { + if (core29.isDebug() && !flags.includes("v")) { args.push("-v"); } let destArg = dest; @@ -82898,10 +114547,10 @@ var require_tool_cache = __commonJS({ args = [flags]; } args.push("-x", "-C", dest, "-f", file); - if (core31.isDebug()) { + if (core29.isDebug()) { args.push("-v"); } - const xarPath = yield io9.which("xar", true); + const xarPath = yield io10.which("xar", true); yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); return dest; }); @@ -82924,7 +114573,7 @@ var require_tool_cache = __commonJS({ return __awaiter2(this, void 0, void 0, function* () { const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const pwshPath = yield io9.which("pwsh", false); + const pwshPath = yield io10.which("pwsh", false); if (pwshPath) { const pwshCommand = [ `$ErrorActionPreference = 'Stop' ;`, @@ -82941,7 +114590,7 @@ var require_tool_cache = __commonJS({ "-Command", pwshCommand ]; - core31.debug(`Using pwsh at path: ${pwshPath}`); + core29.debug(`Using pwsh at path: ${pwshPath}`); yield (0, exec_1.exec)(`"${pwshPath}"`, args); } else { const powershellCommand = [ @@ -82960,17 +114609,17 @@ var require_tool_cache = __commonJS({ "-Command", powershellCommand ]; - const powershellPath = yield io9.which("powershell", true); - core31.debug(`Using powershell at path: ${powershellPath}`); + const powershellPath = yield io10.which("powershell", true); + core29.debug(`Using powershell at path: ${powershellPath}`); yield (0, exec_1.exec)(`"${powershellPath}"`, args); } }); } function extractZipNix(file, dest) { return __awaiter2(this, void 0, void 0, function* () { - const unzipPath = yield io9.which("unzip", true); + const unzipPath = yield io10.which("unzip", true); const args = [file]; - if (!core31.isDebug()) { + if (!core29.isDebug()) { args.unshift("-q"); } args.unshift("-o"); @@ -82979,17 +114628,17 @@ var require_tool_cache = __commonJS({ } function cacheDir2(sourceDir, tool, version, arch2) { return __awaiter2(this, void 0, void 0, function* () { - version = semver11.clean(version) || version; - arch2 = arch2 || os7.arch(); - core31.debug(`Caching tool ${tool} ${version} ${arch2}`); - core31.debug(`source dir: ${sourceDir}`); - if (!fs32.statSync(sourceDir).isDirectory()) { + version = semver13.clean(version) || version; + arch2 = arch2 || os8.arch(); + core29.debug(`Caching tool ${tool} ${version} ${arch2}`); + core29.debug(`source dir: ${sourceDir}`); + if (!fs34.statSync(sourceDir).isDirectory()) { throw new Error("sourceDir is not a directory"); } const destPath = yield _createToolPath(tool, version, arch2); - for (const itemName of fs32.readdirSync(sourceDir)) { + for (const itemName of fs34.readdirSync(sourceDir)) { const s = path30.join(sourceDir, itemName); - yield io9.cp(s, destPath, { recursive: true }); + yield io10.cp(s, destPath, { recursive: true }); } _completeToolPath(tool, version, arch2); return destPath; @@ -82997,17 +114646,17 @@ var require_tool_cache = __commonJS({ } function cacheFile(sourceFile, targetFile, tool, version, arch2) { return __awaiter2(this, void 0, void 0, function* () { - version = semver11.clean(version) || version; - arch2 = arch2 || os7.arch(); - core31.debug(`Caching tool ${tool} ${version} ${arch2}`); - core31.debug(`source file: ${sourceFile}`); - if (!fs32.statSync(sourceFile).isFile()) { + version = semver13.clean(version) || version; + arch2 = arch2 || os8.arch(); + core29.debug(`Caching tool ${tool} ${version} ${arch2}`); + core29.debug(`source file: ${sourceFile}`); + if (!fs34.statSync(sourceFile).isFile()) { throw new Error("sourceFile is not a file"); } const destFolder = yield _createToolPath(tool, version, arch2); const destPath = path30.join(destFolder, targetFile); - core31.debug(`destination file ${destPath}`); - yield io9.cp(sourceFile, destPath); + core29.debug(`destination file ${destPath}`); + yield io10.cp(sourceFile, destPath); _completeToolPath(tool, version, arch2); return destFolder; }); @@ -83019,7 +114668,7 @@ var require_tool_cache = __commonJS({ if (!versionSpec) { throw new Error("versionSpec parameter is required"); } - arch2 = arch2 || os7.arch(); + arch2 = arch2 || os8.arch(); if (!isExplicitVersion(versionSpec)) { const localVersions = findAllVersions2(toolName, arch2); const match2 = evaluateVersions(localVersions, versionSpec); @@ -83027,28 +114676,28 @@ var require_tool_cache = __commonJS({ } let toolPath = ""; if (versionSpec) { - versionSpec = semver11.clean(versionSpec) || ""; + versionSpec = semver13.clean(versionSpec) || ""; const cachePath = path30.join(_getCacheDirectory(), toolName, versionSpec, arch2); - core31.debug(`checking cache: ${cachePath}`); - if (fs32.existsSync(cachePath) && fs32.existsSync(`${cachePath}.complete`)) { - core31.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); + core29.debug(`checking cache: ${cachePath}`); + if (fs34.existsSync(cachePath) && fs34.existsSync(`${cachePath}.complete`)) { + core29.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); toolPath = cachePath; } else { - core31.debug("not found"); + core29.debug("not found"); } } return toolPath; } function findAllVersions2(toolName, arch2) { const versions = []; - arch2 = arch2 || os7.arch(); + arch2 = arch2 || os8.arch(); const toolPath = path30.join(_getCacheDirectory(), toolName); - if (fs32.existsSync(toolPath)) { - const children = fs32.readdirSync(toolPath); + if (fs34.existsSync(toolPath)) { + const children = fs34.readdirSync(toolPath); for (const child of children) { if (isExplicitVersion(child)) { const fullPath = path30.join(toolPath, child, arch2 || ""); - if (fs32.existsSync(fullPath) && fs32.existsSync(`${fullPath}.complete`)) { + if (fs34.existsSync(fullPath) && fs34.existsSync(`${fullPath}.complete`)) { versions.push(child); } } @@ -83063,7 +114712,7 @@ var require_tool_cache = __commonJS({ const http = new httpm.HttpClient("tool-cache"); const headers = {}; if (auth2) { - core31.debug("set auth"); + core29.debug("set auth"); headers.authorization = auth2; } const response = yield http.getJson(treeUrl, headers); @@ -83083,15 +114732,15 @@ var require_tool_cache = __commonJS({ versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); try { releases = JSON.parse(versionsRaw); - } catch (_a2) { - core31.debug("Invalid json"); + } catch (_a6) { + core29.debug("Invalid json"); } } return releases; }); } function findFromManifest(versionSpec_1, stable_1, manifest_1) { - return __awaiter2(this, arguments, void 0, function* (versionSpec, stable, manifest, archFilter = os7.arch()) { + return __awaiter2(this, arguments, void 0, function* (versionSpec, stable, manifest, archFilter = os8.arch()) { const match2 = yield mm._findMatch(versionSpec, stable, manifest, archFilter); return match2; }); @@ -83101,55 +114750,55 @@ var require_tool_cache = __commonJS({ if (!dest) { dest = path30.join(_getTempDirectory(), crypto3.randomUUID()); } - yield io9.mkdirP(dest); + yield io10.mkdirP(dest); return dest; }); } function _createToolPath(tool, version, arch2) { return __awaiter2(this, void 0, void 0, function* () { - const folderPath = path30.join(_getCacheDirectory(), tool, semver11.clean(version) || version, arch2 || ""); - core31.debug(`destination ${folderPath}`); + const folderPath = path30.join(_getCacheDirectory(), tool, semver13.clean(version) || version, arch2 || ""); + core29.debug(`destination ${folderPath}`); const markerPath = `${folderPath}.complete`; - yield io9.rmRF(folderPath); - yield io9.rmRF(markerPath); - yield io9.mkdirP(folderPath); + yield io10.rmRF(folderPath); + yield io10.rmRF(markerPath); + yield io10.mkdirP(folderPath); return folderPath; }); } function _completeToolPath(tool, version, arch2) { - const folderPath = path30.join(_getCacheDirectory(), tool, semver11.clean(version) || version, arch2 || ""); + const folderPath = path30.join(_getCacheDirectory(), tool, semver13.clean(version) || version, arch2 || ""); const markerPath = `${folderPath}.complete`; - fs32.writeFileSync(markerPath, ""); - core31.debug("finished caching tool"); + fs34.writeFileSync(markerPath, ""); + core29.debug("finished caching tool"); } function isExplicitVersion(versionSpec) { - const c = semver11.clean(versionSpec) || ""; - core31.debug(`isExplicit: ${c}`); - const valid4 = semver11.valid(c) != null; - core31.debug(`explicit? ${valid4}`); + const c = semver13.clean(versionSpec) || ""; + core29.debug(`isExplicit: ${c}`); + const valid4 = semver13.valid(c) != null; + core29.debug(`explicit? ${valid4}`); return valid4; } function evaluateVersions(versions, versionSpec) { let version = ""; - core31.debug(`evaluating ${versions.length} versions`); + core29.debug(`evaluating ${versions.length} versions`); versions = versions.sort((a, b) => { - if (semver11.gt(a, b)) { + if (semver13.gt(a, b)) { return 1; } return -1; }); for (let i = versions.length - 1; i >= 0; i--) { const potential = versions[i]; - const satisfied = semver11.satisfies(potential, versionSpec); + const satisfied = semver13.satisfies(potential, versionSpec); if (satisfied) { version = potential; break; } } if (version) { - core31.debug(`matched: ${version}`); + core29.debug(`matched: ${version}`); } else { - core31.debug("match not found"); + core29.debug("match not found"); } return version; } @@ -83173,41 +114822,6 @@ var require_tool_cache = __commonJS({ } }); -// node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/fast-deep-equal/index.js"(exports2, module2) { - "use strict"; - module2.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0; ) - if (!equal(a[i], b[i])) return false; - return true; - } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0; ) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; - } - return true; - } - return a !== a && b !== b; - }; - } -}); - // node_modules/follow-redirects/debug.js var require_debug3 = __commonJS({ "node_modules/follow-redirects/debug.js"(exports2, module2) { @@ -83241,7 +114855,7 @@ var require_follow_redirects = __commonJS({ (function detectUnsupportedEnvironment() { var looksLikeNode = typeof process !== "undefined"; var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; - var looksLikeV8 = isFunction(Error.captureStackTrace); + var looksLikeV8 = isFunction2(Error.captureStackTrace); if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { console.warn("The follow-redirects package should be excluded from browser builds."); } @@ -83342,7 +114956,7 @@ var require_follow_redirects = __commonJS({ if (!isString3(data) && !isBuffer(data)) { throw new TypeError("data should be a string, Buffer or Uint8Array"); } - if (isFunction(encoding)) { + if (isFunction2(encoding)) { callback = encoding; encoding = null; } @@ -83362,10 +114976,10 @@ var require_follow_redirects = __commonJS({ } }; RedirectableRequest.prototype.end = function(data, encoding, callback) { - if (isFunction(data)) { + if (isFunction2(data)) { callback = data; data = encoding = null; - } else if (isFunction(encoding)) { + } else if (isFunction2(encoding)) { callback = encoding; encoding = null; } @@ -83458,6 +115072,12 @@ var require_follow_redirects = __commonJS({ RedirectableRequest.prototype._sanitizeOptions = function(options) { if (!options.headers) { options.headers = {}; + } else if (Array.isArray(options.headers)) { + var headerList = options.headers; + options.headers = {}; + for (var i = 0; i < headerList.length; i += 2) { + options.headers[headerList[i]] = headerList[i + 1]; + } } if (!isArray2(options.sensitiveHeaders)) { options.sensitiveHeaders = []; @@ -83569,7 +115189,7 @@ var require_follow_redirects = __commonJS({ if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) { removeMatchingHeaders(this._headerFilter, this._options.headers); } - if (isFunction(beforeRedirect)) { + if (isFunction2(beforeRedirect)) { var responseDetails = { headers: response.headers, statusCode @@ -83604,7 +115224,7 @@ var require_follow_redirects = __commonJS({ options = validateUrl(input); input = { protocol }; } - if (isFunction(options)) { + if (isFunction2(options)) { callback = options; options = null; } @@ -83684,7 +115304,7 @@ var require_follow_redirects = __commonJS({ } function createErrorType(code, message, baseClass) { function CustomError(properties) { - if (isFunction(Error.captureStackTrace)) { + if (isFunction2(Error.captureStackTrace)) { Error.captureStackTrace(this, this.constructor); } Object.assign(this, properties || {}); @@ -83722,7 +115342,7 @@ var require_follow_redirects = __commonJS({ function isString3(value) { return typeof value === "string" || value instanceof String; } - function isFunction(value) { + function isFunction2(value) { return typeof value === "function"; } function isBuffer(value) { @@ -83732,7 +115352,7 @@ var require_follow_redirects = __commonJS({ return URL2 && value instanceof URL2; } function escapeRegex(regex) { - return regex.replace(/[\]\\/()*+?.$]/g, "\\$&"); + return regex.replace(/[[\]\\/()*+?.^$|]/g, "\\$&"); } module2.exports = wrap({ http, https: https3 }); module2.exports.wrap = wrap; @@ -88742,14 +120362,14 @@ var require_retention = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getExpiration = void 0; var generated_1 = require_generated(); - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); function getExpiration(retentionDays) { if (!retentionDays) { return void 0; } const maxRetentionDays = getRetentionDays(); if (maxRetentionDays && maxRetentionDays < retentionDays) { - core31.warning(`Retention days cannot be greater than the maximum allowed retention set within the repository. Using ${maxRetentionDays} instead.`); + core29.warning(`Retention days cannot be greater than the maximum allowed retention set within the repository. Using ${maxRetentionDays} instead.`); retentionDays = maxRetentionDays; } const expirationDate = /* @__PURE__ */ new Date(); @@ -89052,7 +120672,7 @@ var require_jwt_decode_cjs = __commonJS({ }); // node_modules/@actions/artifact/lib/internal/shared/util.js -var require_util11 = __commonJS({ +var require_util9 = __commonJS({ "node_modules/@actions/artifact/lib/internal/shared/util.js"(exports2) { "use strict"; var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { @@ -89087,7 +120707,7 @@ var require_util11 = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.maskSecretUrls = exports2.maskSigUrl = exports2.getBackendIdsFromToken = void 0; - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); var config_1 = require_config2(); var jwt_decode_1 = __importDefault2(require_jwt_decode_cjs()); var core_1 = require_core(); @@ -89114,8 +120734,8 @@ var require_util11 = __commonJS({ workflowRunBackendId: scopeParts[1], workflowJobRunBackendId: scopeParts[2] }; - core31.debug(`Workflow Run Backend ID: ${ids.workflowRunBackendId}`); - core31.debug(`Workflow Job Run Backend ID: ${ids.workflowJobRunBackendId}`); + core29.debug(`Workflow Run Backend ID: ${ids.workflowRunBackendId}`); + core29.debug(`Workflow Job Run Backend ID: ${ids.workflowJobRunBackendId}`); return ids; } throw InvalidJwtError; @@ -89158,11 +120778,11 @@ var require_artifact_twirp_client2 = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -89178,7 +120798,7 @@ var require_artifact_twirp_client2 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -89192,7 +120812,7 @@ var require_artifact_twirp_client2 = __commonJS({ var config_1 = require_config2(); var user_agent_1 = require_user_agent2(); var errors_1 = require_errors3(); - var util_1 = require_util11(); + var util_1 = require_util9(); var ArtifactHttpClient = class { constructor(userAgent2, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { this.maxAttempts = 5; @@ -89305,7 +120925,7 @@ var require_artifact_twirp_client2 = __commonJS({ } sleep(milliseconds) { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14) => setTimeout(resolve14, milliseconds)); + return new Promise((resolve15) => setTimeout(resolve15, milliseconds)); }); } getExponentialRetryTimeMilliseconds(attempt) { @@ -89361,15 +120981,15 @@ var require_upload_zip_specification = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getUploadZipSpecification = exports2.validateRootDirectory = void 0; - var fs32 = __importStar2(require("fs")); + var fs34 = __importStar2(require("fs")); var core_1 = require_core(); var path_1 = require("path"); var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation(); function validateRootDirectory(rootDirectory) { - if (!fs32.existsSync(rootDirectory)) { + if (!fs34.existsSync(rootDirectory)) { throw new Error(`The provided rootDirectory ${rootDirectory} does not exist`); } - if (!fs32.statSync(rootDirectory).isDirectory()) { + if (!fs34.statSync(rootDirectory).isDirectory()) { throw new Error(`The provided rootDirectory ${rootDirectory} is not a valid directory`); } (0, core_1.info)(`Root directory input is valid!`); @@ -89380,7 +121000,7 @@ var require_upload_zip_specification = __commonJS({ rootDirectory = (0, path_1.normalize)(rootDirectory); rootDirectory = (0, path_1.resolve)(rootDirectory); for (let file of filesToZip) { - const stats = fs32.lstatSync(file, { throwIfNoEntry: false }); + const stats = fs34.lstatSync(file, { throwIfNoEntry: false }); if (!stats) { throw new Error(`File ${file} does not exist`); } @@ -89446,11 +121066,11 @@ var require_blob_upload = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -89466,7 +121086,7 @@ var require_blob_upload = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -89475,7 +121095,7 @@ var require_blob_upload = __commonJS({ exports2.uploadZipToBlobStorage = void 0; var storage_blob_1 = require_commonjs15(); var config_1 = require_config2(); - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); var crypto3 = __importStar2(require("crypto")); var stream2 = __importStar2(require("stream")); var errors_1 = require_errors3(); @@ -89485,7 +121105,7 @@ var require_blob_upload = __commonJS({ let lastProgressTime = Date.now(); const abortController = new AbortController(); const chunkTimer = (interval) => __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { const timer = setInterval(() => { if (Date.now() - lastProgressTime > interval) { reject(new Error("Upload progress stalled.")); @@ -89493,7 +121113,7 @@ var require_blob_upload = __commonJS({ }, interval); abortController.signal.addEventListener("abort", () => { clearInterval(timer); - resolve14(); + resolve15(); }); }); }); @@ -89501,9 +121121,9 @@ var require_blob_upload = __commonJS({ const bufferSize = (0, config_1.getUploadChunkSize)(); const blobClient = new storage_blob_1.BlobClient(authenticatedUploadURL); const blockBlobClient = blobClient.getBlockBlobClient(); - core31.debug(`Uploading artifact zip to blob storage with maxConcurrency: ${maxConcurrency}, bufferSize: ${bufferSize}`); + core29.debug(`Uploading artifact zip to blob storage with maxConcurrency: ${maxConcurrency}, bufferSize: ${bufferSize}`); const uploadCallback = (progress) => { - core31.info(`Uploaded bytes ${progress.loadedBytes}`); + core29.info(`Uploaded bytes ${progress.loadedBytes}`); uploadByteCount = progress.loadedBytes; lastProgressTime = Date.now(); }; @@ -89517,7 +121137,7 @@ var require_blob_upload = __commonJS({ const hashStream = crypto3.createHash("sha256"); zipUploadStream.pipe(uploadStream); zipUploadStream.pipe(hashStream).setEncoding("hex"); - core31.info("Beginning upload of artifact content to blob storage"); + core29.info("Beginning upload of artifact content to blob storage"); try { yield Promise.race([ blockBlobClient.uploadStream(uploadStream, bufferSize, maxConcurrency, options), @@ -89531,12 +121151,12 @@ var require_blob_upload = __commonJS({ } finally { abortController.abort(); } - core31.info("Finished uploading artifact content to blob storage!"); + core29.info("Finished uploading artifact content to blob storage!"); hashStream.end(); sha256Hash = hashStream.read(); - core31.info(`SHA256 digest of uploaded artifact zip is ${sha256Hash}`); + core29.info(`SHA256 digest of uploaded artifact zip is ${sha256Hash}`); if (uploadByteCount === 0) { - core31.warning(`No data was uploaded to blob storage. Reported upload byte count is 0.`); + core29.warning(`No data was uploaded to blob storage. Reported upload byte count is 0.`); } return { uploadSize: uploadByteCount, @@ -89568,6 +121188,8 @@ var require_brace_expansion2 = __commonJS({ var escPeriod2 = "\0PERIOD" + Math.random() + "\0"; var EXPANSION_MAX2 = 1e5; var EXPANSION_MAX_LENGTH2 = 4e6; + var EXPANSION_MAX_DEPTH2 = 1e3; + var EXPANSION_MAX_REWRITES2 = 1e3; function numeric2(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } @@ -89577,25 +121199,36 @@ var require_brace_expansion2 = __commonJS({ function unescapeBraces2(str) { return str.split(escSlash2).join("\\").split(escOpen2).join("{").split(escClose2).join("}").split(escComma2).join(",").split(escPeriod2).join("."); } + function pushAll2(target, items) { + for (var i = 0; i < items.length; i++) { + target.push(items[i]); + } + } function parseCommaParts2(str) { - if (!str) - return [""]; var parts = []; - var m = balanced2("{", "}", 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 = parseCommaParts2(post); - if (post.length) { - p[p.length - 1] += postParts.shift(); - p.push.apply(p, postParts); - } - parts.push.apply(parts, p); - return parts; + var carry = ""; + for (; ; ) { + var m = balanced2("{", "}", str); + if (!m) { + var tail = str.split(","); + tail[0] = carry + tail[0]; + pushAll2(parts, tail); + return parts; + } + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(","); + p[0] = carry + p[0]; + p[p.length - 1] += "{" + body + "}"; + if (!post.length) { + pushAll2(parts, p); + return parts; + } + carry = p.pop(); + pushAll2(parts, p); + str = post; + } } function expandTop(str, options) { if (!str) @@ -89603,10 +121236,12 @@ var require_brace_expansion2 = __commonJS({ options = options || {}; var max = options.max == null ? EXPANSION_MAX2 : options.max; var maxLength = options.maxLength == null ? EXPANSION_MAX_LENGTH2 : options.maxLength; + var maxDepth = options.maxDepth == null ? EXPANSION_MAX_DEPTH2 : options.maxDepth; + var maxRewrites = options.maxRewrites == null ? EXPANSION_MAX_REWRITES2 : options.maxRewrites; if (str.substr(0, 2) === "{}") { str = "\\{\\}" + str.substr(2); } - return expand3(escapeBraces2(str), max, maxLength, true).map(unescapeBraces2); + return expand3(escapeBraces2(str), max, maxLength, maxDepth, 0, maxRewrites, true).map(unescapeBraces2); } function embrace2(str) { return "{" + str + "}"; @@ -89680,8 +121315,12 @@ var require_brace_expansion2 = __commonJS({ } return N; } - function expand3(str, max, maxLength, isTop) { + function expand3(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { + if (depth > maxDepth) { + return [str]; + } var acc = [""]; + var rewrites = 0; var dropEmpties = false; var firstGroup = true; for (; ; ) { @@ -89709,7 +121348,8 @@ var require_brace_expansion2 = __commonJS({ var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { - if (m.post.match(/,(?!,).*\}/)) { + if (rewrites < maxRewrites && m.post.match(/,(?!,).*\}/)) { + rewrites++; str = m.pre + "{" + m.body + escClose2 + m.post; isTop = true; continue; @@ -89733,7 +121373,7 @@ var require_brace_expansion2 = __commonJS({ } else { var n = parseCommaParts2(m.body); if (n.length === 1 && n[0] !== void 0) { - n = expand3(n[0], max, maxLength, false).map(embrace2); + n = expand3(n[0], max, maxLength, maxDepth, depth + 1, maxRewrites, false).map(embrace2); if (n.length === 1) { acc = combine2( acc, @@ -89757,7 +121397,7 @@ var require_brace_expansion2 = __commonJS({ values = []; var valuesLength = 0; outer: for (var j = 0; j < n.length; j++) { - var expanded = expand3(n[j], max, maxLength, false); + var expanded = expand3(n[j], max, maxLength, maxDepth, depth + 1, maxRewrites, false); for (var k = 0; k < expanded.length; k++) { var v = expanded[k]; if (dropsEmpties && !v) continue; @@ -90435,20 +122075,20 @@ var require_minimatch2 = __commonJS({ var require_readdir_glob = __commonJS({ "node_modules/@actions/artifact/node_modules/readdir-glob/index.js"(exports2, module2) { module2.exports = readdirGlob2; - var fs32 = require("fs"); + var fs34 = require("fs"); var { EventEmitter: EventEmitter2 } = require("events"); var { Minimatch: Minimatch2 } = require_minimatch2(); - var { resolve: resolve14 } = require("path"); + var { resolve: resolve15 } = require("path"); function readdir3(dir, strict) { - return new Promise((resolve15, reject) => { - fs32.readdir(dir, { withFileTypes: true }, (err, files) => { + return new Promise((resolve16, reject) => { + fs34.readdir(dir, { withFileTypes: true }, (err, files) => { if (err) { switch (err.code) { case "ENOTDIR": if (strict) { reject(err); } else { - resolve15([]); + resolve16([]); } break; case "ENOTSUP": @@ -90458,7 +122098,7 @@ var require_readdir_glob = __commonJS({ case "ENAMETOOLONG": // Filename too long case "UNKNOWN": - resolve15([]); + resolve16([]); break; case "ELOOP": // Too many levels of symbolic links @@ -90467,30 +122107,30 @@ var require_readdir_glob = __commonJS({ break; } } else { - resolve15(files); + resolve16(files); } }); }); } function stat2(file, followSymlinks) { - return new Promise((resolve15, reject) => { - const statFunc = followSymlinks ? fs32.stat : fs32.lstat; + return new Promise((resolve16, reject) => { + const statFunc = followSymlinks ? fs34.stat : fs34.lstat; statFunc(file, (err, stats) => { if (err) { switch (err.code) { case "ENOENT": if (followSymlinks) { - resolve15(stat2(file, false)); + resolve16(stat2(file, false)); } else { - resolve15(null); + resolve16(null); } break; default: - resolve15(null); + resolve16(null); break; } } else { - resolve15(stats); + resolve16(stats); } }); }); @@ -90580,7 +122220,7 @@ var require_readdir_glob = __commonJS({ (skip) => new Minimatch2(skip, { dot: true }) ); } - this.iterator = explore2(resolve14(cwd || "."), this.options.follow, this.options.stat, this._shouldSkipDirectory.bind(this)); + this.iterator = explore2(resolve15(cwd || "."), this.options.follow, this.options.stat, this._shouldSkipDirectory.bind(this)); this.paused = false; this.inactive = false; this.aborted = false; @@ -90733,7 +122373,7 @@ var require_async = __commonJS({ function isAsyncGenerator(fn) { return fn[Symbol.toStringTag] === "AsyncGenerator"; } - function isAsyncIterable(obj) { + function isAsyncIterable2(obj) { return typeof obj[Symbol.asyncIterator] === "function"; } function wrapAsync(asyncFn) { @@ -90747,10 +122387,10 @@ var require_async = __commonJS({ if (typeof args[arity - 1] === "function") { return asyncFn.apply(this, args); } - return new Promise((resolve14, reject2) => { + return new Promise((resolve15, reject2) => { args[arity - 1] = (err, ...cbArgs) => { if (err) return reject2(err); - resolve14(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + resolve15(cbArgs.length > 1 ? cbArgs : cbArgs[0]); }; asyncFn.apply(this, args); }); @@ -90904,7 +122544,7 @@ var require_async = __commonJS({ if (isAsyncGenerator(obj)) { return asyncEachOfLimit(obj, limit, iteratee, callback); } - if (isAsyncIterable(obj)) { + if (isAsyncIterable2(obj)) { return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback); } var nextElem = createIterator(obj); @@ -90996,13 +122636,13 @@ var require_async = __commonJS({ var applyEachSeries = applyEach$1(mapSeries$1); const PROMISE_SYMBOL = /* @__PURE__ */ Symbol("promiseCallback"); function promiseCallback() { - let resolve14, reject2; + let resolve15, reject2; function callback(err, ...args) { if (err) return reject2(err); - resolve14(args.length > 1 ? args : args[0]); + resolve15(args.length > 1 ? args : args[0]); } callback[PROMISE_SYMBOL] = new Promise((res, rej) => { - resolve14 = res, reject2 = rej; + resolve15 = res, reject2 = rej; }); return callback; } @@ -91349,8 +122989,8 @@ var require_async = __commonJS({ }); } if (rejectOnError || !callback) { - return new Promise((resolve14, reject2) => { - res = resolve14; + return new Promise((resolve15, reject2) => { + res = resolve15; rej = reject2; }); } @@ -91389,10 +123029,10 @@ var require_async = __commonJS({ } const eventMethod = (name) => (handler2) => { if (!handler2) { - return new Promise((resolve14, reject2) => { + return new Promise((resolve15, reject2) => { once2(name, (err, data) => { if (err) return reject2(err); - resolve14(data); + resolve15(data); }); }); } @@ -92539,54 +124179,54 @@ var require_polyfills = __commonJS({ } var chdir; module2.exports = patch; - function patch(fs32) { + function patch(fs34) { if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs32); - } - if (!fs32.lutimes) { - patchLutimes(fs32); - } - fs32.chown = chownFix(fs32.chown); - fs32.fchown = chownFix(fs32.fchown); - fs32.lchown = chownFix(fs32.lchown); - fs32.chmod = chmodFix(fs32.chmod); - fs32.fchmod = chmodFix(fs32.fchmod); - fs32.lchmod = chmodFix(fs32.lchmod); - fs32.chownSync = chownFixSync(fs32.chownSync); - fs32.fchownSync = chownFixSync(fs32.fchownSync); - fs32.lchownSync = chownFixSync(fs32.lchownSync); - fs32.chmodSync = chmodFixSync(fs32.chmodSync); - fs32.fchmodSync = chmodFixSync(fs32.fchmodSync); - fs32.lchmodSync = chmodFixSync(fs32.lchmodSync); - fs32.stat = statFix(fs32.stat); - fs32.fstat = statFix(fs32.fstat); - fs32.lstat = statFix(fs32.lstat); - fs32.statSync = statFixSync(fs32.statSync); - fs32.fstatSync = statFixSync(fs32.fstatSync); - fs32.lstatSync = statFixSync(fs32.lstatSync); - if (fs32.chmod && !fs32.lchmod) { - fs32.lchmod = function(path30, mode, cb) { + patchLchmod(fs34); + } + if (!fs34.lutimes) { + patchLutimes(fs34); + } + fs34.chown = chownFix(fs34.chown); + fs34.fchown = chownFix(fs34.fchown); + fs34.lchown = chownFix(fs34.lchown); + fs34.chmod = chmodFix(fs34.chmod); + fs34.fchmod = chmodFix(fs34.fchmod); + fs34.lchmod = chmodFix(fs34.lchmod); + fs34.chownSync = chownFixSync(fs34.chownSync); + fs34.fchownSync = chownFixSync(fs34.fchownSync); + fs34.lchownSync = chownFixSync(fs34.lchownSync); + fs34.chmodSync = chmodFixSync(fs34.chmodSync); + fs34.fchmodSync = chmodFixSync(fs34.fchmodSync); + fs34.lchmodSync = chmodFixSync(fs34.lchmodSync); + fs34.stat = statFix(fs34.stat); + fs34.fstat = statFix(fs34.fstat); + fs34.lstat = statFix(fs34.lstat); + fs34.statSync = statFixSync(fs34.statSync); + fs34.fstatSync = statFixSync(fs34.fstatSync); + fs34.lstatSync = statFixSync(fs34.lstatSync); + if (fs34.chmod && !fs34.lchmod) { + fs34.lchmod = function(path30, mode, cb) { if (cb) process.nextTick(cb); }; - fs32.lchmodSync = function() { + fs34.lchmodSync = function() { }; } - if (fs32.chown && !fs32.lchown) { - fs32.lchown = function(path30, uid, gid, cb) { + if (fs34.chown && !fs34.lchown) { + fs34.lchown = function(path30, uid, gid, cb) { if (cb) process.nextTick(cb); }; - fs32.lchownSync = function() { + fs34.lchownSync = function() { }; } if (platform2 === "win32") { - fs32.rename = typeof fs32.rename !== "function" ? fs32.rename : (function(fs$rename) { + fs34.rename = typeof fs34.rename !== "function" ? fs34.rename : (function(fs$rename) { function rename(from, to, cb) { var start = Date.now(); var backoff = 0; fs$rename(from, to, function CB(er) { if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < 6e4) { setTimeout(function() { - fs32.stat(to, function(stater, st) { + fs34.stat(to, function(stater, st) { if (stater && stater.code === "ENOENT") fs$rename(from, to, CB); else @@ -92602,9 +124242,9 @@ var require_polyfills = __commonJS({ } if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename); return rename; - })(fs32.rename); + })(fs34.rename); } - fs32.read = typeof fs32.read !== "function" ? fs32.read : (function(fs$read) { + fs34.read = typeof fs34.read !== "function" ? fs34.read : (function(fs$read) { function read(fd, buffer, offset, length, position, callback_) { var callback; if (callback_ && typeof callback_ === "function") { @@ -92612,22 +124252,22 @@ var require_polyfills = __commonJS({ callback = function(er, _2, __) { if (er && er.code === "EAGAIN" && eagCounter < 10) { eagCounter++; - return fs$read.call(fs32, fd, buffer, offset, length, position, callback); + return fs$read.call(fs34, fd, buffer, offset, length, position, callback); } callback_.apply(this, arguments); }; } - return fs$read.call(fs32, fd, buffer, offset, length, position, callback); + return fs$read.call(fs34, fd, buffer, offset, length, position, callback); } if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read); return read; - })(fs32.read); - fs32.readSync = typeof fs32.readSync !== "function" ? fs32.readSync : /* @__PURE__ */ (function(fs$readSync) { + })(fs34.read); + fs34.readSync = typeof fs34.readSync !== "function" ? fs34.readSync : /* @__PURE__ */ (function(fs$readSync) { return function(fd, buffer, offset, length, position) { var eagCounter = 0; while (true) { try { - return fs$readSync.call(fs32, fd, buffer, offset, length, position); + return fs$readSync.call(fs34, fd, buffer, offset, length, position); } catch (er) { if (er.code === "EAGAIN" && eagCounter < 10) { eagCounter++; @@ -92637,10 +124277,10 @@ var require_polyfills = __commonJS({ } } }; - })(fs32.readSync); - function patchLchmod(fs33) { - fs33.lchmod = function(path30, mode, callback) { - fs33.open( + })(fs34.readSync); + function patchLchmod(fs35) { + fs35.lchmod = function(path30, mode, callback) { + fs35.open( path30, constants.O_WRONLY | constants.O_SYMLINK, mode, @@ -92649,80 +124289,80 @@ var require_polyfills = __commonJS({ if (callback) callback(err); return; } - fs33.fchmod(fd, mode, function(err2) { - fs33.close(fd, function(err22) { + fs35.fchmod(fd, mode, function(err2) { + fs35.close(fd, function(err22) { if (callback) callback(err2 || err22); }); }); } ); }; - fs33.lchmodSync = function(path30, mode) { - var fd = fs33.openSync(path30, constants.O_WRONLY | constants.O_SYMLINK, mode); + fs35.lchmodSync = function(path30, mode) { + var fd = fs35.openSync(path30, constants.O_WRONLY | constants.O_SYMLINK, mode); var threw = true; var ret; try { - ret = fs33.fchmodSync(fd, mode); + ret = fs35.fchmodSync(fd, mode); threw = false; } finally { if (threw) { try { - fs33.closeSync(fd); + fs35.closeSync(fd); } catch (er) { } } else { - fs33.closeSync(fd); + fs35.closeSync(fd); } } return ret; }; } - function patchLutimes(fs33) { - if (constants.hasOwnProperty("O_SYMLINK") && fs33.futimes) { - fs33.lutimes = function(path30, at, mt, cb) { - fs33.open(path30, constants.O_SYMLINK, function(er, fd) { + function patchLutimes(fs35) { + if (constants.hasOwnProperty("O_SYMLINK") && fs35.futimes) { + fs35.lutimes = function(path30, at, mt, cb) { + fs35.open(path30, constants.O_SYMLINK, function(er, fd) { if (er) { if (cb) cb(er); return; } - fs33.futimes(fd, at, mt, function(er2) { - fs33.close(fd, function(er22) { + fs35.futimes(fd, at, mt, function(er2) { + fs35.close(fd, function(er22) { if (cb) cb(er2 || er22); }); }); }); }; - fs33.lutimesSync = function(path30, at, mt) { - var fd = fs33.openSync(path30, constants.O_SYMLINK); + fs35.lutimesSync = function(path30, at, mt) { + var fd = fs35.openSync(path30, constants.O_SYMLINK); var ret; var threw = true; try { - ret = fs33.futimesSync(fd, at, mt); + ret = fs35.futimesSync(fd, at, mt); threw = false; } finally { if (threw) { try { - fs33.closeSync(fd); + fs35.closeSync(fd); } catch (er) { } } else { - fs33.closeSync(fd); + fs35.closeSync(fd); } } return ret; }; - } else if (fs33.futimes) { - fs33.lutimes = function(_a2, _b, _c, cb) { + } else if (fs35.futimes) { + fs35.lutimes = function(_a6, _b2, _c2, cb) { if (cb) process.nextTick(cb); }; - fs33.lutimesSync = function() { + fs35.lutimesSync = function() { }; } } function chmodFix(orig) { if (!orig) return orig; return function(target, mode, cb) { - return orig.call(fs32, target, mode, function(er) { + return orig.call(fs34, target, mode, function(er) { if (chownErOk(er)) er = null; if (cb) cb.apply(this, arguments); }); @@ -92732,7 +124372,7 @@ var require_polyfills = __commonJS({ if (!orig) return orig; return function(target, mode) { try { - return orig.call(fs32, target, mode); + return orig.call(fs34, target, mode); } catch (er) { if (!chownErOk(er)) throw er; } @@ -92741,7 +124381,7 @@ var require_polyfills = __commonJS({ function chownFix(orig) { if (!orig) return orig; return function(target, uid, gid, cb) { - return orig.call(fs32, target, uid, gid, function(er) { + return orig.call(fs34, target, uid, gid, function(er) { if (chownErOk(er)) er = null; if (cb) cb.apply(this, arguments); }); @@ -92751,7 +124391,7 @@ var require_polyfills = __commonJS({ if (!orig) return orig; return function(target, uid, gid) { try { - return orig.call(fs32, target, uid, gid); + return orig.call(fs34, target, uid, gid); } catch (er) { if (!chownErOk(er)) throw er; } @@ -92771,13 +124411,13 @@ var require_polyfills = __commonJS({ } if (cb) cb.apply(this, arguments); } - return options ? orig.call(fs32, target, options, callback) : orig.call(fs32, target, callback); + return options ? orig.call(fs34, target, options, callback) : orig.call(fs34, target, callback); }; } function statFixSync(orig) { if (!orig) return orig; return function(target, options) { - var stats = options ? orig.call(fs32, target, options) : orig.call(fs32, target); + var stats = options ? orig.call(fs34, target, options) : orig.call(fs34, target); if (stats) { if (stats.uid < 0) stats.uid += 4294967296; if (stats.gid < 0) stats.gid += 4294967296; @@ -92806,7 +124446,7 @@ var require_legacy_streams = __commonJS({ "node_modules/graceful-fs/legacy-streams.js"(exports2, module2) { var Stream = require("stream").Stream; module2.exports = legacy; - function legacy(fs32) { + function legacy(fs34) { return { ReadStream, WriteStream @@ -92849,7 +124489,7 @@ var require_legacy_streams = __commonJS({ }); return; } - fs32.open(this.path, this.flags, this.mode, function(err, fd) { + fs34.open(this.path, this.flags, this.mode, function(err, fd) { if (err) { self2.emit("error", err); self2.readable = false; @@ -92888,7 +124528,7 @@ var require_legacy_streams = __commonJS({ this.busy = false; this._queue = []; if (this.fd === null) { - this._open = fs32.open; + this._open = fs34.open; this._queue.push([this._open, this.path, this.flags, this.mode, void 0]); this.flush(); } @@ -92923,11 +124563,11 @@ var require_clone = __commonJS({ // node_modules/graceful-fs/graceful-fs.js var require_graceful_fs = __commonJS({ "node_modules/graceful-fs/graceful-fs.js"(exports2, module2) { - var fs32 = require("fs"); + var fs34 = require("fs"); var polyfills = require_polyfills(); var legacy = require_legacy_streams(); var clone = require_clone(); - var util3 = require("util"); + var util4 = require("util"); var gracefulQueue; var previousSymbol; if (typeof Symbol === "function" && typeof Symbol.for === "function") { @@ -92947,20 +124587,20 @@ var require_graceful_fs = __commonJS({ }); } var debug6 = noop3; - if (util3.debuglog) - debug6 = util3.debuglog("gfs4"); + if (util4.debuglog) + debug6 = util4.debuglog("gfs4"); else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) debug6 = function() { - var m = util3.format.apply(util3, arguments); + var m = util4.format.apply(util4, arguments); m = "GFS4: " + m.split(/\n/).join("\nGFS4: "); console.error(m); }; - if (!fs32[gracefulQueue]) { + if (!fs34[gracefulQueue]) { queue2 = global[gracefulQueue] || []; - publishQueue(fs32, queue2); - fs32.close = (function(fs$close) { + publishQueue(fs34, queue2); + fs34.close = (function(fs$close) { function close(fd, cb) { - return fs$close.call(fs32, fd, function(err) { + return fs$close.call(fs34, fd, function(err) { if (!err) { resetQueue(); } @@ -92972,40 +124612,40 @@ var require_graceful_fs = __commonJS({ value: fs$close }); return close; - })(fs32.close); - fs32.closeSync = (function(fs$closeSync) { + })(fs34.close); + fs34.closeSync = (function(fs$closeSync) { function closeSync(fd) { - fs$closeSync.apply(fs32, arguments); + fs$closeSync.apply(fs34, arguments); resetQueue(); } Object.defineProperty(closeSync, previousSymbol, { value: fs$closeSync }); return closeSync; - })(fs32.closeSync); + })(fs34.closeSync); if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) { process.on("exit", function() { - debug6(fs32[gracefulQueue]); - require("assert").equal(fs32[gracefulQueue].length, 0); + debug6(fs34[gracefulQueue]); + require("assert").equal(fs34[gracefulQueue].length, 0); }); } } var queue2; if (!global[gracefulQueue]) { - publishQueue(global, fs32[gracefulQueue]); - } - module2.exports = patch(clone(fs32)); - if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs32.__patched) { - module2.exports = patch(fs32); - fs32.__patched = true; - } - function patch(fs33) { - polyfills(fs33); - fs33.gracefulify = patch; - fs33.createReadStream = createReadStream4; - fs33.createWriteStream = createWriteStream3; - var fs$readFile = fs33.readFile; - fs33.readFile = readFile; + publishQueue(global, fs34[gracefulQueue]); + } + module2.exports = patch(clone(fs34)); + if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs34.__patched) { + module2.exports = patch(fs34); + fs34.__patched = true; + } + function patch(fs35) { + polyfills(fs35); + fs35.gracefulify = patch; + fs35.createReadStream = createReadStream4; + fs35.createWriteStream = createWriteStream3; + var fs$readFile = fs35.readFile; + fs35.readFile = readFile; function readFile(path30, options, cb) { if (typeof options === "function") cb = options, options = null; @@ -93021,8 +124661,8 @@ var require_graceful_fs = __commonJS({ }); } } - var fs$writeFile = fs33.writeFile; - fs33.writeFile = writeFile; + var fs$writeFile = fs35.writeFile; + fs35.writeFile = writeFile; function writeFile(path30, data, options, cb) { if (typeof options === "function") cb = options, options = null; @@ -93038,9 +124678,9 @@ var require_graceful_fs = __commonJS({ }); } } - var fs$appendFile = fs33.appendFile; + var fs$appendFile = fs35.appendFile; if (fs$appendFile) - fs33.appendFile = appendFile; + fs35.appendFile = appendFile; function appendFile(path30, data, options, cb) { if (typeof options === "function") cb = options, options = null; @@ -93056,9 +124696,9 @@ var require_graceful_fs = __commonJS({ }); } } - var fs$copyFile = fs33.copyFile; + var fs$copyFile = fs35.copyFile; if (fs$copyFile) - fs33.copyFile = copyFile2; + fs35.copyFile = copyFile2; function copyFile2(src, dest, flags, cb) { if (typeof flags === "function") { cb = flags; @@ -93076,8 +124716,8 @@ var require_graceful_fs = __commonJS({ }); } } - var fs$readdir = fs33.readdir; - fs33.readdir = readdir3; + var fs$readdir = fs35.readdir; + fs35.readdir = readdir3; var noReaddirOptionVersions = /^v[0-5]\./; function readdir3(path30, options, cb) { if (typeof options === "function") @@ -93118,21 +124758,21 @@ var require_graceful_fs = __commonJS({ } } if (process.version.substr(0, 4) === "v0.8") { - var legStreams = legacy(fs33); + var legStreams = legacy(fs35); ReadStream = legStreams.ReadStream; WriteStream = legStreams.WriteStream; } - var fs$ReadStream = fs33.ReadStream; + var fs$ReadStream = fs35.ReadStream; if (fs$ReadStream) { ReadStream.prototype = Object.create(fs$ReadStream.prototype); ReadStream.prototype.open = ReadStream$open; } - var fs$WriteStream = fs33.WriteStream; + var fs$WriteStream = fs35.WriteStream; if (fs$WriteStream) { WriteStream.prototype = Object.create(fs$WriteStream.prototype); WriteStream.prototype.open = WriteStream$open; } - Object.defineProperty(fs33, "ReadStream", { + Object.defineProperty(fs35, "ReadStream", { get: function() { return ReadStream; }, @@ -93142,7 +124782,7 @@ var require_graceful_fs = __commonJS({ enumerable: true, configurable: true }); - Object.defineProperty(fs33, "WriteStream", { + Object.defineProperty(fs35, "WriteStream", { get: function() { return WriteStream; }, @@ -93153,7 +124793,7 @@ var require_graceful_fs = __commonJS({ configurable: true }); var FileReadStream = ReadStream; - Object.defineProperty(fs33, "FileReadStream", { + Object.defineProperty(fs35, "FileReadStream", { get: function() { return FileReadStream; }, @@ -93164,7 +124804,7 @@ var require_graceful_fs = __commonJS({ configurable: true }); var FileWriteStream = WriteStream; - Object.defineProperty(fs33, "FileWriteStream", { + Object.defineProperty(fs35, "FileWriteStream", { get: function() { return FileWriteStream; }, @@ -93213,13 +124853,13 @@ var require_graceful_fs = __commonJS({ }); } function createReadStream4(path30, options) { - return new fs33.ReadStream(path30, options); + return new fs35.ReadStream(path30, options); } function createWriteStream3(path30, options) { - return new fs33.WriteStream(path30, options); + return new fs35.WriteStream(path30, options); } - var fs$open = fs33.open; - fs33.open = open; + var fs$open = fs35.open; + fs35.open = open; function open(path30, flags, mode, cb) { if (typeof mode === "function") cb = mode, mode = null; @@ -93235,20 +124875,20 @@ var require_graceful_fs = __commonJS({ }); } } - return fs33; + return fs35; } function enqueue(elem) { debug6("ENQUEUE", elem[0].name, elem[1]); - fs32[gracefulQueue].push(elem); + fs34[gracefulQueue].push(elem); retry2(); } var retryTimer; function resetQueue() { var now = Date.now(); - for (var i = 0; i < fs32[gracefulQueue].length; ++i) { - if (fs32[gracefulQueue][i].length > 2) { - fs32[gracefulQueue][i][3] = now; - fs32[gracefulQueue][i][4] = now; + for (var i = 0; i < fs34[gracefulQueue].length; ++i) { + if (fs34[gracefulQueue][i].length > 2) { + fs34[gracefulQueue][i][3] = now; + fs34[gracefulQueue][i][4] = now; } } retry2(); @@ -93256,9 +124896,9 @@ var require_graceful_fs = __commonJS({ function retry2() { clearTimeout(retryTimer); retryTimer = void 0; - if (fs32[gracefulQueue].length === 0) + if (fs34[gracefulQueue].length === 0) return; - var elem = fs32[gracefulQueue].shift(); + var elem = fs34[gracefulQueue].shift(); var fn = elem[0]; var args = elem[1]; var err = elem[2]; @@ -93280,7 +124920,7 @@ var require_graceful_fs = __commonJS({ debug6("RETRY", fn.name, args); fn.apply(null, args.concat([startTime])); } else { - fs32[gracefulQueue].push(elem); + fs34[gracefulQueue].push(elem); } } if (retryTimer === void 0) { @@ -93369,33 +125009,33 @@ var require_stream = __commonJS({ var require_safe_buffer = __commonJS({ "node_modules/lazystream/node_modules/safe-buffer/index.js"(exports2, module2) { var buffer = require("buffer"); - var Buffer2 = buffer.Buffer; + var Buffer3 = buffer.Buffer; function copyProps(src, dst) { for (var key in src) { dst[key] = src[key]; } } - if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { + if (Buffer3.from && Buffer3.alloc && Buffer3.allocUnsafe && Buffer3.allocUnsafeSlow) { module2.exports = buffer; } else { copyProps(buffer, exports2); exports2.Buffer = SafeBuffer; } function SafeBuffer(arg, encodingOrOffset, length) { - return Buffer2(arg, encodingOrOffset, length); + return Buffer3(arg, encodingOrOffset, length); } - copyProps(Buffer2, SafeBuffer); + copyProps(Buffer3, SafeBuffer); SafeBuffer.from = function(arg, encodingOrOffset, length) { if (typeof arg === "number") { throw new TypeError("Argument must not be a number"); } - return Buffer2(arg, encodingOrOffset, length); + return Buffer3(arg, encodingOrOffset, length); }; SafeBuffer.alloc = function(size, fill, encoding) { if (typeof size !== "number") { throw new TypeError("Argument must be a number"); } - var buf = Buffer2(size); + var buf = Buffer3(size); if (fill !== void 0) { if (typeof encoding === "string") { buf.fill(fill, encoding); @@ -93411,7 +125051,7 @@ var require_safe_buffer = __commonJS({ if (typeof size !== "number") { throw new TypeError("Argument must be a number"); } - return Buffer2(size); + return Buffer3(size); }; SafeBuffer.allocUnsafeSlow = function(size) { if (typeof size !== "number") { @@ -93423,7 +125063,7 @@ var require_safe_buffer = __commonJS({ }); // node_modules/core-util-is/lib/util.js -var require_util12 = __commonJS({ +var require_util10 = __commonJS({ "node_modules/core-util-is/lib/util.js"(exports2) { function isArray2(arg) { if (Array.isArray) { @@ -93432,10 +125072,10 @@ var require_util12 = __commonJS({ return objectToString(arg) === "[object Array]"; } exports2.isArray = isArray2; - function isBoolean2(arg) { + function isBoolean3(arg) { return typeof arg === "boolean"; } - exports2.isBoolean = isBoolean2; + exports2.isBoolean = isBoolean3; function isNull(arg) { return arg === null; } @@ -93444,10 +125084,10 @@ var require_util12 = __commonJS({ return arg == null; } exports2.isNullOrUndefined = isNullOrUndefined; - function isNumber2(arg) { + function isNumber3(arg) { return typeof arg === "number"; } - exports2.isNumber = isNumber2; + exports2.isNumber = isNumber3; function isString3(arg) { return typeof arg === "string"; } @@ -93464,22 +125104,22 @@ var require_util12 = __commonJS({ return objectToString(re) === "[object RegExp]"; } exports2.isRegExp = isRegExp; - function isObject2(arg) { + function isObject4(arg) { return typeof arg === "object" && arg !== null; } - exports2.isObject = isObject2; + exports2.isObject = isObject4; function isDate(d) { return objectToString(d) === "[object Date]"; } exports2.isDate = isDate; - function isError(e) { + function isError2(e) { return objectToString(e) === "[object Error]" || e instanceof Error; } - exports2.isError = isError; - function isFunction(arg) { + exports2.isError = isError2; + function isFunction2(arg) { return typeof arg === "function"; } - exports2.isFunction = isFunction; + exports2.isFunction = isFunction2; function isPrimitive(arg) { return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || typeof arg === "symbol" || // ES6 symbol typeof arg === "undefined"; @@ -93528,13 +125168,13 @@ var require_inherits_browser = __commonJS({ var require_inherits = __commonJS({ "node_modules/inherits/inherits.js"(exports2, module2) { try { - util3 = require("util"); - if (typeof util3.inherits !== "function") throw ""; - module2.exports = util3.inherits; + util4 = require("util"); + if (typeof util4.inherits !== "function") throw ""; + module2.exports = util4.inherits; } catch (e) { module2.exports = require_inherits_browser(); } - var util3; + var util4; } }); @@ -93542,13 +125182,13 @@ var require_inherits = __commonJS({ var require_BufferList = __commonJS({ "node_modules/lazystream/node_modules/readable-stream/lib/internal/streams/BufferList.js"(exports2, module2) { "use strict"; - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { + function _classCallCheck(instance8, Constructor) { + if (!(instance8 instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var Buffer2 = require_safe_buffer().Buffer; - var util3 = require("util"); + var Buffer3 = require_safe_buffer().Buffer; + var util4 = require("util"); function copyBuffer(src, target, offset) { src.copy(target, offset); } @@ -93594,8 +125234,8 @@ var require_BufferList = __commonJS({ return ret; }; BufferList.prototype.concat = function concat(n) { - if (this.length === 0) return Buffer2.alloc(0); - var ret = Buffer2.allocUnsafe(n >>> 0); + if (this.length === 0) return Buffer3.alloc(0); + var ret = Buffer3.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { @@ -93607,9 +125247,9 @@ var require_BufferList = __commonJS({ }; return BufferList; })(); - if (util3 && util3.inspect && util3.inspect.custom) { - module2.exports.prototype[util3.inspect.custom] = function() { - var obj = util3.inspect({ length: this.length }); + if (util4 && util4.inspect && util4.inspect.custom) { + module2.exports.prototype[util4.inspect.custom] = function() { + var obj = util4.inspect({ length: this.length }); return this.constructor.name + " " + obj; }; } @@ -93707,31 +125347,31 @@ var require_stream_writable = __commonJS({ }; } var asyncWrite = !process.browser && ["v0.10", "v0.9."].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; - var Duplex; + var Duplex4; Writable.WritableState = WritableState; - var util3 = Object.create(require_util12()); - util3.inherits = require_inherits(); + var util4 = Object.create(require_util10()); + util4.inherits = require_inherits(); var internalUtil = { deprecate: require_node2() }; var Stream = require_stream(); - var Buffer2 = require_safe_buffer().Buffer; + var Buffer3 = require_safe_buffer().Buffer; var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { }; function _uint8ArrayToBuffer(chunk) { - return Buffer2.from(chunk); + return Buffer3.from(chunk); } function _isUint8Array(obj) { - return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + return Buffer3.isBuffer(obj) || obj instanceof OurUint8Array; } var destroyImpl = require_destroy(); - util3.inherits(Writable, Stream); + util4.inherits(Writable, Stream); function nop() { } function WritableState(options, stream2) { - Duplex = Duplex || require_stream_duplex(); + Duplex4 = Duplex4 || require_stream_duplex(); options = options || {}; - var isDuplex = stream2 instanceof Duplex; + var isDuplex = stream2 instanceof Duplex4; this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; var hwm = options.highWaterMark; @@ -93803,8 +125443,8 @@ var require_stream_writable = __commonJS({ }; } function Writable(options) { - Duplex = Duplex || require_stream_duplex(); - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + Duplex4 = Duplex4 || require_stream_duplex(); + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex4)) { return new Writable(options); } this._writableState = new WritableState(options, this); @@ -93844,7 +125484,7 @@ var require_stream_writable = __commonJS({ var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); - if (isBuf && !Buffer2.isBuffer(chunk)) { + if (isBuf && !Buffer3.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === "function") { @@ -93880,7 +125520,7 @@ var require_stream_writable = __commonJS({ }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === "string") { - chunk = Buffer2.from(chunk, encoding); + chunk = Buffer3.from(chunk, encoding); } return chunk; } @@ -94144,25 +125784,25 @@ var require_stream_duplex = __commonJS({ } return keys2; }; - module2.exports = Duplex; - var util3 = Object.create(require_util12()); - util3.inherits = require_inherits(); - var Readable3 = require_stream_readable(); + module2.exports = Duplex4; + var util4 = Object.create(require_util10()); + util4.inherits = require_inherits(); + var Readable4 = require_stream_readable(); var Writable = require_stream_writable(); - util3.inherits(Duplex, Readable3); + util4.inherits(Duplex4, Readable4); { keys = objectKeys(Writable.prototype); for (v = 0; v < keys.length; v++) { method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + if (!Duplex4.prototype[method]) Duplex4.prototype[method] = Writable.prototype[method]; } } var keys; var method; var v; - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable3.call(this, options); + function Duplex4(options) { + if (!(this instanceof Duplex4)) return new Duplex4(options); + Readable4.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; @@ -94170,7 +125810,7 @@ var require_stream_duplex = __commonJS({ if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once("end", onend); } - Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { + Object.defineProperty(Duplex4.prototype, "writableHighWaterMark", { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -94186,7 +125826,7 @@ var require_stream_duplex = __commonJS({ function onEndNT(self2) { self2.end(); } - Object.defineProperty(Duplex.prototype, "destroyed", { + Object.defineProperty(Duplex4.prototype, "destroyed", { get: function() { if (this._readableState === void 0 || this._writableState === void 0) { return false; @@ -94201,7 +125841,7 @@ var require_stream_duplex = __commonJS({ this._writableState.destroyed = value; } }); - Duplex.prototype._destroy = function(err, cb) { + Duplex4.prototype._destroy = function(err, cb) { this.push(null); this.end(); pna.nextTick(cb, err); @@ -94213,8 +125853,8 @@ var require_stream_duplex = __commonJS({ var require_string_decoder = __commonJS({ "node_modules/lazystream/node_modules/string_decoder/lib/string_decoder.js"(exports2) { "use strict"; - var Buffer2 = require_safe_buffer().Buffer; - var isEncoding = Buffer2.isEncoding || function(encoding) { + var Buffer3 = require_safe_buffer().Buffer; + var isEncoding = Buffer3.isEncoding || function(encoding) { encoding = "" + encoding; switch (encoding && encoding.toLowerCase()) { case "hex": @@ -94262,7 +125902,7 @@ var require_string_decoder = __commonJS({ } function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); - if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc); + if (typeof nenc !== "string" && (Buffer3.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc); return nenc || enc; } exports2.StringDecoder = StringDecoder; @@ -94291,7 +125931,7 @@ var require_string_decoder = __commonJS({ } this.lastNeed = 0; this.lastTotal = 0; - this.lastChar = Buffer2.allocUnsafe(nb); + this.lastChar = Buffer3.allocUnsafe(nb); } StringDecoder.prototype.write = function(buf) { if (buf.length === 0) return ""; @@ -94452,26 +126092,26 @@ var require_stream_readable = __commonJS({ "node_modules/lazystream/node_modules/readable-stream/lib/_stream_readable.js"(exports2, module2) { "use strict"; var pna = require_process_nextick_args(); - module2.exports = Readable3; + module2.exports = Readable4; var isArray2 = require_isarray(); - var Duplex; - Readable3.ReadableState = ReadableState; + var Duplex4; + Readable4.ReadableState = ReadableState; var EE = require("events").EventEmitter; var EElistenerCount = function(emitter, type) { return emitter.listeners(type).length; }; var Stream = require_stream(); - var Buffer2 = require_safe_buffer().Buffer; + var Buffer3 = require_safe_buffer().Buffer; var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { }; function _uint8ArrayToBuffer(chunk) { - return Buffer2.from(chunk); + return Buffer3.from(chunk); } function _isUint8Array(obj) { - return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + return Buffer3.isBuffer(obj) || obj instanceof OurUint8Array; } - var util3 = Object.create(require_util12()); - util3.inherits = require_inherits(); + var util4 = Object.create(require_util10()); + util4.inherits = require_inherits(); var debugUtil = require("util"); var debug6 = void 0; if (debugUtil && debugUtil.debuglog) { @@ -94483,7 +126123,7 @@ var require_stream_readable = __commonJS({ var BufferList = require_BufferList(); var destroyImpl = require_destroy(); var StringDecoder; - util3.inherits(Readable3, Stream); + util4.inherits(Readable4, Stream); var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; function prependListener(emitter, event, fn) { if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn); @@ -94492,9 +126132,9 @@ var require_stream_readable = __commonJS({ else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream2) { - Duplex = Duplex || require_stream_duplex(); + Duplex4 = Duplex4 || require_stream_duplex(); options = options || {}; - var isDuplex = stream2 instanceof Duplex; + var isDuplex = stream2 instanceof Duplex4; this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; var hwm = options.highWaterMark; @@ -94529,9 +126169,9 @@ var require_stream_readable = __commonJS({ this.encoding = options.encoding; } } - function Readable3(options) { - Duplex = Duplex || require_stream_duplex(); - if (!(this instanceof Readable3)) return new Readable3(options); + function Readable4(options) { + Duplex4 = Duplex4 || require_stream_duplex(); + if (!(this instanceof Readable4)) return new Readable4(options); this._readableState = new ReadableState(options, this); this.readable = true; if (options) { @@ -94540,7 +126180,7 @@ var require_stream_readable = __commonJS({ } Stream.call(this); } - Object.defineProperty(Readable3.prototype, "destroyed", { + Object.defineProperty(Readable4.prototype, "destroyed", { get: function() { if (this._readableState === void 0) { return false; @@ -94554,20 +126194,20 @@ var require_stream_readable = __commonJS({ this._readableState.destroyed = value; } }); - Readable3.prototype.destroy = destroyImpl.destroy; - Readable3.prototype._undestroy = destroyImpl.undestroy; - Readable3.prototype._destroy = function(err, cb) { + Readable4.prototype.destroy = destroyImpl.destroy; + Readable4.prototype._undestroy = destroyImpl.undestroy; + Readable4.prototype._destroy = function(err, cb) { this.push(null); cb(err); }; - Readable3.prototype.push = function(chunk, encoding) { + Readable4.prototype.push = function(chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === "string") { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { - chunk = Buffer2.from(chunk, encoding); + chunk = Buffer3.from(chunk, encoding); encoding = ""; } skipChunkCheck = true; @@ -94577,7 +126217,7 @@ var require_stream_readable = __commonJS({ } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; - Readable3.prototype.unshift = function(chunk) { + Readable4.prototype.unshift = function(chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream2, chunk, encoding, addToFront, skipChunkCheck) { @@ -94591,7 +126231,7 @@ var require_stream_readable = __commonJS({ if (er) { stream2.emit("error", er); } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { + if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer3.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { @@ -94637,10 +126277,10 @@ var require_stream_readable = __commonJS({ function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } - Readable3.prototype.isPaused = function() { + Readable4.prototype.isPaused = function() { return this._readableState.flowing === false; }; - Readable3.prototype.setEncoding = function(enc) { + Readable4.prototype.setEncoding = function(enc) { if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; @@ -94676,7 +126316,7 @@ var require_stream_readable = __commonJS({ } return state.length; } - Readable3.prototype.read = function(n) { + Readable4.prototype.read = function(n) { debug6("read", n); n = parseInt(n, 10); var state = this._readableState; @@ -94771,10 +126411,10 @@ var require_stream_readable = __commonJS({ } state.readingMore = false; } - Readable3.prototype._read = function(n) { + Readable4.prototype._read = function(n) { this.emit("error", new Error("_read() is not implemented")); }; - Readable3.prototype.pipe = function(dest, pipeOpts) { + Readable4.prototype.pipe = function(dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { @@ -94879,7 +126519,7 @@ var require_stream_readable = __commonJS({ } }; } - Readable3.prototype.unpipe = function(dest) { + Readable4.prototype.unpipe = function(dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; if (state.pipesCount === 0) return this; @@ -94911,7 +126551,7 @@ var require_stream_readable = __commonJS({ dest.emit("unpipe", this, unpipeInfo); return this; }; - Readable3.prototype.on = function(ev, fn) { + Readable4.prototype.on = function(ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); if (ev === "data") { if (this._readableState.flowing !== false) this.resume(); @@ -94929,12 +126569,12 @@ var require_stream_readable = __commonJS({ } return res; }; - Readable3.prototype.addListener = Readable3.prototype.on; + Readable4.prototype.addListener = Readable4.prototype.on; function nReadingNextTick(self2) { debug6("readable nexttick read 0"); self2.read(0); } - Readable3.prototype.resume = function() { + Readable4.prototype.resume = function() { var state = this._readableState; if (!state.flowing) { debug6("resume"); @@ -94960,7 +126600,7 @@ var require_stream_readable = __commonJS({ flow(stream2); if (state.flowing && !state.reading) stream2.read(0); } - Readable3.prototype.pause = function() { + Readable4.prototype.pause = function() { debug6("call pause flowing=%j", this._readableState.flowing); if (false !== this._readableState.flowing) { debug6("pause"); @@ -94975,7 +126615,7 @@ var require_stream_readable = __commonJS({ while (state.flowing && stream2.read() !== null) { } } - Readable3.prototype.wrap = function(stream2) { + Readable4.prototype.wrap = function(stream2) { var _this = this; var state = this._readableState; var paused = false; @@ -95019,7 +126659,7 @@ var require_stream_readable = __commonJS({ }; return this; }; - Object.defineProperty(Readable3.prototype, "readableHighWaterMark", { + Object.defineProperty(Readable4.prototype, "readableHighWaterMark", { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -95028,7 +126668,7 @@ var require_stream_readable = __commonJS({ return this._readableState.highWaterMark; } }); - Readable3._fromList = fromList; + Readable4._fromList = fromList; function fromList(n, state) { if (state.length === 0) return null; var ret; @@ -95083,7 +126723,7 @@ var require_stream_readable = __commonJS({ return ret; } function copyFromBuffer(n, list) { - var ret = Buffer2.allocUnsafe(n); + var ret = Buffer3.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); @@ -95138,10 +126778,10 @@ var require_stream_transform = __commonJS({ "node_modules/lazystream/node_modules/readable-stream/lib/_stream_transform.js"(exports2, module2) { "use strict"; module2.exports = Transform5; - var Duplex = require_stream_duplex(); - var util3 = Object.create(require_util12()); - util3.inherits = require_inherits(); - util3.inherits(Transform5, Duplex); + var Duplex4 = require_stream_duplex(); + var util4 = Object.create(require_util10()); + util4.inherits = require_inherits(); + util4.inherits(Transform5, Duplex4); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; @@ -95162,7 +126802,7 @@ var require_stream_transform = __commonJS({ } function Transform5(options) { if (!(this instanceof Transform5)) return new Transform5(options); - Duplex.call(this, options); + Duplex4.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, @@ -95191,7 +126831,7 @@ var require_stream_transform = __commonJS({ } Transform5.prototype.push = function(chunk, encoding) { this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); + return Duplex4.prototype.push.call(this, chunk, encoding); }; Transform5.prototype._transform = function(chunk, encoding, cb) { throw new Error("_transform() is not implemented"); @@ -95217,7 +126857,7 @@ var require_stream_transform = __commonJS({ }; Transform5.prototype._destroy = function(err, cb) { var _this2 = this; - Duplex.prototype._destroy.call(this, err, function(err2) { + Duplex4.prototype._destroy.call(this, err, function(err2) { cb(err2); _this2.emit("close"); }); @@ -95239,9 +126879,9 @@ var require_stream_passthrough = __commonJS({ "use strict"; module2.exports = PassThrough3; var Transform5 = require_stream_transform(); - var util3 = Object.create(require_util12()); - util3.inherits = require_inherits(); - util3.inherits(PassThrough3, Transform5); + var util4 = Object.create(require_util10()); + util4.inherits = require_inherits(); + util4.inherits(PassThrough3, Transform5); function PassThrough3(options) { if (!(this instanceof PassThrough3)) return new PassThrough3(options); Transform5.call(this, options); @@ -95287,24 +126927,24 @@ var require_passthrough = __commonJS({ // node_modules/lazystream/lib/lazystream.js var require_lazystream = __commonJS({ "node_modules/lazystream/lib/lazystream.js"(exports2, module2) { - var util3 = require("util"); + var util4 = require("util"); var PassThrough3 = require_passthrough(); module2.exports = { - Readable: Readable3, + Readable: Readable4, Writable }; - util3.inherits(Readable3, PassThrough3); - util3.inherits(Writable, PassThrough3); - function beforeFirstCall(instance, method, callback) { - instance[method] = function() { - delete instance[method]; + util4.inherits(Readable4, PassThrough3); + util4.inherits(Writable, PassThrough3); + function beforeFirstCall(instance8, method, callback) { + instance8[method] = function() { + delete instance8[method]; callback.apply(this, arguments); return this[method].apply(this, arguments); }; } - function Readable3(fn, options) { - if (!(this instanceof Readable3)) - return new Readable3(fn, options); + function Readable4(fn, options) { + if (!(this instanceof Readable4)) + return new Readable4(fn, options); PassThrough3.call(this, options); beforeFirstCall(this, "_read", function() { var source = fn.call(this, options); @@ -95513,11 +127153,11 @@ var require_baseGetTag = __commonJS({ // node_modules/lodash/isObject.js var require_isObject = __commonJS({ "node_modules/lodash/isObject.js"(exports2, module2) { - function isObject2(value) { + function isObject4(value) { var type = typeof value; return value != null && (type == "object" || type == "function"); } - module2.exports = isObject2; + module2.exports = isObject4; } }); @@ -95525,19 +127165,19 @@ var require_isObject = __commonJS({ var require_isFunction = __commonJS({ "node_modules/lodash/isFunction.js"(exports2, module2) { var baseGetTag = require_baseGetTag(); - var isObject2 = require_isObject(); + var isObject4 = require_isObject(); var asyncTag = "[object AsyncFunction]"; var funcTag = "[object Function]"; var genTag = "[object GeneratorFunction]"; var proxyTag = "[object Proxy]"; - function isFunction(value) { - if (!isObject2(value)) { + function isFunction2(value) { + if (!isObject4(value)) { return false; } var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } - module2.exports = isFunction; + module2.exports = isFunction2; } }); @@ -95590,9 +127230,9 @@ var require_toSource = __commonJS({ // node_modules/lodash/_baseIsNative.js var require_baseIsNative = __commonJS({ "node_modules/lodash/_baseIsNative.js"(exports2, module2) { - var isFunction = require_isFunction(); + var isFunction2 = require_isFunction(); var isMasked = require_isMasked(); - var isObject2 = require_isObject(); + var isObject4 = require_isObject(); var toSource = require_toSource(); var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; var reIsHostCtor = /^\[object .+?Constructor\]$/; @@ -95604,10 +127244,10 @@ var require_baseIsNative = __commonJS({ "^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" ); function baseIsNative(value) { - if (!isObject2(value) || isMasked(value)) { + if (!isObject4(value) || isMasked(value)) { return false; } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + var pattern = isFunction2(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } module2.exports = baseIsNative; @@ -95743,10 +127383,10 @@ var require_isLength = __commonJS({ // node_modules/lodash/isArrayLike.js var require_isArrayLike = __commonJS({ "node_modules/lodash/isArrayLike.js"(exports2, module2) { - var isFunction = require_isFunction(); + var isFunction2 = require_isFunction(); var isLength = require_isLength(); function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); + return value != null && isLength(value.length) && !isFunction2(value); } module2.exports = isArrayLike; } @@ -95772,9 +127412,9 @@ var require_isIterateeCall = __commonJS({ var eq = require_eq2(); var isArrayLike = require_isArrayLike(); var isIndex = require_isIndex(); - var isObject2 = require_isObject(); + var isObject4 = require_isObject(); function isIterateeCall(value, index2, object2) { - if (!isObject2(object2)) { + if (!isObject4(object2)) { return false; } var type = typeof index2; @@ -95867,8 +127507,8 @@ var require_isBuffer = __commonJS({ var freeExports = typeof exports2 == "object" && exports2 && !exports2.nodeType && exports2; var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2; var moduleExports = freeModule && freeModule.exports === freeExports; - var Buffer2 = moduleExports ? root.Buffer : void 0; - var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0; + var Buffer3 = moduleExports ? root.Buffer : void 0; + var nativeIsBuffer = Buffer3 ? Buffer3.isBuffer : void 0; var isBuffer = nativeIsBuffer || stubFalse; module2.exports = isBuffer; } @@ -96019,13 +127659,13 @@ var require_nativeKeysIn = __commonJS({ // node_modules/lodash/_baseKeysIn.js var require_baseKeysIn = __commonJS({ "node_modules/lodash/_baseKeysIn.js"(exports2, module2) { - var isObject2 = require_isObject(); + var isObject4 = require_isObject(); var isPrototype = require_isPrototype(); var nativeKeysIn = require_nativeKeysIn(); var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; function baseKeysIn(object2) { - if (!isObject2(object2)) { + if (!isObject4(object2)) { return nativeKeysIn(object2); } var isProto = isPrototype(object2), result = []; @@ -96138,8 +127778,8 @@ var require_primordials = __commonJS({ FunctionPrototypeCall(fn, thisArgs, ...args) { return fn.call(thisArgs, ...args); }, - FunctionPrototypeSymbolHasInstance(self2, instance) { - return Function.prototype[Symbol.hasInstance].call(self2, instance); + FunctionPrototypeSymbolHasInstance(self2, instance8) { + return Function.prototype[Symbol.hasInstance].call(self2, instance8); }, MathFloor: Math.floor, Number, @@ -96368,7 +128008,7 @@ var require_errors4 = __commonJS({ } return innerError || outerError; } - var AbortError = class extends Error { + var AbortError2 = class extends Error { constructor(message = "The operation was aborted", options = void 0) { if (options !== void 0 && typeof options !== "object") { throw new codes.ERR_INVALID_ARG_TYPE("options", "Object", options); @@ -96571,7 +128211,7 @@ var require_errors4 = __commonJS({ E("ERR_STREAM_WRITE_AFTER_END", "write after end", Error); E("ERR_UNKNOWN_ENCODING", "Unknown encoding: %s", TypeError); module2.exports = { - AbortError, + AbortError: AbortError2, aggregateTwoErrors: hideStackFrames(aggregateTwoErrors), hideStackFrames, codes @@ -96902,7 +128542,7 @@ var require_event_target_shim = __commonJS({ var CAPTURE = 1; var BUBBLE = 2; var ATTRIBUTE = 3; - function isObject2(x) { + function isObject4(x) { return x !== null && typeof x === "object"; } function getListeners(eventTarget) { @@ -96928,7 +128568,7 @@ var require_event_target_shim = __commonJS({ return null; }, set(listener) { - if (typeof listener !== "function" && !isObject2(listener)) { + if (typeof listener !== "function" && !isObject4(listener)) { listener = null; } const listeners = getListeners(this); @@ -97019,11 +128659,11 @@ var require_event_target_shim = __commonJS({ if (listener == null) { return; } - if (typeof listener !== "function" && !isObject2(listener)) { + if (typeof listener !== "function" && !isObject4(listener)) { throw new TypeError("'listener' should be a function or an object."); } const listeners = getListeners(this); - const optionsIsObj = isObject2(options); + const optionsIsObj = isObject4(options); const capture = optionsIsObj ? Boolean(options.capture) : Boolean(options); const listenerType = capture ? CAPTURE : BUBBLE; const newNode = { @@ -97060,7 +128700,7 @@ var require_event_target_shim = __commonJS({ return; } const listeners = getListeners(this); - const capture = isObject2(options) ? Boolean(options.capture) : Boolean(options); + const capture = isObject4(options) ? Boolean(options.capture) : Boolean(options); const listenerType = capture ? CAPTURE : BUBBLE; let prev = null; let node = listeners.get(eventName); @@ -97248,7 +128888,7 @@ var require_abort_controller = __commonJS({ }); // node_modules/readable-stream/lib/ours/util.js -var require_util13 = __commonJS({ +var require_util11 = __commonJS({ "node_modules/readable-stream/lib/ours/util.js"(exports2, module2) { "use strict"; var bufferModule = require("buffer"); @@ -97291,25 +128931,25 @@ var require_util13 = __commonJS({ }; }, createDeferredPromise: function() { - let resolve14; + let resolve15; let reject; const promise = new Promise((res, rej) => { - resolve14 = res; + resolve15 = res; reject = rej; }); return { promise, - resolve: resolve14, + resolve: resolve15, reject }; }, promisify(fn) { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { fn((err, ...args) => { if (err) { return reject(err); } - return resolve14(...args); + return resolve15(...args); }); }); }, @@ -97410,8 +129050,8 @@ var require_validators = __commonJS({ hideStackFrames, codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL } } = require_errors4(); - var { normalizeEncoding } = require_util13(); - var { isAsyncFunction, isArrayBufferView } = require_util13().types; + var { normalizeEncoding } = require_util11(); + var { isAsyncFunction, isArrayBufferView } = require_util11().types; var signals = {}; function isInt32(value) { return value === (value | 0); @@ -97658,7 +129298,7 @@ var require_process = __commonJS({ }); // node_modules/readable-stream/lib/internal/streams/utils.js -var require_utils7 = __commonJS({ +var require_utils8 = __commonJS({ "node_modules/readable-stream/lib/internal/streams/utils.js"(exports2, module2) { "use strict"; var { SymbolAsyncIterator, SymbolIterator, SymbolFor } = require_primordials(); @@ -97669,12 +129309,12 @@ var require_utils7 = __commonJS({ var kIsDisturbed = SymbolFor("nodejs.stream.disturbed"); var kIsClosedPromise = SymbolFor("nodejs.webstream.isClosedPromise"); var kControllerErrorFunction = SymbolFor("nodejs.webstream.controllerErrorFunction"); - function isReadableNodeStream(obj, strict = false) { + function isReadableNodeStream2(obj, strict = false) { var _obj$_readableState; return !!(obj && typeof obj.pipe === "function" && typeof obj.on === "function" && (!strict || typeof obj.pause === "function" && typeof obj.resume === "function") && (!obj._writableState || ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === void 0 ? void 0 : _obj$_readableState.readable) !== false) && // Duplex (!obj._writableState || obj._readableState)); } - function isWritableNodeStream(obj) { + function isWritableNodeStream2(obj) { var _obj$_writableState; return !!(obj && typeof obj.write === "function" && typeof obj.on === "function" && (!obj._readableState || ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === void 0 ? void 0 : _obj$_writableState.writable) !== false)); } @@ -97696,7 +129336,7 @@ var require_utils7 = __commonJS({ function isWebStream(obj) { return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj); } - function isIterable(obj, isAsync) { + function isIterable2(obj, isAsync) { if (obj == null) return false; if (isAsync === true) return typeof obj[SymbolAsyncIterator] === "function"; if (isAsync === false) return typeof obj[SymbolIterator] === "function"; @@ -97710,7 +129350,7 @@ var require_utils7 = __commonJS({ return !!(stream2.destroyed || stream2[kIsDestroyed] || state !== null && state !== void 0 && state.destroyed); } function isWritableEnded(stream2) { - if (!isWritableNodeStream(stream2)) return null; + if (!isWritableNodeStream2(stream2)) return null; if (stream2.writableEnded === true) return true; const wState = stream2._writableState; if (wState !== null && wState !== void 0 && wState.errored) return false; @@ -97718,7 +129358,7 @@ var require_utils7 = __commonJS({ return wState.ended; } function isWritableFinished(stream2, strict) { - if (!isWritableNodeStream(stream2)) return null; + if (!isWritableNodeStream2(stream2)) return null; if (stream2.writableFinished === true) return true; const wState = stream2._writableState; if (wState !== null && wState !== void 0 && wState.errored) return false; @@ -97726,7 +129366,7 @@ var require_utils7 = __commonJS({ return !!(wState.finished || strict === false && wState.ended === true && wState.length === 0); } function isReadableEnded(stream2) { - if (!isReadableNodeStream(stream2)) return null; + if (!isReadableNodeStream2(stream2)) return null; if (stream2.readableEnded === true) return true; const rState = stream2._readableState; if (!rState || rState.errored) return false; @@ -97734,7 +129374,7 @@ var require_utils7 = __commonJS({ return rState.ended; } function isReadableFinished(stream2, strict) { - if (!isReadableNodeStream(stream2)) return null; + if (!isReadableNodeStream2(stream2)) return null; const rState = stream2._readableState; if (rState !== null && rState !== void 0 && rState.errored) return false; if (typeof (rState === null || rState === void 0 ? void 0 : rState.endEmitted) !== "boolean") return null; @@ -97744,13 +129384,13 @@ var require_utils7 = __commonJS({ if (stream2 && stream2[kIsReadable] != null) return stream2[kIsReadable]; if (typeof (stream2 === null || stream2 === void 0 ? void 0 : stream2.readable) !== "boolean") return null; if (isDestroyed(stream2)) return false; - return isReadableNodeStream(stream2) && stream2.readable && !isReadableFinished(stream2); + return isReadableNodeStream2(stream2) && stream2.readable && !isReadableFinished(stream2); } function isWritable(stream2) { if (stream2 && stream2[kIsWritable] != null) return stream2[kIsWritable]; if (typeof (stream2 === null || stream2 === void 0 ? void 0 : stream2.writable) !== "boolean") return null; if (isDestroyed(stream2)) return false; - return isWritableNodeStream(stream2) && stream2.writable && !isWritableEnded(stream2); + return isWritableNodeStream2(stream2) && stream2.writable && !isWritableEnded(stream2); } function isFinished(stream2, opts) { if (!isNodeStream(stream2)) { @@ -97844,8 +129484,8 @@ var require_utils7 = __commonJS({ isClosed, isDuplexNodeStream, isFinished, - isIterable, - isReadableNodeStream, + isIterable: isIterable2, + isReadableNodeStream: isReadableNodeStream2, isReadableStream, isReadableEnded, isReadableFinished, @@ -97853,7 +129493,7 @@ var require_utils7 = __commonJS({ isNodeStream, isWebStream, isWritable, - isWritableNodeStream, + isWritableNodeStream: isWritableNodeStream2, isWritableStream, isWritableEnded, isWritableFinished, @@ -97871,27 +129511,27 @@ var require_end_of_stream = __commonJS({ "node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports2, module2) { "use strict"; var process2 = require_process(); - var { AbortError, codes } = require_errors4(); + var { AbortError: AbortError2, codes } = require_errors4(); var { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes; - var { kEmptyObject, once } = require_util13(); + var { kEmptyObject, once } = require_util11(); var { validateAbortSignal, validateFunction, validateObject, validateBoolean } = require_validators(); var { Promise: Promise2, PromisePrototypeThen, SymbolDispose } = require_primordials(); var { isClosed, isReadable, - isReadableNodeStream, + isReadableNodeStream: isReadableNodeStream2, isReadableStream, isReadableFinished, isReadableErrored, isWritable, - isWritableNodeStream, + isWritableNodeStream: isWritableNodeStream2, isWritableStream, isWritableFinished, isWritableErrored, isNodeStream, willEmitClose: _willEmitClose, kIsClosedPromise - } = require_utils7(); + } = require_utils8(); var addAbortListener; function isRequest(stream2) { return stream2.setHeader && typeof stream2.abort === "function"; @@ -97917,8 +129557,8 @@ var require_end_of_stream = __commonJS({ if (!isNodeStream(stream2)) { throw new ERR_INVALID_ARG_TYPE("stream", ["ReadableStream", "WritableStream", "Stream"], stream2); } - const readable = (_options$readable = options.readable) !== null && _options$readable !== void 0 ? _options$readable : isReadableNodeStream(stream2); - const writable = (_options$writable = options.writable) !== null && _options$writable !== void 0 ? _options$writable : isWritableNodeStream(stream2); + const readable = (_options$readable = options.readable) !== null && _options$readable !== void 0 ? _options$readable : isReadableNodeStream2(stream2); + const writable = (_options$writable = options.writable) !== null && _options$writable !== void 0 ? _options$writable : isWritableNodeStream2(stream2); const wState = stream2._writableState; const rState = stream2._readableState; const onlegacyfinish = () => { @@ -97926,7 +129566,7 @@ var require_end_of_stream = __commonJS({ onfinish(); } }; - let willEmitClose = _willEmitClose(stream2) && isReadableNodeStream(stream2) === readable && isWritableNodeStream(stream2) === writable; + let willEmitClose = _willEmitClose(stream2) && isReadableNodeStream2(stream2) === readable && isWritableNodeStream2(stream2) === writable; let writableFinished = isWritableFinished(stream2, false); const onfinish = () => { writableFinished = true; @@ -97963,7 +129603,7 @@ var require_end_of_stream = __commonJS({ if (errored && typeof errored !== "boolean") { return callback.call(stream2, errored); } - if (readable && !readableFinished && isReadableNodeStream(stream2, true)) { + if (readable && !readableFinished && isReadableNodeStream2(stream2, true)) { if (!isReadableFinished(stream2, false)) return callback.call(stream2, new ERR_STREAM_PREMATURE_CLOSE()); } if (writable && !writableFinished) { @@ -98038,7 +129678,7 @@ var require_end_of_stream = __commonJS({ cleanup(); endCallback.call( stream2, - new AbortError(void 0, { + new AbortError2(void 0, { cause: options.signal.reason }) ); @@ -98046,7 +129686,7 @@ var require_end_of_stream = __commonJS({ if (options.signal.aborted) { process2.nextTick(abort); } else { - addAbortListener = addAbortListener || require_util13().addAbortListener; + addAbortListener = addAbortListener || require_util11().addAbortListener; const disposable = addAbortListener(options.signal, abort); const originalCallback = callback; callback = once((...args) => { @@ -98065,7 +129705,7 @@ var require_end_of_stream = __commonJS({ isAborted = true; callback.call( stream2, - new AbortError(void 0, { + new AbortError2(void 0, { cause: options.signal.reason }) ); @@ -98073,7 +129713,7 @@ var require_end_of_stream = __commonJS({ if (options.signal.aborted) { process2.nextTick(abort); } else { - addAbortListener = addAbortListener || require_util13().addAbortListener; + addAbortListener = addAbortListener || require_util11().addAbortListener; const disposable = addAbortListener(options.signal, abort); const originalCallback = callback; callback = once((...args) => { @@ -98100,7 +129740,7 @@ var require_end_of_stream = __commonJS({ validateBoolean(opts.cleanup, "cleanup"); autoCleanup = opts.cleanup; } - return new Promise2((resolve14, reject) => { + return new Promise2((resolve15, reject) => { const cleanup = eos(stream2, opts, (err) => { if (autoCleanup) { cleanup(); @@ -98108,7 +129748,7 @@ var require_end_of_stream = __commonJS({ if (err) { reject(err); } else { - resolve14(); + resolve15(); } }); }); @@ -98126,10 +129766,10 @@ var require_destroy2 = __commonJS({ var { aggregateTwoErrors, codes: { ERR_MULTIPLE_CALLBACK }, - AbortError + AbortError: AbortError2 } = require_errors4(); var { Symbol: Symbol2 } = require_primordials(); - var { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require_utils7(); + var { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require_utils8(); var kDestroy = Symbol2("kDestroy"); var kConstruct = Symbol2("kConstruct"); function checkError(err, w, r) { @@ -98351,7 +129991,7 @@ var require_destroy2 = __commonJS({ return; } if (!err && !isFinished(stream2)) { - err = new AbortError(); + err = new AbortError2(); } if (isServerRequest(stream2)) { stream2.socket = null; @@ -98466,8 +130106,8 @@ var require_add_abort_signal = __commonJS({ "node_modules/readable-stream/lib/internal/streams/add-abort-signal.js"(exports2, module2) { "use strict"; var { SymbolDispose } = require_primordials(); - var { AbortError, codes } = require_errors4(); - var { isNodeStream, isWebStream, kControllerErrorFunction } = require_utils7(); + var { AbortError: AbortError2, codes } = require_errors4(); + var { isNodeStream, isWebStream, kControllerErrorFunction } = require_utils8(); var eos = require_end_of_stream(); var { ERR_INVALID_ARG_TYPE } = codes; var addAbortListener; @@ -98489,13 +130129,13 @@ var require_add_abort_signal = __commonJS({ } const onAbort = isNodeStream(stream2) ? () => { stream2.destroy( - new AbortError(void 0, { + new AbortError2(void 0, { cause: signal.reason }) ); } : () => { stream2[kControllerErrorFunction]( - new AbortError(void 0, { + new AbortError2(void 0, { cause: signal.reason }) ); @@ -98503,7 +130143,7 @@ var require_add_abort_signal = __commonJS({ if (signal.aborted) { onAbort(); } else { - addAbortListener = addAbortListener || require_util13().addAbortListener; + addAbortListener = addAbortListener || require_util11().addAbortListener; const disposable = addAbortListener(signal, onAbort); eos(stream2, disposable[SymbolDispose]); } @@ -98517,8 +130157,8 @@ var require_buffer_list = __commonJS({ "node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports2, module2) { "use strict"; var { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array: Uint8Array2 } = require_primordials(); - var { Buffer: Buffer2 } = require("buffer"); - var { inspect } = require_util13(); + var { Buffer: Buffer3 } = require("buffer"); + var { inspect } = require_util11(); module2.exports = class BufferList { constructor() { this.head = null; @@ -98564,8 +130204,8 @@ var require_buffer_list = __commonJS({ return ret; } concat(n) { - if (this.length === 0) return Buffer2.alloc(0); - const ret = Buffer2.allocUnsafe(n >>> 0); + if (this.length === 0) return Buffer3.alloc(0); + const ret = Buffer3.allocUnsafe(n >>> 0); let p = this.head; let i = 0; while (p) { @@ -98626,7 +130266,7 @@ var require_buffer_list = __commonJS({ } // Consumes a specified amount of bytes from the buffered data. _getBuffer(n) { - const ret = Buffer2.allocUnsafe(n); + const ret = Buffer3.allocUnsafe(n); const retLen = n; let p = this.head; let c = 0; @@ -98668,7 +130308,7 @@ var require_buffer_list = __commonJS({ }); // node_modules/readable-stream/lib/internal/streams/state.js -var require_state3 = __commonJS({ +var require_state2 = __commonJS({ "node_modules/readable-stream/lib/internal/streams/state.js"(exports2, module2) { "use strict"; var { MathFloor, NumberIsInteger } = require_primordials(); @@ -98713,34 +130353,34 @@ var require_state3 = __commonJS({ var require_safe_buffer2 = __commonJS({ "node_modules/safe-buffer/index.js"(exports2, module2) { var buffer = require("buffer"); - var Buffer2 = buffer.Buffer; + var Buffer3 = buffer.Buffer; function copyProps(src, dst) { for (var key in src) { dst[key] = src[key]; } } - if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { + if (Buffer3.from && Buffer3.alloc && Buffer3.allocUnsafe && Buffer3.allocUnsafeSlow) { module2.exports = buffer; } else { copyProps(buffer, exports2); exports2.Buffer = SafeBuffer; } function SafeBuffer(arg, encodingOrOffset, length) { - return Buffer2(arg, encodingOrOffset, length); + return Buffer3(arg, encodingOrOffset, length); } - SafeBuffer.prototype = Object.create(Buffer2.prototype); - copyProps(Buffer2, SafeBuffer); + SafeBuffer.prototype = Object.create(Buffer3.prototype); + copyProps(Buffer3, SafeBuffer); SafeBuffer.from = function(arg, encodingOrOffset, length) { if (typeof arg === "number") { throw new TypeError("Argument must not be a number"); } - return Buffer2(arg, encodingOrOffset, length); + return Buffer3(arg, encodingOrOffset, length); }; SafeBuffer.alloc = function(size, fill, encoding) { if (typeof size !== "number") { throw new TypeError("Argument must be a number"); } - var buf = Buffer2(size); + var buf = Buffer3(size); if (fill !== void 0) { if (typeof encoding === "string") { buf.fill(fill, encoding); @@ -98756,7 +130396,7 @@ var require_safe_buffer2 = __commonJS({ if (typeof size !== "number") { throw new TypeError("Argument must be a number"); } - return Buffer2(size); + return Buffer3(size); }; SafeBuffer.allocUnsafeSlow = function(size) { if (typeof size !== "number") { @@ -98771,8 +130411,8 @@ var require_safe_buffer2 = __commonJS({ var require_string_decoder2 = __commonJS({ "node_modules/string_decoder/lib/string_decoder.js"(exports2) { "use strict"; - var Buffer2 = require_safe_buffer2().Buffer; - var isEncoding = Buffer2.isEncoding || function(encoding) { + var Buffer3 = require_safe_buffer2().Buffer; + var isEncoding = Buffer3.isEncoding || function(encoding) { encoding = "" + encoding; switch (encoding && encoding.toLowerCase()) { case "hex": @@ -98820,7 +130460,7 @@ var require_string_decoder2 = __commonJS({ } function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); - if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc); + if (typeof nenc !== "string" && (Buffer3.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc); return nenc || enc; } exports2.StringDecoder = StringDecoder; @@ -98849,7 +130489,7 @@ var require_string_decoder2 = __commonJS({ } this.lastNeed = 0; this.lastTotal = 0; - this.lastChar = Buffer2.allocUnsafe(nb); + this.lastChar = Buffer3.allocUnsafe(nb); } StringDecoder.prototype.write = function(buf) { if (buf.length === 0) return ""; @@ -99011,12 +130651,12 @@ var require_from = __commonJS({ "use strict"; var process2 = require_process(); var { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = require_primordials(); - var { Buffer: Buffer2 } = require("buffer"); + var { Buffer: Buffer3 } = require("buffer"); var { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = require_errors4().codes; - function from(Readable3, iterable, opts) { + function from(Readable4, iterable, opts) { let iterator2; - if (typeof iterable === "string" || iterable instanceof Buffer2) { - return new Readable3({ + if (typeof iterable === "string" || iterable instanceof Buffer3) { + return new Readable4({ objectMode: true, ...opts, read() { @@ -99035,7 +130675,7 @@ var require_from = __commonJS({ } else { throw new ERR_INVALID_ARG_TYPE("iterable", ["Iterable"], iterable); } - const readable = new Readable3({ + const readable = new Readable4({ objectMode: true, highWaterMark: 1, // TODO(ronag): What options should be allowed? @@ -99119,19 +130759,19 @@ var require_readable3 = __commonJS({ SymbolAsyncIterator, Symbol: Symbol2 } = require_primordials(); - module2.exports = Readable3; - Readable3.ReadableState = ReadableState; + module2.exports = Readable4; + Readable4.ReadableState = ReadableState; var { EventEmitter: EE } = require("events"); var { Stream, prependListener } = require_legacy(); - var { Buffer: Buffer2 } = require("buffer"); + var { Buffer: Buffer3 } = require("buffer"); var { addAbortSignal } = require_add_abort_signal(); var eos = require_end_of_stream(); - var debug6 = require_util13().debuglog("stream", (fn) => { + var debug6 = require_util11().debuglog("stream", (fn) => { debug6 = fn; }); var BufferList = require_buffer_list(); var destroyImpl = require_destroy2(); - var { getHighWaterMark, getDefaultHighWaterMark } = require_state3(); + var { getHighWaterMark, getDefaultHighWaterMark } = require_state2(); var { aggregateTwoErrors, codes: { @@ -99141,14 +130781,14 @@ var require_readable3 = __commonJS({ ERR_STREAM_PUSH_AFTER_EOF, ERR_STREAM_UNSHIFT_AFTER_END_EVENT }, - AbortError + AbortError: AbortError2 } = require_errors4(); var { validateObject } = require_validators(); var kPaused = Symbol2("kPaused"); var { StringDecoder } = require_string_decoder2(); var from = require_from(); - ObjectSetPrototypeOf(Readable3.prototype, Stream.prototype); - ObjectSetPrototypeOf(Readable3, Stream); + ObjectSetPrototypeOf(Readable4.prototype, Stream.prototype); + ObjectSetPrototypeOf(Readable4, Stream); var nop = () => { }; var { errorOrDestroy } = destroyImpl; @@ -99243,8 +130883,8 @@ var require_readable3 = __commonJS({ this.encoding = options.encoding; } } - function Readable3(options) { - if (!(this instanceof Readable3)) return new Readable3(options); + function Readable4(options) { + if (!(this instanceof Readable4)) return new Readable4(options); const isDuplex = this instanceof require_duplex(); this._readableState = new ReadableState(options, this, isDuplex); if (options) { @@ -99260,26 +130900,26 @@ var require_readable3 = __commonJS({ } }); } - Readable3.prototype.destroy = destroyImpl.destroy; - Readable3.prototype._undestroy = destroyImpl.undestroy; - Readable3.prototype._destroy = function(err, cb) { + Readable4.prototype.destroy = destroyImpl.destroy; + Readable4.prototype._undestroy = destroyImpl.undestroy; + Readable4.prototype._destroy = function(err, cb) { cb(err); }; - Readable3.prototype[EE.captureRejectionSymbol] = function(err) { + Readable4.prototype[EE.captureRejectionSymbol] = function(err) { this.destroy(err); }; - Readable3.prototype[SymbolAsyncDispose] = function() { + Readable4.prototype[SymbolAsyncDispose] = function() { let error3; if (!this.destroyed) { - error3 = this.readableEnded ? null : new AbortError(); + error3 = this.readableEnded ? null : new AbortError2(); this.destroy(error3); } - return new Promise2((resolve14, reject) => eos(this, (err) => err && err !== error3 ? reject(err) : resolve14(null))); + return new Promise2((resolve15, reject) => eos(this, (err) => err && err !== error3 ? reject(err) : resolve15(null))); }; - Readable3.prototype.push = function(chunk, encoding) { + Readable4.prototype.push = function(chunk, encoding) { return readableAddChunk(this, chunk, encoding, false); }; - Readable3.prototype.unshift = function(chunk, encoding) { + Readable4.prototype.unshift = function(chunk, encoding) { return readableAddChunk(this, chunk, encoding, true); }; function readableAddChunk(stream2, chunk, encoding, addToFront) { @@ -99291,13 +130931,13 @@ var require_readable3 = __commonJS({ encoding = encoding || state.defaultEncoding; if (state.encoding !== encoding) { if (addToFront && state.encoding) { - chunk = Buffer2.from(chunk, encoding).toString(state.encoding); + chunk = Buffer3.from(chunk, encoding).toString(state.encoding); } else { - chunk = Buffer2.from(chunk, encoding); + chunk = Buffer3.from(chunk, encoding); encoding = ""; } } - } else if (chunk instanceof Buffer2) { + } else if (chunk instanceof Buffer3) { encoding = ""; } else if (Stream._isUint8Array(chunk)) { chunk = Stream._uint8ArrayToBuffer(chunk); @@ -99353,18 +130993,18 @@ var require_readable3 = __commonJS({ } maybeReadMore(stream2, state); } - Readable3.prototype.isPaused = function() { + Readable4.prototype.isPaused = function() { const state = this._readableState; return state[kPaused] === true || state.flowing === false; }; - Readable3.prototype.setEncoding = function(enc) { - const decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; + Readable4.prototype.setEncoding = function(enc) { + const decoder2 = new StringDecoder(enc); + this._readableState.decoder = decoder2; this._readableState.encoding = this._readableState.decoder.encoding; const buffer = this._readableState.buffer; let content = ""; for (const data of buffer) { - content += decoder.write(data); + content += decoder2.write(data); } buffer.clear(); if (content !== "") buffer.push(content); @@ -99396,7 +131036,7 @@ var require_readable3 = __commonJS({ if (n <= state.length) return n; return state.ended ? state.length : 0; } - Readable3.prototype.read = function(n) { + Readable4.prototype.read = function(n) { debug6("read", n); if (n === void 0) { n = NaN; @@ -99518,10 +131158,10 @@ var require_readable3 = __commonJS({ } state.readingMore = false; } - Readable3.prototype._read = function(n) { + Readable4.prototype._read = function(n) { throw new ERR_METHOD_NOT_IMPLEMENTED("_read()"); }; - Readable3.prototype.pipe = function(dest, pipeOpts) { + Readable4.prototype.pipe = function(dest, pipeOpts) { const src = this; const state = this._readableState; if (state.pipes.length === 1) { @@ -99646,7 +131286,7 @@ var require_readable3 = __commonJS({ } }; } - Readable3.prototype.unpipe = function(dest) { + Readable4.prototype.unpipe = function(dest) { const state = this._readableState; const unpipeInfo = { hasUnpiped: false @@ -99669,7 +131309,7 @@ var require_readable3 = __commonJS({ dest.emit("unpipe", this, unpipeInfo); return this; }; - Readable3.prototype.on = function(ev, fn) { + Readable4.prototype.on = function(ev, fn) { const res = Stream.prototype.on.call(this, ev, fn); const state = this._readableState; if (ev === "data") { @@ -99690,16 +131330,16 @@ var require_readable3 = __commonJS({ } return res; }; - Readable3.prototype.addListener = Readable3.prototype.on; - Readable3.prototype.removeListener = function(ev, fn) { + Readable4.prototype.addListener = Readable4.prototype.on; + Readable4.prototype.removeListener = function(ev, fn) { const res = Stream.prototype.removeListener.call(this, ev, fn); if (ev === "readable") { process2.nextTick(updateReadableListening, this); } return res; }; - Readable3.prototype.off = Readable3.prototype.removeListener; - Readable3.prototype.removeAllListeners = function(ev) { + Readable4.prototype.off = Readable4.prototype.removeListener; + Readable4.prototype.removeAllListeners = function(ev) { const res = Stream.prototype.removeAllListeners.apply(this, arguments); if (ev === "readable" || ev === void 0) { process2.nextTick(updateReadableListening, this); @@ -99721,7 +131361,7 @@ var require_readable3 = __commonJS({ debug6("readable nexttick read 0"); self2.read(0); } - Readable3.prototype.resume = function() { + Readable4.prototype.resume = function() { const state = this._readableState; if (!state.flowing) { debug6("resume"); @@ -99747,7 +131387,7 @@ var require_readable3 = __commonJS({ flow(stream2); if (state.flowing && !state.reading) stream2.read(0); } - Readable3.prototype.pause = function() { + Readable4.prototype.pause = function() { debug6("call pause flowing=%j", this._readableState.flowing); if (this._readableState.flowing !== false) { debug6("pause"); @@ -99762,7 +131402,7 @@ var require_readable3 = __commonJS({ debug6("flow", state.flowing); while (state.flowing && stream2.read() !== null) ; } - Readable3.prototype.wrap = function(stream2) { + Readable4.prototype.wrap = function(stream2) { let paused = false; stream2.on("data", (chunk) => { if (!this.push(chunk) && stream2.pause) { @@ -99797,10 +131437,10 @@ var require_readable3 = __commonJS({ } return this; }; - Readable3.prototype[SymbolAsyncIterator] = function() { + Readable4.prototype[SymbolAsyncIterator] = function() { return streamToAsyncIterator(this); }; - Readable3.prototype.iterator = function(options) { + Readable4.prototype.iterator = function(options) { if (options !== void 0) { validateObject(options, "options"); } @@ -99808,7 +131448,7 @@ var require_readable3 = __commonJS({ }; function streamToAsyncIterator(stream2, options) { if (typeof stream2.read !== "function") { - stream2 = Readable3.wrap(stream2, { + stream2 = Readable4.wrap(stream2, { objectMode: true }); } @@ -99818,12 +131458,12 @@ var require_readable3 = __commonJS({ } async function* createAsyncIterator(stream2, options) { let callback = nop; - function next(resolve14) { + function next(resolve15) { if (this === stream2) { callback(); callback = nop; } else { - callback = resolve14; + callback = resolve15; } } stream2.on("readable", next); @@ -99864,7 +131504,7 @@ var require_readable3 = __commonJS({ } } } - ObjectDefineProperties(Readable3.prototype, { + ObjectDefineProperties(Readable4.prototype, { readable: { __proto__: null, get() { @@ -99991,7 +131631,7 @@ var require_readable3 = __commonJS({ } } }); - Readable3._fromList = fromList; + Readable4._fromList = fromList; function fromList(n, state) { if (state.length === 0) return null; let ret; @@ -100038,23 +131678,23 @@ var require_readable3 = __commonJS({ stream2.end(); } } - Readable3.from = function(iterable, opts) { - return from(Readable3, iterable, opts); + Readable4.from = function(iterable, opts) { + return from(Readable4, iterable, opts); }; var webStreamsAdapters; function lazyWebStreams() { if (webStreamsAdapters === void 0) webStreamsAdapters = {}; return webStreamsAdapters; } - Readable3.fromWeb = function(readableStream, options) { + Readable4.fromWeb = function(readableStream, options) { return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options); }; - Readable3.toWeb = function(streamReadable, options) { + Readable4.toWeb = function(streamReadable, options) { return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options); }; - Readable3.wrap = function(src, options) { + Readable4.wrap = function(src, options) { var _ref, _src$readableObjectMo; - return new Readable3({ + return new Readable4({ objectMode: (_ref = (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== void 0 ? _src$readableObjectMo : src.objectMode) !== null && _ref !== void 0 ? _ref : true, ...options, destroy(err, callback) { @@ -100086,10 +131726,10 @@ var require_writable = __commonJS({ Writable.WritableState = WritableState; var { EventEmitter: EE } = require("events"); var Stream = require_legacy().Stream; - var { Buffer: Buffer2 } = require("buffer"); + var { Buffer: Buffer3 } = require("buffer"); var destroyImpl = require_destroy2(); var { addAbortSignal } = require_add_abort_signal(); - var { getHighWaterMark, getDefaultHighWaterMark } = require_state3(); + var { getHighWaterMark, getDefaultHighWaterMark } = require_state2(); var { ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED, @@ -100196,7 +131836,7 @@ var require_writable = __commonJS({ encoding = state.defaultEncoding; } else { if (!encoding) encoding = state.defaultEncoding; - else if (encoding !== "buffer" && !Buffer2.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding); + else if (encoding !== "buffer" && !Buffer3.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding); if (typeof cb !== "function") cb = nop; } if (chunk === null) { @@ -100204,10 +131844,10 @@ var require_writable = __commonJS({ } else if (!state.objectMode) { if (typeof chunk === "string") { if (state.decodeStrings !== false) { - chunk = Buffer2.from(chunk, encoding); + chunk = Buffer3.from(chunk, encoding); encoding = "buffer"; } - } else if (chunk instanceof Buffer2) { + } else if (chunk instanceof Buffer3) { encoding = "buffer"; } else if (Stream._isUint8Array(chunk)) { chunk = Stream._uint8ArrayToBuffer(chunk); @@ -100245,7 +131885,7 @@ var require_writable = __commonJS({ }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { if (typeof encoding === "string") encoding = StringPrototypeToLowerCase(encoding); - if (!Buffer2.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding); + if (!Buffer3.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding); this._writableState.defaultEncoding = encoding; return this; }; @@ -100695,24 +132335,24 @@ var require_duplexify = __commonJS({ var { isReadable, isWritable, - isIterable, + isIterable: isIterable2, isNodeStream, - isReadableNodeStream, - isWritableNodeStream, + isReadableNodeStream: isReadableNodeStream2, + isWritableNodeStream: isWritableNodeStream2, isDuplexNodeStream, isReadableStream, isWritableStream - } = require_utils7(); + } = require_utils8(); var eos = require_end_of_stream(); var { - AbortError, + AbortError: AbortError2, codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE } } = require_errors4(); var { destroyer } = require_destroy2(); - var Duplex = require_duplex(); - var Readable3 = require_readable3(); + var Duplex4 = require_duplex(); + var Readable4 = require_readable3(); var Writable = require_writable(); - var { createDeferredPromise } = require_util13(); + var { createDeferredPromise } = require_util11(); var from = require_from(); var Blob2 = globalThis.Blob || bufferModule.Blob; var isBlob = typeof Blob2 !== "undefined" ? function isBlob2(b) { @@ -100722,7 +132362,7 @@ var require_duplexify = __commonJS({ }; var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController; var { FunctionPrototypeCall } = require_primordials(); - var Duplexify = class extends Duplex { + var Duplexify = class extends Duplex4 { constructor(options) { super(options); if ((options === null || options === void 0 ? void 0 : options.readable) === false) { @@ -100742,12 +132382,12 @@ var require_duplexify = __commonJS({ if (isDuplexNodeStream(body)) { return body; } - if (isReadableNodeStream(body)) { + if (isReadableNodeStream2(body)) { return _duplexify({ readable: body }); } - if (isWritableNodeStream(body)) { + if (isWritableNodeStream2(body)) { return _duplexify({ writable: body }); @@ -100760,7 +132400,7 @@ var require_duplexify = __commonJS({ } if (isReadableStream(body)) { return _duplexify({ - readable: Readable3.fromWeb(body) + readable: Readable4.fromWeb(body) }); } if (isWritableStream(body)) { @@ -100770,7 +132410,7 @@ var require_duplexify = __commonJS({ } if (typeof body === "function") { const { value, write, final, destroy } = fromAsyncGen(body); - if (isIterable(value)) { + if (isIterable2(value)) { return from(Duplexify, value, { // TODO (ronag): highWaterMark? objectMode: true, @@ -100817,7 +132457,7 @@ var require_duplexify = __commonJS({ if (isBlob(body)) { return duplexify(body.arrayBuffer()); } - if (isIterable(body)) { + if (isIterable2(body)) { return from(Duplexify, body, { // TODO (ronag): highWaterMark? objectMode: true, @@ -100828,8 +132468,8 @@ var require_duplexify = __commonJS({ return Duplexify.fromWeb(body); } if (typeof (body === null || body === void 0 ? void 0 : body.writable) === "object" || typeof (body === null || body === void 0 ? void 0 : body.readable) === "object") { - const readable = body !== null && body !== void 0 && body.readable ? isReadableNodeStream(body === null || body === void 0 ? void 0 : body.readable) ? body === null || body === void 0 ? void 0 : body.readable : duplexify(body.readable) : void 0; - const writable = body !== null && body !== void 0 && body.writable ? isWritableNodeStream(body === null || body === void 0 ? void 0 : body.writable) ? body === null || body === void 0 ? void 0 : body.writable : duplexify(body.writable) : void 0; + const readable = body !== null && body !== void 0 && body.readable ? isReadableNodeStream2(body === null || body === void 0 ? void 0 : body.readable) ? body === null || body === void 0 ? void 0 : body.readable : duplexify(body.readable) : void 0; + const writable = body !== null && body !== void 0 && body.writable ? isWritableNodeStream2(body === null || body === void 0 ? void 0 : body.writable) ? body === null || body === void 0 ? void 0 : body.writable : duplexify(body.writable) : void 0; return _duplexify({ readable, writable @@ -100875,7 +132515,7 @@ var require_duplexify = __commonJS({ ); }; function fromAsyncGen(fn) { - let { promise, resolve: resolve14 } = createDeferredPromise(); + let { promise, resolve: resolve15 } = createDeferredPromise(); const ac = new AbortController2(); const signal = ac.signal; const value = fn( @@ -100887,10 +132527,10 @@ var require_duplexify = __commonJS({ process2.nextTick(cb); if (done) return; if (signal.aborted) - throw new AbortError(void 0, { + throw new AbortError2(void 0, { cause: signal.reason }); - ({ promise, resolve: resolve14 } = createDeferredPromise()); + ({ promise, resolve: resolve15 } = createDeferredPromise()); yield chunk; } })(), @@ -100901,8 +132541,8 @@ var require_duplexify = __commonJS({ return { value, write(chunk, encoding, cb) { - const _resolve = resolve14; - resolve14 = null; + const _resolve = resolve15; + resolve15 = null; _resolve({ chunk, done: false, @@ -100910,8 +132550,8 @@ var require_duplexify = __commonJS({ }); }, final(cb) { - const _resolve = resolve14; - resolve14 = null; + const _resolve = resolve15; + resolve15 = null; _resolve({ done: true, cb @@ -100924,7 +132564,7 @@ var require_duplexify = __commonJS({ }; } function _duplexify(pair) { - const r = pair.readable && typeof pair.readable.read !== "function" ? Readable3.wrap(pair.readable) : pair.readable; + const r = pair.readable && typeof pair.readable.read !== "function" ? Readable4.wrap(pair.readable) : pair.readable; const w = pair.writable; let readable = !!isReadable(r); let writable = !!isWritable(w); @@ -101016,7 +132656,7 @@ var require_duplexify = __commonJS({ } d._destroy = function(err, callback) { if (!err && onclose !== null) { - err = new AbortError(); + err = new AbortError2(); } onreadable = null; ondrain = null; @@ -101044,21 +132684,21 @@ var require_duplex = __commonJS({ ObjectKeys, ObjectSetPrototypeOf } = require_primordials(); - module2.exports = Duplex; - var Readable3 = require_readable3(); + module2.exports = Duplex4; + var Readable4 = require_readable3(); var Writable = require_writable(); - ObjectSetPrototypeOf(Duplex.prototype, Readable3.prototype); - ObjectSetPrototypeOf(Duplex, Readable3); + ObjectSetPrototypeOf(Duplex4.prototype, Readable4.prototype); + ObjectSetPrototypeOf(Duplex4, Readable4); { const keys = ObjectKeys(Writable.prototype); for (let i = 0; i < keys.length; i++) { const method = keys[i]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + if (!Duplex4.prototype[method]) Duplex4.prototype[method] = Writable.prototype[method]; } } - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable3.call(this, options); + function Duplex4(options) { + if (!(this instanceof Duplex4)) return new Duplex4(options); + Readable4.call(this, options); Writable.call(this, options); if (options) { this.allowHalfOpen = options.allowHalfOpen !== false; @@ -101077,7 +132717,7 @@ var require_duplex = __commonJS({ this.allowHalfOpen = true; } } - ObjectDefineProperties(Duplex.prototype, { + ObjectDefineProperties(Duplex4.prototype, { writable: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writable") @@ -101135,14 +132775,14 @@ var require_duplex = __commonJS({ if (webStreamsAdapters === void 0) webStreamsAdapters = {}; return webStreamsAdapters; } - Duplex.fromWeb = function(pair, options) { + Duplex4.fromWeb = function(pair, options) { return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options); }; - Duplex.toWeb = function(duplex) { + Duplex4.toWeb = function(duplex) { return lazyWebStreams().newReadableWritablePairFromDuplex(duplex); }; var duplexify; - Duplex.from = function(body) { + Duplex4.from = function(body) { if (!duplexify) { duplexify = require_duplexify(); } @@ -101158,10 +132798,10 @@ var require_transform = __commonJS({ var { ObjectSetPrototypeOf, Symbol: Symbol2 } = require_primordials(); module2.exports = Transform5; var { ERR_METHOD_NOT_IMPLEMENTED } = require_errors4().codes; - var Duplex = require_duplex(); - var { getHighWaterMark } = require_state3(); - ObjectSetPrototypeOf(Transform5.prototype, Duplex.prototype); - ObjectSetPrototypeOf(Transform5, Duplex); + var Duplex4 = require_duplex(); + var { getHighWaterMark } = require_state2(); + ObjectSetPrototypeOf(Transform5.prototype, Duplex4.prototype); + ObjectSetPrototypeOf(Transform5, Duplex4); var kCallback = Symbol2("kCallback"); function Transform5(options) { if (!(this instanceof Transform5)) return new Transform5(options); @@ -101178,7 +132818,7 @@ var require_transform = __commonJS({ writableHighWaterMark: options.writableHighWaterMark || 0 }; } - Duplex.call(this, options); + Duplex4.call(this, options); this._readableState.sync = false; this[kCallback] = null; if (options) { @@ -101278,9 +132918,9 @@ var require_pipeline4 = __commonJS({ var process2 = require_process(); var { ArrayIsArray, Promise: Promise2, SymbolAsyncIterator, SymbolDispose } = require_primordials(); var eos = require_end_of_stream(); - var { once } = require_util13(); + var { once } = require_util11(); var destroyImpl = require_destroy2(); - var Duplex = require_duplex(); + var Duplex4 = require_duplex(); var { aggregateTwoErrors, codes: { @@ -101290,22 +132930,22 @@ var require_pipeline4 = __commonJS({ ERR_STREAM_DESTROYED, ERR_STREAM_PREMATURE_CLOSE }, - AbortError + AbortError: AbortError2 } = require_errors4(); var { validateFunction, validateAbortSignal } = require_validators(); var { - isIterable, + isIterable: isIterable2, isReadable, - isReadableNodeStream, + isReadableNodeStream: isReadableNodeStream2, isNodeStream, isTransformStream, isWebStream, isReadableStream, isReadableFinished - } = require_utils7(); + } = require_utils8(); var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController; var PassThrough3; - var Readable3; + var Readable4; var addAbortListener; function destroyer(stream2, reading, writing) { let finished = false; @@ -101336,18 +132976,18 @@ var require_pipeline4 = __commonJS({ return streams.pop(); } function makeAsyncIterable(val) { - if (isIterable(val)) { + if (isIterable2(val)) { return val; - } else if (isReadableNodeStream(val)) { + } else if (isReadableNodeStream2(val)) { return fromReadable(val); } throw new ERR_INVALID_ARG_TYPE("val", ["Readable", "Iterable", "AsyncIterable"], val); } async function* fromReadable(val) { - if (!Readable3) { - Readable3 = require_readable3(); + if (!Readable4) { + Readable4 = require_readable3(); } - yield* Readable3.prototype[SymbolAsyncIterator].call(val); + yield* Readable4.prototype[SymbolAsyncIterator].call(val); } async function pumpToNode(iterable, writable, finish, { end }) { let error3; @@ -101362,7 +133002,7 @@ var require_pipeline4 = __commonJS({ callback(); } }; - const wait = () => new Promise2((resolve14, reject) => { + const wait = () => new Promise2((resolve15, reject) => { if (error3) { reject(error3); } else { @@ -101370,7 +133010,7 @@ var require_pipeline4 = __commonJS({ if (error3) { reject(error3); } else { - resolve14(); + resolve15(); } }; } @@ -101445,9 +133085,9 @@ var require_pipeline4 = __commonJS({ const lastStreamCleanup = []; validateAbortSignal(outerSignal, "options.signal"); function abort() { - finishImpl(new AbortError()); + finishImpl(new AbortError2()); } - addAbortListener = addAbortListener || require_util13().addAbortListener; + addAbortListener = addAbortListener || require_util11().addAbortListener; let disposable; if (outerSignal) { disposable = addAbortListener(outerSignal, abort); @@ -101513,13 +133153,13 @@ var require_pipeline4 = __commonJS({ ret = stream2({ signal }); - if (!isIterable(ret)) { + if (!isIterable2(ret)) { throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or Stream", "source", ret); } - } else if (isIterable(stream2) || isReadableNodeStream(stream2) || isTransformStream(stream2)) { + } else if (isIterable2(stream2) || isReadableNodeStream2(stream2) || isTransformStream(stream2)) { ret = stream2; } else { - ret = Duplex.from(stream2); + ret = Duplex4.from(stream2); } } else if (typeof stream2 === "function") { if (isTransformStream(ret)) { @@ -101532,7 +133172,7 @@ var require_pipeline4 = __commonJS({ signal }); if (reading) { - if (!isIterable(ret, true)) { + if (!isIterable2(ret, true)) { throw new ERR_INVALID_RETURN_VALUE("AsyncIterable", `transform[${i - 1}]`, ret); } } else { @@ -101563,7 +133203,7 @@ var require_pipeline4 = __commonJS({ process2.nextTick(finish, err); } ); - } else if (isIterable(ret, true)) { + } else if (isIterable2(ret, true)) { finishCount++; pumpToNode(ret, pt, finish, { end @@ -101585,7 +133225,7 @@ var require_pipeline4 = __commonJS({ } } } else if (isNodeStream(stream2)) { - if (isReadableNodeStream(ret)) { + if (isReadableNodeStream2(ret)) { finishCount += 2; const cleanup = pipe(ret, stream2, finish, { end @@ -101599,7 +133239,7 @@ var require_pipeline4 = __commonJS({ pumpToNode(toRead, stream2, finish, { end }); - } else if (isIterable(ret)) { + } else if (isIterable2(ret)) { finishCount++; pumpToNode(ret, stream2, finish, { end @@ -101613,12 +133253,12 @@ var require_pipeline4 = __commonJS({ } ret = stream2; } else if (isWebStream(stream2)) { - if (isReadableNodeStream(ret)) { + if (isReadableNodeStream2(ret)) { finishCount++; pumpToWeb(makeAsyncIterable(ret), stream2, finish, { end }); - } else if (isReadableStream(ret) || isIterable(ret)) { + } else if (isReadableStream(ret) || isIterable2(ret)) { finishCount++; pumpToWeb(ret, stream2, finish, { end @@ -101637,7 +133277,7 @@ var require_pipeline4 = __commonJS({ } ret = stream2; } else { - ret = Duplex.from(stream2); + ret = Duplex4.from(stream2); } } if (signal !== null && signal !== void 0 && signal.aborted || outerSignal !== null && outerSignal !== void 0 && outerSignal.aborted) { @@ -101705,7 +133345,7 @@ var require_compose = __commonJS({ "node_modules/readable-stream/lib/internal/streams/compose.js"(exports2, module2) { "use strict"; var { pipeline: pipeline2 } = require_pipeline4(); - var Duplex = require_duplex(); + var Duplex4 = require_duplex(); var { destroyer } = require_destroy2(); var { isNodeStream, @@ -101715,9 +133355,9 @@ var require_compose = __commonJS({ isTransformStream, isWritableStream, isReadableStream - } = require_utils7(); + } = require_utils8(); var { - AbortError, + AbortError: AbortError2, codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS } } = require_errors4(); var eos = require_end_of_stream(); @@ -101726,15 +133366,15 @@ var require_compose = __commonJS({ throw new ERR_MISSING_ARGS("streams"); } if (streams.length === 1) { - return Duplex.from(streams[0]); + return Duplex4.from(streams[0]); } const orgStreams = [...streams]; if (typeof streams[0] === "function") { - streams[0] = Duplex.from(streams[0]); + streams[0] = Duplex4.from(streams[0]); } if (typeof streams[streams.length - 1] === "function") { const idx = streams.length - 1; - streams[idx] = Duplex.from(streams[idx]); + streams[idx] = Duplex4.from(streams[idx]); } for (let n = 0; n < streams.length; ++n) { if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) { @@ -101767,7 +133407,7 @@ var require_compose = __commonJS({ const tail = pipeline2(streams, onfinished); const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head)); const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail)); - d = new Duplex({ + d = new Duplex4({ // TODO (ronag): highWaterMark? writableObjectMode: !!(head !== null && head !== void 0 && head.writableObjectMode), readableObjectMode: !!(tail !== null && tail !== void 0 && tail.readableObjectMode), @@ -101874,7 +133514,7 @@ var require_compose = __commonJS({ } d._destroy = function(err, callback) { if (!err && onclose !== null) { - err = new AbortError(); + err = new AbortError2(); } onreadable = null; ondrain = null; @@ -101900,7 +133540,7 @@ var require_operators = __commonJS({ var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController; var { codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE }, - AbortError + AbortError: AbortError2 } = require_errors4(); var { validateAbortSignal, validateInteger, validateObject } = require_validators(); var kWeakHandler = require_primordials().Symbol("kWeak"); @@ -101908,8 +133548,8 @@ var require_operators = __commonJS({ var { finished } = require_end_of_stream(); var staticCompose = require_compose(); var { addAbortSignalNoValidate } = require_add_abort_signal(); - var { isWritable, isNodeStream } = require_utils7(); - var { deprecate } = require_util13(); + var { isWritable, isNodeStream } = require_utils8(); + var { deprecate } = require_util11(); var { ArrayPrototypePush, Boolean: Boolean2, @@ -101962,7 +133602,7 @@ var require_operators = __commonJS({ validateInteger(highWaterMark, "options.highWaterMark", 0); highWaterMark += concurrency; return async function* map2() { - const signal = require_util13().AbortSignalAny( + const signal = require_util11().AbortSignalAny( [options === null || options === void 0 ? void 0 : options.signal].filter(Boolean2) ); const stream2 = this; @@ -101988,14 +133628,14 @@ var require_operators = __commonJS({ resume = null; } } - async function pump() { + async function pump3() { try { for await (let val of stream2) { if (done) { return; } if (signal.aborted) { - throw new AbortError(); + throw new AbortError2(); } try { val = fn(val, signalOpt); @@ -102014,8 +133654,8 @@ var require_operators = __commonJS({ next = null; } if (!done && (queue2.length >= highWaterMark || cnt >= concurrency)) { - await new Promise2((resolve14) => { - resume = resolve14; + await new Promise2((resolve15) => { + resume = resolve15; }); } } @@ -102032,7 +133672,7 @@ var require_operators = __commonJS({ } } } - pump(); + pump3(); try { while (true) { while (queue2.length > 0) { @@ -102041,7 +133681,7 @@ var require_operators = __commonJS({ return; } if (signal.aborted) { - throw new AbortError(); + throw new AbortError2(); } if (val !== kEmpty) { yield val; @@ -102049,8 +133689,8 @@ var require_operators = __commonJS({ queue2.shift(); maybeResume(); } - await new Promise2((resolve14) => { - next = resolve14; + await new Promise2((resolve15) => { + next = resolve15; }); } } finally { @@ -102074,7 +133714,7 @@ var require_operators = __commonJS({ for await (const val of this) { var _options$signal; if (options !== null && options !== void 0 && (_options$signal = options.signal) !== null && _options$signal !== void 0 && _options$signal.aborted) { - throw new AbortError({ + throw new AbortError2({ cause: options.signal.reason }); } @@ -102147,7 +133787,7 @@ var require_operators = __commonJS({ } let hasInitialValue = arguments.length > 1; if (options !== null && options !== void 0 && (_options$signal2 = options.signal) !== null && _options$signal2 !== void 0 && _options$signal2.aborted) { - const err = new AbortError(void 0, { + const err = new AbortError2(void 0, { cause: options.signal.reason }); this.once("error", () => { @@ -102171,7 +133811,7 @@ var require_operators = __commonJS({ var _options$signal3; gotAnyItemFromStream = true; if (options !== null && options !== void 0 && (_options$signal3 = options.signal) !== null && _options$signal3 !== void 0 && _options$signal3.aborted) { - throw new AbortError(); + throw new AbortError2(); } if (!hasInitialValue) { initialValue = value; @@ -102201,7 +133841,7 @@ var require_operators = __commonJS({ for await (const val of this) { var _options$signal4; if (options !== null && options !== void 0 && (_options$signal4 = options.signal) !== null && _options$signal4 !== void 0 && _options$signal4.aborted) { - throw new AbortError(void 0, { + throw new AbortError2(void 0, { cause: options.signal.reason }); } @@ -102238,12 +133878,12 @@ var require_operators = __commonJS({ return async function* drop2() { var _options$signal5; if (options !== null && options !== void 0 && (_options$signal5 = options.signal) !== null && _options$signal5 !== void 0 && _options$signal5.aborted) { - throw new AbortError(); + throw new AbortError2(); } for await (const val of this) { var _options$signal6; if (options !== null && options !== void 0 && (_options$signal6 = options.signal) !== null && _options$signal6 !== void 0 && _options$signal6.aborted) { - throw new AbortError(); + throw new AbortError2(); } if (number2-- <= 0) { yield val; @@ -102262,12 +133902,12 @@ var require_operators = __commonJS({ return async function* take2() { var _options$signal7; if (options !== null && options !== void 0 && (_options$signal7 = options.signal) !== null && _options$signal7 !== void 0 && _options$signal7.aborted) { - throw new AbortError(); + throw new AbortError2(); } for await (const val of this) { var _options$signal8; if (options !== null && options !== void 0 && (_options$signal8 = options.signal) !== null && _options$signal8 !== void 0 && _options$signal8.aborted) { - throw new AbortError(); + throw new AbortError2(); } if (number2-- > 0) { yield val; @@ -102303,16 +133943,16 @@ var require_promises = __commonJS({ "node_modules/readable-stream/lib/stream/promises.js"(exports2, module2) { "use strict"; var { ArrayPrototypePop, Promise: Promise2 } = require_primordials(); - var { isIterable, isNodeStream, isWebStream } = require_utils7(); + var { isIterable: isIterable2, isNodeStream, isWebStream } = require_utils8(); var { pipelineImpl: pl } = require_pipeline4(); var { finished } = require_end_of_stream(); require_stream2(); function pipeline2(...streams) { - return new Promise2((resolve14, reject) => { + return new Promise2((resolve15, reject) => { let signal; let end; const lastArg = streams[streams.length - 1]; - if (lastArg && typeof lastArg === "object" && !isNodeStream(lastArg) && !isIterable(lastArg) && !isWebStream(lastArg)) { + if (lastArg && typeof lastArg === "object" && !isNodeStream(lastArg) && !isIterable2(lastArg) && !isWebStream(lastArg)) { const options = ArrayPrototypePop(streams); signal = options.signal; end = options.end; @@ -102323,7 +133963,7 @@ var require_promises = __commonJS({ if (err) { reject(err); } else { - resolve14(value); + resolve15(value); } }, { @@ -102344,22 +133984,22 @@ var require_promises = __commonJS({ var require_stream2 = __commonJS({ "node_modules/readable-stream/lib/stream.js"(exports2, module2) { "use strict"; - var { Buffer: Buffer2 } = require("buffer"); + var { Buffer: Buffer3 } = require("buffer"); var { ObjectDefineProperty, ObjectKeys, ReflectApply } = require_primordials(); var { promisify: { custom: customPromisify } - } = require_util13(); + } = require_util11(); var { streamReturningOperators, promiseReturningOperators } = require_operators(); var { codes: { ERR_ILLEGAL_CONSTRUCTOR } } = require_errors4(); var compose = require_compose(); - var { setDefaultHighWaterMark, getDefaultHighWaterMark } = require_state3(); + var { setDefaultHighWaterMark, getDefaultHighWaterMark } = require_state2(); var { pipeline: pipeline2 } = require_pipeline4(); var { destroyer } = require_destroy2(); var eos = require_end_of_stream(); - var promises6 = require_promises(); - var utils = require_utils7(); + var promises7 = require_promises(); + var utils = require_utils8(); var Stream = module2.exports = require_legacy().Stream; Stream.isDestroyed = utils.isDestroyed; Stream.isDisturbed = utils.isDisturbed; @@ -102432,21 +134072,21 @@ var require_stream2 = __commonJS({ configurable: true, enumerable: true, get() { - return promises6; + return promises7; } }); ObjectDefineProperty(pipeline2, customPromisify, { __proto__: null, enumerable: true, get() { - return promises6.pipeline; + return promises7.pipeline; } }); ObjectDefineProperty(eos, customPromisify, { __proto__: null, enumerable: true, get() { - return promises6.finished; + return promises7.finished; } }); Stream.Stream = Stream; @@ -102454,7 +134094,7 @@ var require_stream2 = __commonJS({ return value instanceof Uint8Array; }; Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { - return Buffer2.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); + return Buffer3.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); }; } }); @@ -102465,7 +134105,7 @@ var require_ours = __commonJS({ "use strict"; var Stream = require("stream"); if (Stream && process.env.READABLE_STREAM === "disable") { - const promises6 = Stream.promises; + const promises7 = Stream.promises; module2.exports._uint8ArrayToBuffer = Stream._uint8ArrayToBuffer; module2.exports._isUint8Array = Stream._isUint8Array; module2.exports.isDisturbed = Stream.isDisturbed; @@ -102485,13 +134125,13 @@ var require_ours = __commonJS({ configurable: true, enumerable: true, get() { - return promises6; + return promises7; } }); module2.exports.Stream = Stream.Stream; } else { const CustomStream = require_stream2(); - const promises6 = require_promises(); + const promises7 = require_promises(); const originalDestroy = CustomStream.Readable.destroy; module2.exports = CustomStream.Readable; module2.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer; @@ -102514,7 +134154,7 @@ var require_ours = __commonJS({ configurable: true, enumerable: true, get() { - return promises6; + return promises7; } }); module2.exports.Stream = CustomStream.Stream; @@ -102819,8 +134459,8 @@ var require_Map = __commonJS({ "node_modules/lodash/_Map.js"(exports2, module2) { var getNative = require_getNative(); var root = require_root(); - var Map2 = getNative(root, "Map"); - module2.exports = Map2; + var Map3 = getNative(root, "Map"); + module2.exports = Map3; } }); @@ -102829,12 +134469,12 @@ var require_mapCacheClear = __commonJS({ "node_modules/lodash/_mapCacheClear.js"(exports2, module2) { var Hash = require_Hash(); var ListCache = require_ListCache(); - var Map2 = require_Map(); + var Map3 = require_Map(); function mapCacheClear() { this.size = 0; this.__data__ = { "hash": new Hash(), - "map": new (Map2 || ListCache)(), + "map": new (Map3 || ListCache)(), "string": new Hash() }; } @@ -103328,490 +134968,752 @@ var require_isPlainObject = __commonJS({ var require_index_min = __commonJS({ "node_modules/glob/dist/commonjs/index.min.js"(exports2) { "use strict"; - var R = (n, t) => () => (t || n((t = { exports: {} }).exports, t), t.exports); - var Ge = R((Y) => { + var x = (n, t) => () => { + try { + return t || n((t = { exports: {} }).exports, t), t.exports; + } catch (e) { + throw t = 0, e; + } + }; + var ls = x((tt) => { "use strict"; - Object.defineProperty(Y, "__esModule", { value: true }); - 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); + Object.defineProperty(tt, "__esModule", { value: true }); + tt.range = tt.balanced = void 0; + var di = (n, t, e) => { + let s = n instanceof RegExp ? as(n, e) : n, i = t instanceof RegExp ? as(t, e) : t, r = s !== null && i != null && (0, tt.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) => { + tt.balanced = di; + var as = (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); + }, pi = (n, t, e) => { + let s, i, r, h, a, o = e.indexOf(n), l = e.indexOf(t, o + 1), c = o; + if (o >= 0 && l > 0) { + if (n === t) return [o, l]; + for (s = [], r = e.length; c >= 0 && !a; ) { + if (c === o) s.push(c), o = e.indexOf(n, c + 1); else if (s.length === 1) { - let c = s.pop(); - c !== void 0 && (o = [c, l]); - } else i = s.pop(), i !== void 0 && i < r && (r = i, h = l), l = e.indexOf(t, f + 1); - f = a < l && a >= 0 ? a : l; + let u = s.pop(); + u !== void 0 && (a = [u, l]); + } else i = s.pop(), i !== void 0 && i < r && (r = i, h = l), l = e.indexOf(t, c + 1); + c = o < l && o >= 0 ? o : l; } - s.length && h !== void 0 && (o = [r, h]); + s.length && h !== void 0 && (a = [r, h]); } - return o; + return a; }; - Y.range = zs; + tt.range = pi; }); - var Ke = R((it) => { + var ms = x((T) => { "use strict"; - Object.defineProperty(it, "__esModule", { value: true }); - 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) { + Object.defineProperty(T, "__esModule", { value: true }); + T.EXPANSION_MAX_REWRITES = T.EXPANSION_MAX_DEPTH = T.EXPANSION_MAX_LENGTH = T.EXPANSION_MAX = void 0; + T.expand = Mi; + var cs = ls(), us = "\0SLASH" + Math.random() + "\0", fs34 = "\0OPEN" + Math.random() + "\0", ve = "\0CLOSE" + Math.random() + "\0", ds = "\0COMMA" + Math.random() + "\0", ps = "\0PERIOD" + Math.random() + "\0", mi = new RegExp(us, "g"), gi = new RegExp(fs34, "g"), wi = new RegExp(ve, "g"), bi = new RegExp(ds, "g"), yi = new RegExp(ps, "g"), Si = /\\\\/g, vi = /\\{/g, _i = /\\}/g, Ei = /\\,/g, Oi = /\\\./g; + T.EXPANSION_MAX = 1e5; + T.EXPANSION_MAX_LENGTH = 4e6; + T.EXPANSION_MAX_DEPTH = 1e3; + T.EXPANSION_MAX_REWRITES = 1e3; + function be(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 Ci(n) { + return n.replace(Si, us).replace(vi, fs34).replace(_i, ve).replace(Ei, ds).replace(Oi, ps); + } + function Ai(n) { + return n.replace(mi, "\\").replace(gi, "{").replace(wi, "}").replace(bi, ",").replace(yi, "."); } - function ti(n) { - return n.replace(Us, "\\").replace($s, "{").replace(qs, "}").replace(Hs, ",").replace(Vs, "."); + function ye(n, t) { + for (let e = 0; e < t.length; e++) n.push(t[e]); } - 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 ki(n) { + let t = [], e = ""; + for (; ; ) { + let s = (0, cs.balanced)("{", "}", n); + if (!s) { + let o = n.split(","); + return o[0] = e + o[0], ye(t, o), t; + } + let { pre: i, body: r, post: h } = s, a = i.split(","); + if (a[0] = e + a[0], a[a.length - 1] += "{" + r + "}", !h.length) return ye(t, a), t; + e = a.pop(), ye(t, a), n = h; + } } - function ei(n, t = {}) { + function Mi(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, true).map(ti); + let { max: e = T.EXPANSION_MAX, maxLength: s = T.EXPANSION_MAX_LENGTH, maxDepth: i = T.EXPANSION_MAX_DEPTH, maxRewrites: r = T.EXPANSION_MAX_REWRITES } = t; + return n.slice(0, 2) === "{}" && (n = "\\{\\}" + n.slice(2)), Se(Ci(n), e, s, i, 0, r, true).map(Ai); } - function si(n) { + function xi(n) { return "{" + n + "}"; } - function ii(n) { + function Ri(n) { return /^-?0\d/.test(n); } - function ri(n, t) { + function Pi(n, t) { return n <= t; } - function ni(n, t) { + function Ti(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, false) : [""]; - if (/\$$/.test(i.pre)) for (let o = 0; o < h.length && o < t; o++) { - let a = r + "{" + i.body + "}" + h[o]; - s.push(a); + function lt2(n, t, e, s, i, r) { + let h = [], a = 0; + for (let o = 0; o < n.length; o++) for (let l = 0; l < e.length; l++) { + if (h.length >= s) return h; + let c = n[o] + t + e[l]; + if (!(r && !c)) { + if (a + c.length > i) return h; + h.push(c), a += c.length; + } + } + return h; + } + function Fi(n, t, e, s) { + let i = n.split(/\.\./), r = []; + if (i[0] === void 0 || i[1] === void 0) return r; + let h = be(i[0]), a = be(i[1]), o = Math.max(i[0].length, i[1].length), l = i.length === 3 && i[2] !== void 0 ? Math.max(Math.abs(be(i[2])), 1) : 1, c = Pi; + a < h && (l *= -1, c = Ti); + let p = i.some(Ri), d = 0; + for (let g = h; c(g, a) && r.length < e; g += l) { + let f; + if (t) f = String.fromCharCode(g), f === "\\" && (f = ""); + else if (f = String(g), p) { + let b = o - f.length; + if (b > 0) { + let m = new Array(b + 1).join("0"); + g < 0 ? f = "-" + m + f.slice(1) : f = m + f; + } + } + if (d + f.length > s) break; + r.push(f), d += f.length; } - else { - let o = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body), a = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body), l = o || a, f = i.body.indexOf(",") >= 0; - if (!l && !f) return i.post.match(/,(?!,).*\}/) ? (n = i.pre + "{" + i.body + ue + i.post, ht(n, t, true)) : [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, false).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; - m < u && (b *= -1, w = ni); - let E = c.some(ii); - d = []; - for (let y = u; w(y, m); y += b) { - let S; - if (a) S = String.fromCharCode(y), S === "\\" && (S = ""); - else if (S = String(y), E) { - let B = p - S.length; - if (B > 0) { - let U = new Array(B + 1).join("0"); - y < 0 ? S = "-" + U + S.slice(1) : S = U + S; + return r; + } + function Se(n, t, e, s, i, r, h) { + if (i > s) return [n]; + let a = [""], o = 0, l = false, c = true; + for (; ; ) { + let u = (0, cs.balanced)("{", "}", n); + if (!u) return lt2(a, n, [""], t, e, l); + let p = u.pre; + if (/\$$/.test(p)) { + if (a = lt2(a, p + "{" + u.body + "}", [""], t, e, l && !u.post.length), c = false, !u.post.length) break; + n = u.post; + continue; + } + let d = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(u.body), g = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(u.body), f = d || g, b = u.body.indexOf(",") >= 0; + if (!f && !b) { + if (o < r && u.post.match(/,(?!,).*\}/)) { + o++, n = u.pre + "{" + u.body + ve + u.post, h = true; + continue; + } + return lt2(a, p + "{" + u.body + "}" + u.post, [""], t, e, l); + } + c && (l = h && !f, c = false); + let m; + if (f) m = Fi(u.body, g, t, e); + else { + let y = ki(u.body); + if (y.length === 1 && y[0] !== void 0 && (y = Se(y[0], t, e, s, i + 1, r, false).map(xi), y.length === 1)) { + if (a = lt2(a, p + y[0], [""], t, e, l && !u.post.length), !u.post.length) break; + n = u.post; + continue; + } + let _2 = l && !u.post.length && !p; + for (let S = 0; _2 && S < a.length; S++) a[S] && (_2 = false); + m = []; + let v = 0; + t: for (let S = 0; S < y.length; S++) { + let K = Se(y[S], t, e, s, i + 1, r, false); + for (let z = 0; z < K.length; z++) { + let $ = K[z]; + if (!(_2 && !$)) { + if (m.length >= t || v + $.length > e) break t; + m.push($), v += $.length; } } - d.push(S); } - } else { - d = []; - for (let u = 0; u < c.length; u++) d.push.apply(d, ht(c[u], t, false)); - } - for (let u = 0; u < d.length; u++) for (let m = 0; m < h.length && s.length < t; m++) { - let p = r + d[u] + h[m]; - (!e || l || p) && s.push(p); } + if (a = lt2(a, p, m, t, e, l && !u.post.length), !u.post.length) break; + n = u.post; } - return s; + return a; } }); - var Xe = R((Ct) => { - "use strict"; - Object.defineProperty(Ct, "__esModule", { value: true }); - 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) => { + var gs = x((Tt) => { "use strict"; - Object.defineProperty(Rt, "__esModule", { value: true }); - Rt.parseClass = void 0; - var ai = { "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true], "[:alpha:]": ["\\p{L}\\p{Nl}", true], "[:ascii:]": ["\\x00-\\x7f", false], "[:blank:]": ["\\p{Zs}\\t", true], "[:cntrl:]": ["\\p{Cc}", true], "[:digit:]": ["\\p{Nd}", true], "[:graph:]": ["\\p{Z}\\p{C}", true, true], "[:lower:]": ["\\p{Ll}", true], "[:print:]": ["\\p{C}", true], "[:punct:]": ["\\p{P}", true], "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true], "[:upper:]": ["\\p{Lu}", true], "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true], "[:xdigit:]": ["A-Fa-f0-9", false] }, 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 = false, o = false, a = false, l = false, f = e, c = ""; - t: for (; r < n.length; ) { - let p = n.charAt(r); - if ((p === "!" || p === "^") && r === e + 1) { - l = true, r++; + Object.defineProperty(Tt, "__esModule", { value: true }); + Tt.parseClass = void 0; + var ji = { "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}"], "[:alpha:]": ["\\p{L}\\p{Nl}"], "[:ascii:]": ["\\x00-\\x7f"], "[:blank:]": ["\\p{Zs}\\t"], "[:cntrl:]": ["\\p{Cc}"], "[:digit:]": ["\\p{Nd}"], "[:graph:]": ["\\p{Z}\\p{C}", true], "[:lower:]": ["\\p{Ll}"], "[:print:]": ["\\p{C}", true], "[:punct:]": ["\\p{P}\\p{S}"], "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f"], "[:upper:]": ["\\p{Lu}"], "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}"], "[:xdigit:]": ["A-Fa-f0-9"] }, ct = (n) => n.replace(/[[\]\\-]/g, "\\$&"), _e2 = /$./, Di = (n, t, e = false, s) => { + let i = (m) => { + let y = s ? m.normalize(s) : m; + return [...y].length === 1 ? y : m; + }, r = t; + if (n.charAt(r) !== "[") throw new Error("not in a brace expression"); + let h = [], a = [], o = r + 1, l = false, c = false, u = false, p = r, d = ""; + t: for (; o < n.length; ) { + let m = String.fromCodePoint(n.codePointAt(o)); + if ((m === "!" || m === "^") && o === r + 1) { + u = true, o++; continue; } - if (p === "]" && h && !a) { - f = r + 1; + if (m === "]" && l && !c) { + p = o + 1; break; } - if (h = true, p === "\\" && !a) { - a = true, r++; + if (l = true, m === "\\" && !c) { + c = true, o++; continue; } - if (p === "[" && !a) { - for (let [b, [w, v, E]] of Object.entries(ai)) if (n.startsWith(b, r)) { - if (c) return ["$.", false, n.length - e, true]; - r += b.length, E ? i.push(w) : s.push(w), o = o || v; + if (m === "[" && !c) { + for (let [_2, [v, S]] of Object.entries(ji)) if (n.startsWith(_2, o)) { + if (d) return [_e2, n.length - r]; + o += _2.length, S ? a.push(v) : h.push(v); continue t; } } - if (a = false, c) { - p > c ? s.push(ot(c) + "-" + ot(p)) : p === c && s.push(ot(p)), c = "", r++; + c = false; + let y = i(m); + if (d) { + y.codePointAt(0) > d.codePointAt(0) ? h.push(ct(d) + "-" + ct(y)) : y === d && h.push(ct(y)), d = "", o += m.length; continue; } - if (n.startsWith("-]", r + 1)) { - s.push(ot(p + "-")), r += 2; + if (n.startsWith("-]", o + m.length)) { + h.push(ct(y + "-")), o += m.length + 1; continue; } - if (n.startsWith("-", r + 1)) { - c = p, r += 2; + if (n.startsWith("-", o + m.length)) { + d = y, o += m.length + 1; continue; } - s.push(ot(p)), r++; + h.push(ct(y)), o += m.length; } - if (f < r) return ["", false, 0, false]; - if (!s.length && !i.length) return ["$.", false, n.length - e, true]; - if (i.length === 0 && s.length === 1 && /^\\?.$/.test(s[0]) && !l) { - let p = s[0].length === 2 ? s[0].slice(-1) : s[0]; - return [li(p), false, f - e, false]; - } - let d = "[" + (l ? "^" : "") + Ye(s) + "]", u = "[" + (l ? "" : "^") + Ye(i) + "]"; - return [s.length && i.length ? "(" + d + "|" + u + ")" : s.length ? d : u, o, f - e, true]; + if (p < o) return [_e2, 0]; + if (!h.length && !a.length) return [_e2, n.length - r]; + let g = "[" + (u ? "^" : "") + h.join("") + "]", f = "[" + (u ? "" : "^") + a.join("") + "]", b = "^" + (h.length && a.length ? "(" + g + "|" + f + ")" : h.length ? g : f); + return [new RegExp(b, e ? "iu" : "u"), p - r]; }; - Rt.parseClass = ci; + Tt.parseClass = Di; }); - var kt = R((At) => { + var Cs = x((jt) => { "use strict"; - Object.defineProperty(At, "__esModule", { value: true }); - At.unescape = void 0; - var ui = (n, { windowsPathsNoEscape: t = false, magicalBraces: e = true } = {}) => 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: true }); - Dt.AST = void 0; - var fi = Je(), Mt = kt(), di = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]), Ze = (n) => di.has(n), pi = "(?!(?:^|/)\\.\\.?(?:$|/))", Pt = "(?!\\.)", mi = /* @__PURE__ */ new Set(["[", "."]), gi = /* @__PURE__ */ new Set(["..", "."]), wi = new Set("().*{}+?[]^$\\!"), bi = (n) => n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), de = "[^/]", Qe = de + "*?", ts = de + "+?", fe = class n { - type; - #t; - #s; - #n = false; - #r = []; - #h; - #S; - #w; - #c = false; - #o; - #f; - #u = false; - constructor(t, e, s = {}) { - this.type = t, t && (this.#s = true), 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 = true; - 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 = true; - 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 && i < s.#r.length; i++) for (let r of t.#r) { - if (typeof r == "string") throw new Error("string part in extglob AST??"); - r.copyIn(s.#r[i]); - } - e = s, s = e.#h; + Object.defineProperty(jt, "__esModule", { value: true }); + jt.Matcher = void 0; + var Ni = gs(), Ee = { t: "match", id: 0 }, Li = "!?+*@", et = (n) => ({ t: "lit", ch: n }), Wi = (n) => n.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&"), Oe = (n) => new RegExp(`^${Wi(n)}$`, "iu"), Me = (n, t) => { + if (t === n.ch) return true; + if (!n.re) return false; + let e = t.charCodeAt(0); + if (e >= 128) return n.re.test(t); + let s = n.ascii ??= new Uint8Array(128); + return s[e] ||= n.re.test(t) ? 1 : 2, s[e] === 1; + }, Bi = (n, t, e, s) => { + let i = []; + for (let r = 0; r < n.length; ) { + let h = String.fromCodePoint(n.codePointAt(r)); + if (h === "\\") { + let a = n.codePointAt(r + 1), o = a === void 0 ? h : String.fromCodePoint(a); + i.push(et(o)), r += 1 + o.length; + continue; + } + if (h === "[") { + let [a, o] = (0, Ni.parseClass)(n, r, t, s); + if (o) { + i.push({ t: "class", re: a }), r += o; + continue; } } - return this; + if (!e && Li.includes(h) && n[r + 1] === "(") { + i.push({ t: "open", type: h }), r += 2; + continue; + } + i.push(!e && h === "|" ? { t: "bar" } : !e && h === ")" ? { t: "close" } : h === "*" ? { t: "star" } : h === "?" ? { t: "any" } : et(h)), r += h.length; } - push(...t) { - for (let e of t) if (e !== "") { - if (typeof e != "string" && !(e instanceof n && e.#h === this)) throw new Error("invalid part: " + e); - this.#r.push(e); + return i; + }, zi = (n) => { + let t = /* @__PURE__ */ new Map(), e = []; + return n.forEach((s, i) => { + s.t === "open" ? e.push(i) : s.t === "close" && e.length && t.set(e.pop(), i); + }), t; + }, Ss = (n, t, e, s, i) => { + let r = [], h = [r]; + for (let a = e; a < s; a++) { + let o = n[a], l = t.get(a); + if (o.t === "open" && l !== void 0) { + let c = Ss(n, t, a + 1, l, false); + r.push({ t: "ext", type: o.type, alts: c }), a = l; + } else o.t === "bar" && !i ? h.push(r = []) : o.t === "open" ? r.push(et(o.type), et("(")) : o.t === "bar" ? r.push(et("|")) : o.t === "close" ? r.push(et(")")) : r.push(o); + } + return h; + }, vs = (n, t) => { + let e = [], s = "", i = () => { + for (let r of s.normalize(t)) e.push(et(r)); + s = ""; + }; + for (let r of n) { + if (r.t === "lit") { + s += r.ch; + continue; + } + i(), e.push(r.t === "ext" ? { ...r, alts: r.alts.map((h) => vs(h, t)) } : r); + } + return i(), e; + }, Gi = (n, t) => { + let e = 1, s = (a) => ({ t: "split", id: e++, out: a }), i = (a, o) => a.reduceRight((l, c) => r(c, l), o), r = (a, o) => { + switch (a.t) { + case "lit": + let p = t ? Oe(a.ch) : void 0; + return { t: "lit", id: e++, ch: a.ch, re: p, next: o }; + case "any": + case "star": + return { t: a.t, id: e++, next: o }; + case "class": + return { t: "class", id: e++, re: a.re, next: o }; + } + let l = (p) => a.alts.map((d) => i(d, p)); + switch (a.type) { + case "@": + return s(l(o)); + case "?": + return s([o, ...l(o)]); + case "!": + return { t: "neg", id: e++, sub: s(l(Ee)), next: o }; + } + let c = s([]), u = s(l(c)); + return c.out.push(o, u), a.type === "*" ? c : u; + }; + return [i(n, Ee), e]; + }, Ii = (n) => { + let t = [], e = /* @__PURE__ */ new Set(), s = (r) => r.t === "match" ? "match" : String(r.id), i = (r, h) => { + if (r.t === "match" || e.has(r)) return; + e.add(r); + let a = (o) => t.push(`${h}${r.id}: ${o}`); + switch (r.t) { + case "split": + a(`split -> ${r.out.map(s).join(", ")}`); + for (let o of r.out) i(o, h); + return; + case "neg": + return a(`!(${s(r.sub)}) -> ${s(r.next)}`), i(r.sub, h + " "), i(r.next, h); + case "lit": + a(`${JSON.stringify(r.ch)} -> ${s(r.next)}`); + break; + case "class": + a(`${r.re} -> ${s(r.next)}`); + break; + default: + a(`${r.t === "any" ? "?" : "*"} -> ${s(r.next)}`); } + i(r.next, h); + }; + return i(n, ""), [`start -> ${s(n)}`, ...t].join(` +`); + }, Ce = class { + gen; + threads = []; + match = false; + runs = []; + ids = []; + constructor(t) { + this.gen = t; } - toJSON() { - let t = this.type === null ? this.#r.slice().map((e) => typeof 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; + get dead() { + return !this.threads.length && !this.match && !this.runs.length; } - isStart() { - if (this.#t === this) return true; - if (!this.#h?.isStart()) return false; - if (this.#S === 0) return true; - let t = this.#h; - for (let e = 0; e < this.#S; e++) { - let s = t.#r[e]; - if (!(s instanceof n && s.type === "!")) return false; - } - return true; + }, _s2 = (n, t) => n.ids.length !== t.ids.length || n.runs.length !== t.runs.length || n.ids.some((e, s) => e !== t.ids[s]) ? false : n.runs.every((e) => t.runs.some((s) => s.neg === e.neg && _s2(s.state, e.state))), ws = (n) => ({ has: new Float64Array(n), seen: new Float64Array(n), gen: 0 }), ut = class { + dots; + dotStart; + #t; + constructor(t, e, s) { + this.dots = t, this.dotStart = e, this.#t = s; } - isEnd() { - if (this.#t === this || this.#h?.type === "!") return true; - if (!this.#h?.isEnd()) return false; - if (!this.type) return this.#h?.isEnd(); - let t = this.#h ? this.#h.#r.length : 0; - return this.#S === t - 1; + state() { + return new Ce(++this.#t.gen); } - copyIn(t) { - typeof t == "string" ? this.push(t) : this.push(t.clone(this)); + done(t) { + return t.ids = t.threads.map((e) => e.id).sort((e, s) => e - s), t.match && t.ids.unshift(Ee.id), t; } - clone(t) { - let e = new n(this.type, t); - for (let s of this.#r) e.copyIn(s); - return e; + #i(t, e) { + let { seen: s } = this.#t; + return s[e.id] === t.gen ? false : (s[e.id] = t.gen, true); } - static #i(t, e, s, i) { - let r = false, h = false, o = -1, a = false; - if (e.type === null) { - let u = s, m = ""; - for (; u < t.length; ) { - let p = t.charAt(u++); - if (r || p === "\\") { - r = !r, m += p; - continue; - } - if (h) { - u === o + 1 ? (p === "^" || p === "!") && (a = true) : p === "]" && !(u === o + 2 && a) && (h = false), m += p; - continue; - } else if (p === "[") { - h = true, o = u, a = false, m += p; - continue; - } - if (!i.noext && Ze(p) && t.charAt(u) === "(") { - e.push(m), m = ""; - let b = new n(p, e); - u = n.#i(t, b, u, i), e.push(b); - continue; - } - m += p; - } - return e.push(m), u; - } - let l = s + 1, f = new n(null, e), c = [], d = ""; - for (; l < t.length; ) { - let u = t.charAt(l++); - if (r || u === "\\") { - r = !r, d += u; - continue; - } - if (h) { - l === o + 1 ? (u === "^" || u === "!") && (a = true) : u === "]" && !(l === o + 2 && a) && (h = false), d += u; - continue; - } else if (u === "[") { - h = true, o = l, a = false, d += u; - continue; - } - if (Ze(u) && t.charAt(l) === "(") { - f.push(d), d = ""; - let m = new n(u, f); - f.push(m), l = n.#i(t, m, l, i); - continue; - } - if (u === "|") { - f.push(d), d = "", c.push(f), f = new n(null, e); - continue; - } - if (u === ")") return d === "" && e.#r.length === 0 && (e.#u = true), f.push(d), d = "", e.push(...c, f), l; - d += u; - } - return e.type = null, e.#s = void 0, e.#r = [t.substring(s - 1)], l; + #e(t, e) { + let { has: s } = this.#t; + return s[e.id] === t.gen ? false : (s[e.id] = t.gen, t.threads.push(e), true); } - static fromGlob(t, e = {}) { - let s = new n(null, void 0, e); - return n.#i(t, s, 0, e), s; + restricted(t, e) { + return e && (this.dots || this.dotStart && t === 0); } - toMMPattern() { - if (this !== this.#t) return this.#t.toMMPattern(); - let t = this.toString(), [e, s, i, r] = this.toRegExpSource(); - if (!(i || this.#s || this.#o.nocase && !this.#o.nocaseMagicOnly && t.toUpperCase() !== t.toLowerCase())) return s; - let o = (this.#o.nocase ? "i" : "") + (r ? "u" : ""); - return Object.assign(new RegExp(`^${e}$`, o), { _src: e, _glob: t }); + add(t, e, s, i) { + switch (e.t) { + case "split": + if (!this.#i(t, e)) return; + for (let h of e.out) this.add(t, h, s, i); + return; + case "neg": + if (!this.#i(t, e)) return; + let r = this.state(); + return this.add(r, e.sub, s, false), this.done(r), this.addRun(t, { t: "run", neg: e, state: r }, s, i); + case "star": + if (this.restricted(s, i)) return; + this.#e(t, e) && this.add(t, e.next, s, i); + return; + case "match": + t.match = true; + return; + default: + this.#e(t, e); + } } - get options() { - return this.#o; + addRun(t, e, s, i) { + for (let r of t.runs) if (r.neg === e.neg && _s2(r.state, e.state)) return; + t.runs.push(e), e.state.match || this.add(t, e.neg.next, s, i); } - toRegExpSource(t) { - let e = t ?? !!this.#o.dot; - if (this.#t === this && this.#a(), !this.type) { - let a = this.isStart() && this.isEnd() && !this.#r.some((u) => typeof 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()), false, false]; - } - let h = !s || t || e || !Pt ? "" : this.#d(true); - 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 = false) { - let i = false, r = "", h = false, o = false; - for (let a = 0; a < t.length; a++) { - let l = t.charAt(a); - if (i) { - i = false, r += (wi.has(l) ? "\\" : "") + l; - continue; - } - if (l === "*") { - if (o) continue; - o = true, r += s && /^[*]+$/.test(t) ? ts : Qe, e = true; - continue; - } else o = false; - if (l === "\\") { - a === t.length - 1 ? r += "\\\\" : i = true; - continue; - } - if (l === "[") { - let [f, c, d, u] = (0, fi.parseClass)(t, a); - if (d) { - r += f, h = h || c, a += d - 1, e = e || u; - continue; - } - } - if (l === "?") { - r += de, e = true; + step(t, e, s, i) { + let r = this.state(); + for (let h of t.threads) switch (h.t) { + case "lit": + Me(h, e) && this.add(r, h.next, s + 1, i); + break; + case "any": + this.restricted(s, i) || this.add(r, h.next, s + 1, i); + break; + case "class": + !this.restricted(s, i) && h.re.test(e) && this.add(r, h.next, s + 1, i); + break; + case "star": + this.restricted(s, i) || this.add(r, h, s + 1, i); + } + if (!this.restricted(s, i)) for (let h of t.runs) { + if (h.state.dead) { + this.addRun(r, h, s + 1, i); continue; } - r += bi(l); + let a = this.step(h.state, e, s, false); + this.addRun(r, { t: "run", neg: h.neg, state: a }, s + 1, i); } - return [r, (0, Mt.unescape)(t), !!e, h]; + return this.done(r); + } + }, Es = (n) => { + let t = n.ids.join(); + if (!n.runs.length) return t; + let e = n.runs.map((s) => `${s.neg.id}(${Es(s.state)})`); + return `${t}|${e.sort().join("|")}`; + }, Ui = 1 << 18, Ae = class { + #t; + #i = /* @__PURE__ */ new Map(); + #e = 0; + #h; + #n; + #d; + #c; + constructor(t, e) { + this.#t = t, this.#d = new ut(false, false, e), this.#c = new ut(false, true, e); + } + #p(t) { + return { state: t, match: t.match, dead: t.dead, next: /* @__PURE__ */ new Map() }; + } + #o(t) { + let e = Es(t), s = this.#i.get(e); + if (s) return s; + this.#e > Ui && this.#m(); + let i = this.#p(t); + return this.#i.set(e, i), this.#e += e.length + 1, i; + } + #m() { + this.#i.clear(), this.#e = 0, this.#h = void 0, this.#n = void 0; + } + start(t) { + if (t) { + if (this.#n) return this.#n; + let s = this.#c.state(); + return this.#c.add(s, this.#t, 0, true), this.#n = this.#p(this.#c.done(s)); + } + if (this.#h) return this.#h; + let e = this.#d.state(); + return this.#d.add(e, this.#t, 0, true), this.#h = this.#o(this.#d.done(e)); + } + next(t, e) { + let s = e.charCodeAt(0), i = s < 128 ? void 0 : t.next.get(e); + if (i) return i; + let r = t === this.#n ? this.#o(this.#c.step(t.state, e, 0, true)) : this.#o(this.#d.step(t.state, e, 1, true)); + return s < 128 ? (t.ascii || (t.ascii = new Array(128), this.#e += 128), t.ascii[s] = r) : t.next.set(e, r), this.#e++, r; + } + }, $i = (n) => { + let t = []; + for (let e = n; e.t !== "match"; e = e.next) { + if (e.t === "split" || e.t === "neg") return; + t.push(e); + } + return t; + }, qi = (n, t, e, s) => { + let i = 0, r = e, h = -1, a = 0; + for (; r < s; ) { + let o = n[i]; + if (o?.t === "star") { + h = i++, a = r; + continue; + } + let l = t[r]; + if (o && (o.t === "any" || o.t === "lit" && Me(o, l) || o.t === "class" && o.re.test(l))) { + i++, r++; + continue; + } + if (h === -1) return false; + i = h + 1, r = ++a; + } + for (; n[i]?.t === "star"; ) i++; + return i === n.length; + }, Os = (n) => { + let t = 0, e = 0; + for (let s of n) { + let [i, r] = Hi(s); + t += i, e += r; + } + return [t, e]; + }, Hi = (n) => { + if (n.t === "star") return [0, 1 / 0]; + if (n.t !== "ext") return [1, 1]; + if (n.type === "!") return [0, 1 / 0]; + let t = n.alts.map(Os), e = Math.min(...t.map((r) => r[0])), s = Math.max(...t.map((r) => r[1])), i = s === 0 ? 0 : 1 / 0; + return n.type === "@" ? [e, s] : n.type === "?" ? [0, s] : n.type === "*" ? [0, i] : [e, i]; + }, bs = (n, t, e) => { + for (let s = 0; s < n.length; s++) if (!Me(n[s], t[e + s])) return false; + return true; + }, Xi = /[/\ud800-\udfff]/, Ki = /[\ud800-\udfff]/, Ft = (n) => Ki.test(n) ? [...n] : n, ys = (n) => { + if (n.includes("/")) throw new Error("can only match a single path portion, got: " + n); + }, ke = class { + pattern; + options; + #t; + #i; + #e; + #h; + #n; + #d; + #c; + #p = false; + #o = 0; + #m = 1 / 0; + #a = []; + #l = []; + #r; + #w; + #_ = false; + #b; + #u; + constructor(t, e = {}) { + if (t.includes("/")) throw new Error("can only match a single path portion, got pattern: " + t); + this.pattern = t, this.options = e; + let { nocase: s = false, noext: i = false, normalize: r } = e; + this.#u = r === true ? "NFC" : r || void 0; + let h = /^[?*+@]\(\)$/.test(t), a = Bi(t, s, i || h, this.#u), [o] = Ss(a, zi(a), 0, a.length, true); + this.#u && (o = vs(o, this.#u)); + let [l, c] = Gi(o, s); + if (this.#t = l, this.#i = c, o.every((u) => u.t === "lit")) this.#n = o.map((u) => u.ch).join(""), s && (this.#d = Oe(this.#n)); + else { + let u = (g) => g.t !== "lit" ? void 0 : s ? { ch: g.ch, re: Oe(g.ch) } : { ch: g.ch }; + for (let g of o) { + let f = u(g); + if (!f) break; + this.#a.push(f); + } + for (let g = o.length - 1; g >= 0; g--) { + let f = u(o[g]); + if (!f) break; + this.#l.unshift(f); + } + this.#_ = !!(this.#a.length || this.#l.length), s || (this.#r = this.#a.map((g) => g.ch).join(""), this.#w = this.#l.map((g) => g.ch).join("")), this.#c = $i(this.#t)?.slice(this.#a.length, -this.#l.length || void 0), this.#p = !!this.#c?.every((g) => g.t === "star" || g.t === "any"); + let [p, d] = Os(o); + this.#o = p, this.#m = d; + } + } + test(t) { + return this.#u ? (ys(t), this.#v(t.normalize(this.#u))) : Xi.test(t) ? (ys(t), this.#v(t, [...t])) : this.#v(t, t); + } + testUnchecked(t) { + return this.#v(this.#u ? t.normalize(this.#u) : t); + } + #v(t, e) { + if (this.#n !== void 0) return this.#d ? this.#d.test(t) : t === this.#n; + let s = this.#o, i = this.#m; + if (e === void 0) { + let c = t.length, u = c + 1 >> 1; + if (c < s || u > i) return false; + (u < s || c > i) && (e = Ft(t)); + } + if (e !== void 0 && (e.length < s || e.length > i)) return false; + let r = this.#a.length; + if (this.#_) if (this.#r !== void 0 && this.#w !== void 0) { + if (!t.startsWith(this.#r) || !t.endsWith(this.#w)) return false; + } else { + e ??= Ft(t); + let c = e.length - this.#l.length; + if (!bs(this.#a, e, 0) || !bs(this.#l, e, c)) return false; + } + let h = !this.options.dot && t.startsWith("."); + if (this.#c) { + if (t === "." || t === ".." || h && !r) return false; + if (this.#p) return true; + e ??= Ft(t); + let c = e.length - this.#l.length; + return qi(this.#c, e, r, c); + } + if (e ??= Ft(t), t === "." || t === "..") { + this.#e ??= ws(this.#i); + let c = this.#h ??= new ut(true, false, this.#e), u = c.state(); + c.add(u, this.#t, 0, true); + let p = c.done(u); + for (let d = 0; d < e.length; d++) p = c.step(p, e[d], d, true); + return p.match; + } + this.#e ??= ws(this.#i); + let a = this.#b ??= new Ae(this.#t, this.#e), o = a.start(h), l = e === t; + for (let c = 0; c < e.length; c++) { + if (o.dead) return false; + let u = l ? t.charCodeAt(c) : e[c].charCodeAt(0); + o = o.ascii?.[u] ?? a.next(o, e[c]); + } + return o.match; + } + toString() { + return Ii(this.#t); } }; - Dt.AST = fe; + jt.Matcher = ke; }); - var me = R((Ft) => { + var As = x((Dt) => { "use strict"; - Object.defineProperty(Ft, "__esModule", { value: true }); - Ft.escape = void 0; - var yi = (n, { windowsPathsNoEscape: t = false, magicalBraces: e = false } = {}) => e ? t ? n.replace(/[?*()[\]{}]/g, "[$&]") : n.replace(/[?*()[\]\\{}]/g, "\\$&") : t ? n.replace(/[?*()[\]]/g, "[$&]") : n.replace(/[?*()[\]\\]/g, "\\$&"); - Ft.escape = yi; + Object.defineProperty(Dt, "__esModule", { value: true }); + Dt.assertValidPattern = void 0; + var Vi = 1024 * 64, Yi = (n) => { + if (typeof n != "string") throw new TypeError("invalid pattern"); + if (n.length > Vi) throw new TypeError("pattern is too long"); + }; + Dt.assertValidPattern = Yi; }); - var H = R((g) => { + var xe = x((Nt) => { "use strict"; - Object.defineProperty(g, "__esModule", { value: true }); - 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) === "#" ? false : 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 = /* @__PURE__ */ 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 { + Object.defineProperty(Nt, "__esModule", { value: true }); + Nt.escape = void 0; + var Zi = (n, { windowsPathsNoEscape: t = false, magicalBraces: e = false } = {}) => e ? t ? n.replace(/[?*()[\]{}]/g, "[$&]") : n.replace(/[?*()[\]\\{}]/g, "\\$&") : t ? n.replace(/[?*()[\]]/g, "[$&]") : n.replace(/[?*()[\]\\]/g, "\\$&"); + Nt.escape = Zi; + }); + var Re = x((Lt) => { + "use strict"; + Object.defineProperty(Lt, "__esModule", { value: true }); + Lt.unescape = void 0; + var Ji = (n, { windowsPathsNoEscape: t = false, magicalBraces: e = true } = {}) => 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"); + Lt.unescape = Ji; + }); + var Y = x((w) => { + "use strict"; + Object.defineProperty(w, "__esModule", { value: true }); + w.unescape = w.escape = w.Minimatch = w.match = w.braceExpand = w.defaults = w.filter = w.GLOBSTAR = w.sep = w.minimatch = void 0; + var Qi = ms(), ks = Cs(), zt = As(), tr = xe(), er = Re(), sr = (n, t, e = {}) => ((0, zt.assertValidPattern)(t), !e.nocomment && t.charAt(0) === "#" ? false : new ht(t, e).match(n)); + w.minimatch = sr; + var Fs = typeof process == "object" && process ? process.env?.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix", Ms = { win32: { sep: "\\" }, posix: { sep: "/" } }; + w.sep = Fs === "win32" ? Ms.win32.sep : Ms.posix.sep; + w.minimatch.sep = w.sep; + w.GLOBSTAR = /* @__PURE__ */ Symbol("globstar **"); + w.minimatch.GLOBSTAR = w.GLOBSTAR; + var ir = (n, t = {}) => (e) => (0, w.minimatch)(e, n, t); + w.filter = ir; + w.minimatch.filter = w.filter; + var q = (n, t = {}) => Object.assign({}, n, t), rr = (n) => { + if (!n || typeof n != "object" || !Object.keys(n).length) return w.minimatch; + let t = w.minimatch; + return Object.assign((s, i, r = {}) => t(s, i, q(n, r)), { Minimatch: class extends t.Minimatch { constructor(i, r = {}) { - super(i, F(n, r)); + super(i, q(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 t.defaults(q(n, i)).Minimatch; + } + }, unescape: (s, i = {}) => t.unescape(s, q(n, i)), escape: (s, i = {}) => t.escape(s, q(n, i)), filter: (s, i = {}) => t.filter(s, q(n, i)), defaults: (s) => t.defaults(q(n, s)), braceExpand: (s, i = {}) => t.braceExpand(s, q(n, i)), match: (s, i, r = {}) => t.match(s, i, q(n, r)), sep: t.sep, GLOBSTAR: w.GLOBSTAR }); + }; + w.defaults = rr; + w.minimatch.defaults = w.defaults; + var nr = (n, t = {}) => ((0, zt.assertValidPattern)(n), t.nobrace || !/\{(?:(?!\{).)*\}/.test(n) ? [n] : (0, Qi.expand)(n, { max: t.braceExpandMax })); + w.braceExpand = nr; + w.minimatch.braceExpand = w.braceExpand; + var hr = (n, t, e = {}) => { + let s = new ht(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 { + w.match = hr; + w.minimatch.match = w.match; + var xs = /[?*]|[+@!]\(.*?\)|\[|\]/, js = (n, t) => { + let e = t + 1; + (n.charAt(e) === "!" || n.charAt(e) === "^") && e++; + let s = false; + for (; e < n.length; e++) { + let i = n.charAt(e); + if (i === "]" && s) return e; + s = true, i === "\\" && e++; + } + return -1; + }, or2 = (n, t) => { + if (!t && (n === "+()" || n === "@()")) return n; + let e = ""; + for (let s = 0; s < n.length; s++) { + let i = n.charAt(s); + if (i === "\\") e += n.charAt(++s) || i; + else { + if (i === "*" || i === "?") return; + if (i === "[") { + let r = js(n, s); + if (r === -1) { + e += i; + continue; + } + let h = n.slice(s + 1, r); + if (h.startsWith("\\") && (h = h.slice(1)), [...h].length !== 1 || "!^".includes(n.charAt(s + 1))) return; + e += h, s = r; + } else { + if (!t && "+@!".includes(i) && n.charAt(s + 1) === "(" && n.includes(")", s + 2)) return; + e += i; + } + } + } + return e; + }, ar = (n) => { + if (/^[?*+@]\(\)$/.test(n) || n.includes("[:")) return false; + let t = 0; + for (let e = 0; e < n.length; e++) { + let s = n.charAt(e); + if (s === "\\") { + if (++e === n.length) return false; + } else if (s === "[") { + let i = js(n, e); + i !== -1 && (e = i); + } else if ("+@!?*".includes(s) && n.charAt(e + 1) === "(") t++, e++; + else if (s === ")") { + if (!t--) return false; + } else if (s === "|" && !t) return false; + } + return !t; + }, Pe, Rs, V = (n, t) => typeof n == "string" ? t === n : t !== "" && n.testUnchecked(t), Ps = (n, t, e, s, i) => V(n, t) ? e : s !== void 0 && V(n, s) ? i : -1, je = (n) => n === "." || n === "..", Te = (n) => typeof n == "string" && /^[a-z]:$/i.test(n), Bt = (n) => typeof n == "string" && /^unc$/i.test(n), Fe = (n) => { + if (n[0] !== "" || n[1] !== "") return -1; + let t = n[2] !== "?" ? 2 : Bt(n[3]) ? 4 : -1, e = n[t], s = n[t + 1]; + return t !== -1 && e !== void 0 && e !== "" && e !== w.GLOBSTAR && s !== void 0 && s !== "" && s !== w.GLOBSTAR ? t : -1; + }, Wt = (n, t) => !je(n) && (t || !n.startsWith(".")), ft = (n, t, e, s, i) => { + for (let r = t; r < e; ) { + if (n.charCodeAt(r) === 46) { + if (!s) return true; + let a = n.charCodeAt(r + 1) === 46 ? r + 2 : r + 1; + if (a >= e || Gt(n.charCodeAt(a), i)) return true; + } + let h = De(n, r, i); + if (h === -1) return false; + for (r = h + 1; r < e && Gt(n.charCodeAt(r), i); ) r++; + } + return false; + }, Gt = (n, t) => t === "/" ? n === 47 : t === "\\" ? n === 92 : n === 47 || n === 92, De = (n, t, e) => { + if (e !== "both") return n.indexOf(e, t); + let s = n.indexOf("/", t), i = n.indexOf("\\", t); + return s === -1 ? i : i === -1 ? s : Math.min(s, i); + }, Ts = (n, t, e) => e !== "both" ? n.lastIndexOf(e, t) : Math.max(n.lastIndexOf("/", t), n.lastIndexOf("\\", t)), ht = class { options; set; pattern; @@ -103828,19 +135730,51 @@ var require_index_min = __commonJS({ isWindows; platform; windowsNoMagicRoot; - regexp; + maxGlobstarRecursion; + #t; + #i; + #e; + #h; + #n = []; + #d = []; + #c = []; + #p = /* @__PURE__ */ new Map(); + #o = /* @__PURE__ */ new WeakMap(); 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"; + (0, zt.assertValidPattern)(t), e = e || {}, this.options = e, this.maxGlobstarRecursion = e.maxGlobstarRecursion ?? 200, this.pattern = t, this.platform = e.platform || Fs, this.isWindows = this.platform === "win32"; let s = "allowWindowsEscape"; - this.windowsPathsNoEscape = !!e.windowsPathsNoEscape || e[s] === false, this.windowsPathsNoEscape && (this.pattern = this.pattern.replace(/\\/g, "/")), this.preserveMultipleSlashes = !!e.preserveMultipleSlashes, this.regexp = null, this.negate = false, this.nonegate = !!e.nonegate, this.comment = false, this.empty = false, 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(); + this.windowsPathsNoEscape = !!e.windowsPathsNoEscape || e[s] === false, this.windowsPathsNoEscape && (this.pattern = this.pattern.replace(/\\/g, "/")), this.preserveMultipleSlashes = !!e.preserveMultipleSlashes, this.negate = false, this.nonegate = !!e.nonegate, this.comment = false, this.empty = false, 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.#t = !this.preserveMultipleSlashes, this.#e = (e.optimizationLevel ?? 1) >= 2; + let i = e.normalize; + this.#h = i === true ? "NFC" : i || void 0, this.make(); + let r = this.set.map((h) => this.#a(h)); + this.#c = this.set.map((h, a) => this.#t && h.length - 1 > r[a]), this.#n = this.set.map((h, a) => { + let o = this.#c[a] ? h.length - 1 : h.length, l = h.slice(r[a] + 1, o).filter((c) => typeof c == "string" && !!c); + return [...new Set(l)]; + }), this.#i = this.#n.some((h) => h.length), this.#d = this.set.map((h, a) => { + let [o, l, c] = h; + if (this.#c[a] && h.length === 2 && o === w.GLOBSTAR && l !== w.GLOBSTAR) return "tail"; + if (this.#c[a] && e.matchBase && h.length === 1 && o !== w.GLOBSTAR && o !== "") return "base"; + if (!(!this.#t || r[a] !== -1)) { + if (h.length === 3 && o === w.GLOBSTAR && c === w.GLOBSTAR && l !== w.GLOBSTAR && l !== "" && this.maxGlobstarRecursion > 0) return "mid"; + if (h.length === 2 && l === w.GLOBSTAR && o !== w.GLOBSTAR && o !== "") return "head"; + } + }); + } + #m(t) { + return this.#h ? t.normalize(this.#h) : t; + } + #a(t) { + if (!this.isWindows) return -1; + if (Te(t[0])) return 0; + if (t[0] === "" && t[1] === "" && t[2] === "?" && Te(t[3])) return 3; + let s = Fe(t); + return s === -1 ? -1 : s + 1; } hasMagic() { if (this.options.magicalBraces && this.set.length > 1) return true; for (let t of this.set) for (let e of t) if (typeof e != "string") return true; return false; } - debug(...t) { - } make() { let t = this.pattern, e = this.options; if (!e.nocomment && t.charAt(0) === "#") { @@ -103851,25 +135785,50 @@ var require_index_min = __commonJS({ this.empty = true; 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) => { + this.parseNegate(), this.globSet = [...new Set(this.braceExpand())]; + let s = this.globSet.map((r) => this.#S(r)); + this.globParts = this.preprocess(s); + let i = this.globParts.map((r, h, a) => { 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))]; + let o = r[2] === "?" && Bt(r[3]) ? 6 : 4, l = r[0] === "" && r[1] === "" && (r[2] === "?" || !xs.test(r[2])) && r.slice(3, o).every((u) => !xs.test(u)), c = /^[a-z]:/i.test(r[0]); + if (l) return [...r.slice(0, o).map((u) => this.#m(u)), ...r.slice(o).map((u) => this.parse(u))]; + if (c) return [this.#m(r[0]), ...r.slice(1).map((u) => this.parse(u))]; } - return r.map((a) => this.parse(a)); + return r.map((o) => this.parse(o)); }); - if (this.debug(this.pattern, i), this.set = i.filter((r) => r.indexOf(false) === -1), this.isWindows) for (let r = 0; r < this.set.length; r++) { + if (this.set = i.filter((r) => r.indexOf(false) === -1), this.isWindows) for (let r = 0; r < this.set.length; r++) { let h = this.set[r]; - h[0] === "" && h[1] === "" && this.globParts[r][2] === "?" && typeof h[3] == "string" && /^[a-z]:$/i.test(h[3]) && (h[2] = "?"); + h[0] === "" && h[1] === "" && this.globParts[r][2] === "?" && (Te(h[3]) || Bt(this.globParts[r][3])) && (Bt(this.globParts[r][3]) && (h[3] = "UNC"), h[2] = "?"); + } + e.noext || this.mergeRows(); + } + mergeRows() { + let t = true; + for (; t; ) { + t = false; + let e = Math.max(0, ...this.set.map((s) => s.length)); + for (let s = 0; s < e; s++) { + let i = /* @__PURE__ */ new Map(); + this.set.forEach((h, a) => { + if (!(h[s] instanceof ks.Matcher) || !ar(this.globParts[a][s])) return; + let o = [...this.globParts[a]]; + o[s] = ""; + let l = `${h.length}/${o.join("/")}`, c = i.get(l); + c ? c.push(a) : i.set(l, [a]); + }); + let r = /* @__PURE__ */ new Set(); + for (let h of i.values()) { + if (h.length < 2) continue; + let [a, ...o] = h, c = `@(${h.map((u) => this.globParts[u][s]).join("|")})`; + this.globParts[a][s] = c, this.set[a][s] = this.parse(c); + for (let u of o) r.add(u); + } + r.size && (t = true, this.set = this.set.filter((h, a) => !r.has(a)), this.globParts = this.globParts.filter((h, a) => !r.has(a))); + } } - this.debug(this.pattern, this.set); } preprocess(t) { - if (this.options.noglobstar) for (let s = 0; s < t.length; s++) for (let i = 0; i < t[s].length; i++) t[s][i] === "**" && (t[s][i] = "*"); + if (this.options.noglobstar) for (let s of t) for (let i = 0; i < s.length; i++) s[i] === "**" && (s[i] = "*"); let { optimizationLevel: e = 1 } = this.options; return e >= 2 ? (t = this.firstPhasePreProcess(t), t = this.secondPhasePreProcess(t)) : e >= 1 ? t = this.levelOneOptimize(t) : t = this.adjascentGlobstarOptimize(t), t; } @@ -103885,67 +135844,150 @@ var require_index_min = __commonJS({ }); } 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 = false; + return t.map((e) => { + let s = this.#a(e) + 1; + return e = e.reduce((i, r) => { + let h = i[i.length - 1]; + return r === "**" && h === "**" ? i : r === ".." && i.length > s && h && h !== ".." && h !== "." && h !== "**" ? (i.pop(), i) : (i.push(r), i); + }, []), e.length === 0 ? [""] : e; + }); + } + #l(t) { + let e = !this.isWindows || !t.includes("\\") ? "/" : t.includes("/") ? "both" : "\\", s = this.#t ? 0 : -1, i = "", r = 0, h, a = 0, o = !!this.options.dot; + t: for (let l = 0; l < this.set.length; l++) { + let c = this.set[l], u = c[c.length - 1], p = s !== -1 && this.#c[l] && u !== w.GLOBSTAR; + if (p && s === 0) { + let f = Ts(t, t.length, e); + if (r = f + 1, i = t.slice(r), i === "" && f >= 0) { + let m = f; + for (; m > 0 && Gt(t.charCodeAt(m - 1), e); ) m--; + a = m === 0 ? 0 : Ts(t, m - 1, e) + 1, h = t.slice(a, m); + } + let b = this.#e && (je(i) || i === "" && h !== void 0 && je(h)); + s = b ? -1 : 1, p = !b; + } + let d = -1; + if (p && typeof u == "string" && (d = Ps(u, i, r, h, a), d === -1)) continue; + if (this.#i) { + for (let f of this.#n[l]) if (!t.includes(f)) continue t; + } + if (p && typeof u == "object" && (d = Ps(u, i, r, h, a), d === -1)) continue; + let g = this.#d[l]; + if (g === "base" && p) return "yes"; + if (g === "tail" && p) { + if (this.#e && ft(t, 0, d, true, e)) return "maybe"; + if (!ft(t, 0, d, o, e)) return "yes"; + continue; + } + if (g === "mid" || g === "head") { + let f = this.#w(t, c, g === "head", o, e); + if (f !== "no") return f; + continue; + } + return "maybe"; + } + return "no"; + } + #r(t, e, s) { + let i = !!this.options.dot, r = t.length; + if (s === "head") { + if (r < 2 || !V(e[0], t[0])) return false; + for (let a = 1; a < r; a++) if (!Wt(t[a], i)) return false; + return true; + } + let h = e[1]; + if (s === "tail") { + let a = r - 1; + if (!V(h, t[a]) && (t[a] !== "" || r === 1 || !V(h, t[--a]))) return false; + for (let o = 0; o < a; o++) if (!Wt(t[o], i)) return false; + return true; + } + for (let a = 0; a < r; a++) { + if (V(h, t[a]) && a + 1 < r) { + let o = a + 1; + for (; o < r && Wt(t[o], i); ) o++; + if (o === r) return true; + } + if (!Wt(t[a], i)) return false; + } + return false; + } + #w(t, e, s, i, r) { + if (this.#e && ft(t, 0, t.length, true, r)) return "maybe"; + let h = e[s ? 0 : 1], a = 0; + for (let o = De(t, a, r); o !== -1; o = De(t, a, r)) { + let l = o + 1; + for (; l < t.length && Gt(t.charCodeAt(l), r); ) l++; + if ((typeof h == "string" ? o - a === h.length && t.startsWith(h, a) : o > a && h.testUnchecked(t.slice(a, o))) && !ft(t, l, t.length, i, r)) return "yes"; + if (s || ft(t, a, l, i, r)) return "no"; + a = l; + } + return "no"; + } + #_(t) { + let e = Pe; + return e?.f === t && e.isWindows === this.isWindows && e.preserveMultipleSlashes === this.preserveMultipleSlashes && e.normalize === this.#h ? e : void 0; + } + #b(t) { + let { isWindows: e, preserveMultipleSlashes: s } = this, i = this.#S(e ? t.split("\\").join("/") : t), r = this.#h; + return r && (i = i.map((h) => h.normalize(r))), Pe = { f: t, isWindows: e, preserveMultipleSlashes: s, normalize: r, parts: i }, Pe; + } + #u(t) { + let e = [...t], s = false; do { - if (e = false, !this.preserveMultipleSlashes) { - for (let i = 1; i < t.length - 1; i++) { - let r = t[i]; - i === 1 && r === "" && t[0] === "" || (r === "." || r === "") && (e = true, t.splice(i, 1), i--); + if (s = false, !this.preserveMultipleSlashes) { + for (let h = 1; h < e.length - 1; h++) { + let a = e[h]; + h === 1 && a === "" && e[0] === "" || (a === "." || a === "") && (s = true, e.splice(h, 1), h--); } - t[0] === "." && t.length === 2 && (t[1] === "." || t[1] === "") && (e = true, t.pop()); + e[0] === "." && e.length === 2 && (e[1] === "." || e[1] === "") && (s = true, e.pop()); } - let s = 0; - for (; (s = t.indexOf("..", s + 1)) !== -1; ) { - let i = t[s - 1]; - i && i !== "." && i !== ".." && i !== "**" && (e = true, t.splice(s - 1, 2), s -= 2); + let i = this.#a(e) + 1, r = i; + for (; (r = e.indexOf("..", r + 1)) !== -1; ) { + let h = e[r - 1]; + h && h !== "." && h !== ".." && h !== "**" && (s = true, e.splice(r - 1, 2), r = Math.max(r - 2, i)); } - } while (e); - return t.length === 0 ? [""] : t; + } while (s); + return e.length === 0 ? [""] : e; } firstPhasePreProcess(t) { - let e = false; + let { braceExpandMax: e = 1e5 } = this.options, s = false; do { - e = false; - for (let s of t) { - let i = -1; - for (; (i = s.indexOf("**", i + 1)) !== -1; ) { - let h = i; - for (; s[h + 1] === "**"; ) h++; - h > i && 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 = true, s.splice(i, 1); - let f = s.slice(0); - f[i] = "**", t.push(f), i--; + s = false; + for (let i of t) { + let r = -1; + for (; (r = i.indexOf("**", r + 1)) !== -1; ) { + let o = r; + for (; i[o + 1] === "**"; ) o++; + o > r && i.splice(r + 1, o - r); + let l = i[r + 1], c = i[r + 2], u = i[r + 3]; + if (l !== ".." || !c || c === "." || c === ".." || !u || u === "." || u === ".." || t.length >= e) continue; + s = true, i.splice(r, 1); + let p = i.slice(0); + p[r] = "**", t.push(p), r--; } if (!this.preserveMultipleSlashes) { - for (let h = 1; h < s.length - 1; h++) { - let o = s[h]; - h === 1 && o === "" && s[0] === "" || (o === "." || o === "") && (e = true, s.splice(h, 1), h--); + for (let o = 1; o < i.length - 1; o++) { + let l = i[o]; + o === 1 && l === "" && i[0] === "" || (l === "." || l === "") && (s = true, i.splice(o, 1), o--); } - s[0] === "." && s.length === 2 && (s[1] === "." || s[1] === "") && (e = true, s.pop()); - } - let r = 0; - for (; (r = s.indexOf("..", r + 1)) !== -1; ) { - let h = s[r - 1]; - if (h && h !== "." && h !== ".." && h !== "**") { - e = true; - let a = r === 1 && s[r + 1] === "**" ? ["."] : []; - s.splice(r - 1, 2, ...a), s.length === 0 && s.push(""), r -= 2; + i[0] === "." && i.length === 2 && (i[1] === "." || i[1] === "") && (s = true, i.pop()); + } + let h = this.#a(i) + 1, a = h; + for (; (a = i.indexOf("..", a + 1)) !== -1; ) { + let o = i[a - 1]; + if (o && o !== "." && o !== ".." && o !== "**") { + s = true; + let c = a === 1 && i[a + 1] === "**" ? ["."] : []; + i.splice(a - 1, 2, ...c), i.length === 0 && i.push(""), a = Math.max(a - 2, h); } } } - } while (e); + } while (s); return t; } secondPhasePreProcess(t) { + if (t.length > 1e3) return t; for (let e = 0; e < t.length - 1; e++) for (let s = e + 1; s < t.length; s++) { let i = this.partsMatch(t[e], t[s], !this.preserveMultipleSlashes); if (i) { @@ -103956,16 +135998,16 @@ var require_index_min = __commonJS({ return t.filter((e) => e.length); } partsMatch(t, e, s = false) { - let i = 0, r = 0, h = [], o = ""; - for (; i < t.length && r < e.length; ) if (t[i] === e[r]) h.push(o === "b" ? e[r] : t[i]), i++, r++; + let i = 0, r = 0, h = [], a = ""; + for (; i < t.length && r < e.length; ) if (t[i] === e[r]) h.push(a === "b" ? e[r] : t[i]), i++, r++; else if (s && t[i] === "**" && e[r] === t[i + 1]) h.push(t[i]), i++; else if (s && e[r] === "**" && t[i] === e[r + 1]) h.push(e[r]), r++; else if (t[i] === "*" && e[r] && (this.options.dot || !e[r].startsWith(".")) && e[r] !== "**") { - if (o === "b") return false; - o = "a", h.push(t[i]), i++, r++; + if (a === "b") return false; + a = "a", h.push(t[i]), i++, r++; } else if (e[r] === "*" && t[i] && (this.options.dot || !t[i].startsWith(".")) && t[i] !== "**") { - if (o === "a") return false; - o = "b", h.push(e[r]), i++, r++; + if (a === "a") return false; + a = "b", h.push(e[r]), i++, r++; } else return false; return t.length === e.length && h; } @@ -103975,184 +136017,184 @@ var require_index_min = __commonJS({ for (let i = 0; i < t.length && t.charAt(i) === "!"; i++) e = !e, s++; s && (this.pattern = t.slice(s)), this.negate = e; } - matchOne(t, e, s = false) { - let i = this.options; - if (this.isWindows) { - let p = typeof t[0] == "string" && /^[a-z]:$/i.test(t[0]), b = !p && t[0] === "" && t[1] === "" && t[2] === "?" && /^[a-z]:$/i.test(t[3]), w = typeof e[0] == "string" && /^[a-z]:$/i.test(e[0]), v = !w && e[0] === "" && e[1] === "" && e[2] === "?" && typeof e[3] == "string" && /^[a-z]:$/i.test(e[3]), E = b ? 3 : p ? 0 : void 0, y = v ? 3 : w ? 0 : void 0; - if (typeof E == "number" && typeof y == "number") { - let [S, B] = [t[E], e[y]]; - S.toLowerCase() === B.toLowerCase() && (e[y] = S, y > E ? 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 < a && o < l; h++, o++) { - this.debug("matchOne loop"); - var f = e[o], c = t[h]; - if (this.debug(e, f, c), f === false) return false; - if (f === g.GLOBSTAR) { - this.debug("GLOBSTAR", [e, f, c]); - var d = h, u = o + 1; - if (u === l) { - for (this.debug("** at the end"); h < a; h++) if (t[h] === "." || t[h] === ".." || !i.dot && t[h].charAt(0) === ".") return false; - return true; - } - for (; d < a; ) { - var m = t[d]; - if (this.debug(` -globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) return this.debug("globstar found match!", d, a, m), true; - if (m === "." || m === ".." || !i.dot && m.charAt(0) === ".") { - this.debug("dot detected!", t, d, e, u); - break; - } - this.debug("globstar swallow a segment, and continue"), d++; - } - return !!(s && (this.debug(` ->>> no match, partial?`, t, d, e, u), d === a)); + #v(t, e, s, i) { + let r = 0, h = 0, a = this.isWindows ? Fe(e) : -1, o = a === -1 ? -1 : Fe(s); + if (o !== -1) { + let l = s[o], c = s[o + 1]; + typeof l != "string" || typeof c != "string" ? (r = a, h = o) : e[a].toLowerCase() === l.toLowerCase() && e[a + 1].toLowerCase() === c.toLowerCase() && (r = a + 2, h = o + 2); + } else if (this.isWindows) { + let l = typeof t[0] == "string" && /^[a-z]:$/i.test(t[0]), c = !l && t[0] === "" && t[1] === "" && t[2] === "?" && /^[a-z]:$/i.test(t[3]), u = typeof s[0] == "string" && /^[a-z]:$/i.test(s[0]), p = !u && s[0] === "" && s[1] === "" && s[2] === "?" && typeof s[3] == "string" && /^[a-z]:$/i.test(s[3]), d = c ? 3 : l ? 0 : void 0, g = p ? 3 : u ? 0 : void 0; + if (typeof d == "number" && typeof g == "number") { + let [f, b] = [t[d], s[g]]; + f.toLowerCase() === b.toLowerCase() && (h = g + 1, r = d + 1); + } + } + return t = e, s.includes(w.GLOBSTAR) ? this.#y(t, s, i, r, h) : this.#g(t, s, i, r, h); + } + #y(t, e, s, i, r) { + let { head: h, body: a, tail: o, segments: l } = this.#E(e, s, r); + if (h.length) { + let u = i + h.length; + if (!this.#g(t, h, s, i, 0, u)) return false; + i += h.length, r += h.length; + } + let c = 0; + if (o.length) { + if (o.length + i > t.length) return false; + let u = t.length - o.length; + if (this.#g(t, o, s, u, 0)) c = o.length; + else { + if (t[t.length - 1] !== "" || i + o.length === t.length || (u--, !this.#g(t, o, s, u, 0))) return false; + c = o.length + 1; + } + } + if (!a.length) { + let u = !!c; + for (let p = i; p < t.length - c; p++) { + let d = String(t[p]); + if (u = true, d === "." || d === ".." || !this.options.dot && d.startsWith(".")) return false; } - 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 false; + return s || u; + } + return !!this.#O(t, l, t.length - c, i, 0, s, 0, !!c, /* @__PURE__ */ new Set()); + } + #E(t, e, s) { + let i = this.#o.get(t); + i || (i = [], this.#o.set(t, i)); + let r = s * 2 + (e ? 1 : 0), h = i[r]; + if (h) return h; + let a = t.indexOf(w.GLOBSTAR, s), o = t.lastIndexOf(w.GLOBSTAR), l = t.slice(s, a), c = t.slice(a + 1, e ? void 0 : o), u = e ? [] : t.slice(o + 1), p = [[[], 0]], d = p[0], g = 0, f = [0]; + for (let m of c) m === w.GLOBSTAR ? (f.push(g), d = [[], 0], p.push(d)) : (d[0].push(m), g++); + p.forEach((m, y) => { + m[1] = g - f[y]; + }); + let b = { head: l, body: c, tail: u, segments: p }; + return i[r] = b, b; + } + #O(t, e, s, i, r, h, a, o, l) { + let c = e[r]; + if (!c) { + if (h) return i >= s || i === s - 1 && t[i] === ""; + for (let g = i; g < s; g++) { + o = true; + let f = t[g]; + if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) return false; + } + return o; + } + let [u, p] = c, d = h ? s : s - p; + for (; i <= d; ) { + let g = r * (t.length + 1) + i; + if (l.has(g)) return false; + if (l.add(g), this.#g(t, u, h, i, 0, i + u.length) && a < this.maxGlobstarRecursion) { + let m = this.#O(t, e, s, i + u.length, r + 1, h, a + 1, o, l); + if (m !== false) return m; + } + if (i === d) break; + let b = t[i]; + if (b === "." || b === ".." || !this.options.dot && b.startsWith(".")) return false; + i++; } - if (h === a && o === l) return true; - if (h === a) return s; - if (o === l) return h === a - 1 && t[h] === ""; + return h || null; + } + #g(t, e, s, i, r, h = t.length) { + let a, o, l, c; + for (a = i, o = r, c = Math.min(h, t.length), l = e.length; a < c && o < l; a++, o++) { + let u = e[o], p = t[a]; + if (u === false || u === w.GLOBSTAR || !V(u, p)) return false; + } + if (a === c && o === l) return true; + if (a === c) return s; + if (o === l) return a === c - 1 && t[a] === ""; throw new Error("wtf?"); } braceExpand() { - return (0, g.braceExpand)(this.pattern, this.options); + return (0, w.braceExpand)(this.pattern, this.options); } parse(t) { - (0, jt.assertValidPattern)(t); + (0, zt.assertValidPattern)(t); let e = this.options; - if (t === "**") return g.GLOBSTAR; + if (t === "**") return w.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 === false) return this.regexp; - let t = this.set; - if (!t.length) return this.regexp = false, 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 = false; - } - return this.regexp; + let { nocase: s, nocaseMagicOnly: i, noext: r = false, dot: h, normalize: a } = e, o = or2(t, r); + if (o !== void 0 && !(s && !i && t.toUpperCase() !== t.toLowerCase())) return this.#m(o); + let l = this.#p.get(t); + return l || (l = new ks.Matcher(t, { nocase: s, noext: r, dot: h, normalize: a }), this.#p.set(t, l)), l; } - slashSplit(t) { - return this.preserveMultipleSlashes ? t.split("/") : this.isWindows && /^\/\/[^\/]+/.test(t) ? ["", ...t.split(/\/+/)] : t.split(/\/+/); + #S(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 false; + if (this.comment) return false; if (this.empty) return t === ""; if (t === "/" && e) return true; - 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 < r.length; o++) { - let a = r[o], l = i; - if (s.matchBase && a.length === 1 && (l = [h]), this.matchOne(l, a, e)) return s.flipNegate ? true : !this.negate; + let s = this.options, i = this.#_(t); + if (!i) { + if (!e && !this.#h && (this.#t || this.#i) && Rs !== t) { + Rs = t; + let l = this.#l(t); + if (l === "no") return s.flipNegate ? false : this.negate; + if (l === "yes") return s.flipNegate ? true : !this.negate; + } + i = this.#b(t); + } + let r = i.parts, h = this.#e ? i.resolved ??= this.#u(r) : r, a = this.set, o = r[r.length - 1]; + if (!o) for (let l = r.length - 2; !o && l >= 0; l--) o = r[l]; + for (let l = 0; l < a.length; l++) { + let c = a[l], u = e ? void 0 : this.#d[l]; + if (u === "base" ? V(c[0], o) : u ? this.#r(h, c, u) : s.matchBase && c.length === 1 ? this.#v([o], [o], c, e) : this.#v(r, h, c, e)) return s.flipNegate ? true : !this.negate; } return s.flipNegate ? false : this.negate; } static defaults(t) { - return g.minimatch.defaults(t).Minimatch; + return w.minimatch.defaults(t).Minimatch; } }; - g.Minimatch = J; - var Zi = pe(); - Object.defineProperty(g, "AST", { enumerable: true, get: function() { - return Zi.AST; + w.Minimatch = ht; + var lr = xe(); + Object.defineProperty(w, "escape", { enumerable: true, get: function() { + return lr.escape; } }); - var Qi = me(); - Object.defineProperty(g, "escape", { enumerable: true, get: function() { - return Qi.escape; + var cr2 = Re(); + Object.defineProperty(w, "unescape", { enumerable: true, get: function() { + return cr2.unescape; } }); - var tr = kt(); - Object.defineProperty(g, "unescape", { enumerable: true, get: function() { - return tr.unescape; - } }); - g.minimatch.AST = is.AST; - g.minimatch.Minimatch = J; - g.minimatch.escape = vi.escape; - g.minimatch.unescape = Ei.unescape; + w.minimatch.Minimatch = ht; + w.minimatch.escape = tr.escape; + w.minimatch.unescape = er.unescape; }); - var fs32 = R((Wt) => { + var zs = x((Ut) => { "use strict"; - Object.defineProperty(Wt, "__esModule", { value: true }); - Wt.LRUCache = void 0; - var er = typeof performance == "object" && performance && typeof performance.now == "function" ? performance : Date, as = /* @__PURE__ */ 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, os7 = globalThis.AbortSignal; - if (typeof Lt > "u") { - os7 = class { - onabort; - _onabort = []; - reason; - aborted = false; - addEventListener(e, s) { - this._onabort.push(s); - } - }, Lt = class { - constructor() { - t(); - } - signal = new os7(); - abort(e) { - if (!this.signal.aborted) { - this.signal.reason = e, this.signal.aborted = true; - 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 = false, 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 { + var Ns = (n, t) => () => (t || n((t = { exports: {} }).exports, t), t.exports), ur = Ns((n) => { + "use strict"; + Object.defineProperty(n, "__esModule", { value: true }), n.tracing = n.metrics = void 0; + var t = require("node:diagnostics_channel"); + n.metrics = (0, t.channel)("lru-cache:metrics"), n.tracing = (0, t.tracingChannel)("lru-cache"); + }), fr = Ns((n) => { + "use strict"; + Object.defineProperty(n, "__esModule", { value: true }), n.defaultPerf = void 0, n.defaultPerf = typeof performance == "object" && performance && typeof performance.now == "function" ? performance : Date; + }); + Object.defineProperty(Ut, "__esModule", { value: true }); + Ut.LRUCache = void 0; + var O = ur(), dr = fr(), Ne = () => O.metrics.hasSubscribers || O.tracing.hasSubscribers, Ls = /* @__PURE__ */ new Set(), Ds = typeof process == "object" && process ? process : {}, pr = (n, t, e, s) => { + typeof Ds.emitWarning == "function" ? Ds.emitWarning(n, t, e, s) : console.error(`[${e}] ${t}: ${n}`); + }, mr = (n) => !Ls.has(n), Z = (n) => !!n && n === Math.floor(n) && n > 0 && isFinite(n), Ws = (n) => Z(n) ? n <= Math.pow(2, 8) ? Uint8Array : n <= Math.pow(2, 16) ? Uint16Array : n <= Math.pow(2, 32) ? Uint32Array : n <= Number.MAX_SAFE_INTEGER ? It : null : null, It = class extends Array { constructor(n) { super(n), this.fill(0); } - }, ir = class at { + }, gr = class dt { heap; length; static #t = false; static create(t) { - let e = cs(t); + let e = Ws(t); if (!e) return []; - at.#t = true; - let s = new at(t, e); - return at.#t = false, s; + dt.#t = true; + let s = new dt(t, e); + return dt.#t = false, s; } constructor(t, e) { - if (!at.#t) throw new TypeError("instantiate Stack using Stack.create(n)"); + if (!dt.#t) throw new TypeError("instantiate Stack using Stack.create(n)"); this.heap = new e(t), this.length = 0; } push(t) { @@ -104161,17 +136203,17 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur pop() { return this.heap[--this.length]; } - }, rr = class us { + }, wr = class Bs { #t; - #s; - #n; - #r; + #i; + #e; #h; - #S; - #w; + #n; + #d; #c; + #p; get perf() { - return this.#c; + return this.#p; } ttl; ttlResolution; @@ -104188,253 +136230,264 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur allowStaleOnFetchAbort; allowStaleOnFetchRejection; ignoreFetchAbort; + backgroundFetchSize; #o; - #f; - #u; + #m; #a; - #i; - #d; + #l; + #r; + #w; + #_; + #b; + #u; #v; #y; - #p; - #R; - #m; + #E; #O; - #x; #g; - #b; - #E; - #T; - #e; - #F; + #S; + #C; + #M; + #s; + #P; 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; + return { starts: t.#O, ttls: t.#g, autopurgeTimers: t.#S, sizes: t.#E, keyMap: t.#a, keyList: t.#l, valList: t.#r, next: t.#w, prev: t.#_, get head() { + return t.#b; }, 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) }; + return t.#u; + }, free: t.#v, isBackgroundFetch: (e) => t.#f(e), backgroundFetch: (e, s, i, r) => t.#L(e, s, i, r), moveToTail: (e) => t.#K(e), indexes: (e) => t.#x(e), rindexes: (e) => t.#R(e), isStale: (e) => t.#A(e) }; } get max() { return this.#t; } get maxSize() { - return this.#s; + return this.#i; } get calculatedSize() { - return this.#f; + return this.#m; } get size() { return this.#o; } get fetchMethod() { - return this.#S; + return this.#d; } get memoMethod() { - return this.#w; + return this.#c; } get dispose() { - return this.#n; + return this.#e; } get onInsert() { - return this.#r; + return this.#h; } get disposeAfter() { - return this.#h; + return this.#n; } 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"); + let { max: e = 0, ttl: s, ttlResolution: i = 1, ttlAutopurge: r, updateAgeOnGet: h, updateAgeOnHas: a, allowStale: o, dispose: l, onInsert: c, disposeAfter: u, noDisposeOnSet: p, noUpdateTTL: d, maxSize: g = 0, maxEntrySize: f = 0, sizeCalculation: b, fetchMethod: m, memoMethod: y, noDeleteOnFetchRejection: _2, noDeleteOnStaleGet: v, allowStaleOnFetchRejection: S, allowStaleOnFetchAbort: K, ignoreFetchAbort: z, backgroundFetchSize: $ = 1, perf: nt } = t; + if (this.backgroundFetchSize = $, nt !== void 0 && typeof nt?.now != "function") throw new TypeError("perf option must have a now() method if specified"); + if (this.#p = nt ?? dr.defaultPerf, e !== 0 && !Z(e)) throw new TypeError("max option must be a nonnegative integer"); + let ge = e ? Ws(e) : Array; + if (!ge) throw new Error("invalid max value: " + e); + if (this.#t = e, this.#i = g, this.maxEntrySize = f || this.#i, this.sizeCalculation = b, this.sizeCalculation) { + if (!this.#i && !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 = /* @__PURE__ */ 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"); + if (y !== void 0 && typeof y != "function") throw new TypeError("memoMethod must be a function if defined"); + if (this.#c = y, m !== void 0 && typeof m != "function") throw new TypeError("fetchMethod must be a function if specified"); + if (this.#d = m, this.#M = !!m, this.#a = /* @__PURE__ */ new Map(), this.#l = Array.from({ length: e }).fill(void 0), this.#r = Array.from({ length: e }).fill(void 0), this.#w = new ge(e), this.#_ = new ge(e), this.#b = 0, this.#u = 0, this.#v = gr.create(e), this.#o = 0, this.#m = 0, typeof l == "function" && (this.#e = l), typeof c == "function" && (this.#h = c), typeof u == "function" ? (this.#n = u, this.#y = []) : (this.#n = void 0, this.#y = void 0), this.#C = !!this.#e, this.#P = !!this.#h, this.#s = !!this.#n, this.noDisposeOnSet = !!p, this.noUpdateTTL = !!d, this.noDeleteOnFetchRejection = !!_2, this.allowStaleOnFetchRejection = !!S, this.allowStaleOnFetchAbort = !!K, this.ignoreFetchAbort = !!z, this.maxEntrySize !== 0) { + if (this.#i !== 0 && !Z(this.#i)) throw new TypeError("maxSize must be a positive integer if specified"); + if (!Z(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.allowStale = !!o, this.noDeleteOnStaleGet = !!v, this.updateAgeOnGet = !!h, this.updateAgeOnHas = !!a, this.ttlResolution = Z(i) || i === 0 ? i : 1, this.ttlAutopurge = !!r, this.ttl = s || 0, this.ttl) { + if (!Z(this.ttl)) throw new TypeError("ttl must be a positive integer if specified"); + this.#T(); } - 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)); + if (this.#t === 0 && this.ttl === 0 && this.#i === 0) throw new TypeError("At least one of max, maxSize, or ttl is required"); + if (!this.ttlAutopurge && !this.#t && !this.#i) { + let we = "LRU_CACHE_UNBOUNDED"; + mr(we) && (Ls.add(we), pr("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.", "UnboundedCacheWarning", we, Bs)); } } 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; + return this.#a.has(t) ? 1 / 0 : 0; + } + #T() { + let t = new It(this.#t), e = new It(this.#t); + this.#g = t, this.#O = e; + let s = this.ttlAutopurge ? Array.from({ length: this.#t }) : void 0; + this.#S = s, this.#B = (o, l, c = this.#p.now()) => { + e[o] = l !== 0 ? c : 0, t[o] = l, i(o, l); + }, this.#k = (o) => { + e[o] = t[o] !== 0 ? this.#p.now() : 0, i(o, t[o]); + }; + let i = this.ttlAutopurge ? (o, l) => { + if (s?.[o] && (clearTimeout(s[o]), s[o] = void 0), l && l !== 0 && s) { + let c = setTimeout(() => { + this.#A(o) ? (this.#W(this.#l[o], "expire"), s[o] = void 0) : i(o, a(o)); + }, l + 1); + c.unref && c.unref(), s[o] = c; + } + } : () => { + }; + this.#F = (o, l) => { + if (t[l]) { + let c = t[l], u = e[l]; + if (!c || !u) return; + o.ttl = c, o.start = u, o.now = r || h(); + let p = o.now - u; + o.remainingTTL = c - p; } }; - let i = 0, r = () => { - let h = this.#c.now(); + let r = 0, h = () => { + let o = this.#p.now(); if (this.ttlResolution > 0) { - i = h; - let o = setTimeout(() => i = 0, this.ttlResolution); - o.unref && o.unref(); + r = o; + let l = setTimeout(() => r = 0, this.ttlResolution); + l.unref && l.unref(); } - return h; + return o; + }; + this.getRemainingTTL = (o) => { + let l = this.#a.get(o); + return l === void 0 ? 0 : a(l); + }; + let a = (o) => { + let l = t[o], c = e[o]; + if (!l || !c) return 1 / 0; + let u = (r || h()) - c; + return l - u; }; - 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; + this.#A = (o) => { + let l = e[o], c = t[o]; + return !!c && !!l && (r || h()) - l > c; }; } - #C = () => { + #k = () => { }; - #D = () => { + #F = () => { }; - #W = () => { + #B = () => { }; - #_ = () => false; + #A = () => false; #$() { - 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."); + let t = new It(this.#t); + this.#m = 0, this.#E = t, this.#D = (e) => { + this.#m -= t[e], t[e] = 0; + }, this.#z = (e, s, i, r) => { + if (!Z(i)) { + if (this.#f(s)) return this.backgroundFetchSize; + if (r) { + if (typeof r != "function") throw new TypeError("sizeCalculation must be a function"); + if (i = r(s, e), !Z(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(true); + if (t[e] = s, this.#i) { + let r = this.#i - t[e]; + for (; this.#m > r; ) this.#U(true); } - this.#f += t[e], i && (i.entrySize = s, i.totalCalculatedSize = this.#f); + this.#m += t[e], i && (i.entrySize = s, i.totalCalculatedSize = this.#m); }; } - #L = (t) => { + #D = (t) => { }; #j = (t, e, s) => { }; - #B = (t, e, s, i) => { + #z = (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]; + *#x({ allowStale: t = this.allowStale } = {}) { + if (this.#o) for (let e = this.#u; this.#G(e) && ((t || !this.#A(e)) && (yield e), e !== this.#b); ) e = this.#_[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]; + *#R({ allowStale: t = this.allowStale } = {}) { + if (this.#o) for (let e = this.#b; this.#G(e) && ((t || !this.#A(e)) && (yield e), e !== this.#u); ) e = this.#w[e]; } - #I(t) { - return t !== void 0 && this.#u.get(this.#a[t]) === t; + #G(t) { + return t !== void 0 && this.#a.get(this.#l[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]]); + for (let t of this.#x()) this.#r[t] !== void 0 && this.#l[t] !== void 0 && !this.#f(this.#r[t]) && (yield [this.#l[t], this.#r[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]]); + for (let t of this.#R()) this.#r[t] !== void 0 && this.#l[t] !== void 0 && !this.#f(this.#r[t]) && (yield [this.#l[t], this.#r[t]]); } *keys() { - for (let t of this.#k()) { - let e = this.#a[t]; - e !== void 0 && !this.#l(this.#i[t]) && (yield e); + for (let t of this.#x()) { + let e = this.#l[t]; + e !== void 0 && !this.#f(this.#r[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); + for (let t of this.#R()) { + let e = this.#l[t]; + e !== void 0 && !this.#f(this.#r[t]) && (yield e); } } *values() { - for (let t of this.#k()) this.#i[t] !== void 0 && !this.#l(this.#i[t]) && (yield this.#i[t]); + for (let t of this.#x()) this.#r[t] !== void 0 && !this.#f(this.#r[t]) && (yield this.#r[t]); } *rvalues() { - for (let t of this.#M()) this.#i[t] !== void 0 && !this.#l(this.#i[t]) && (yield this.#i[t]); + for (let t of this.#R()) this.#r[t] !== void 0 && !this.#f(this.#r[t]) && (yield this.#r[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); + for (let s of this.#x()) { + let i = this.#r[s], r = this.#f(i) ? i.__staleWhileFetching : i; + if (r !== void 0 && t(r, this.#l[s], this)) return this.#X(this.#l[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); + for (let s of this.#x()) { + let i = this.#r[s], r = this.#f(i) ? i.__staleWhileFetching : i; + r !== void 0 && t.call(e, r, this.#l[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); + for (let s of this.#R()) { + let i = this.#r[s], r = this.#f(i) ? i.__staleWhileFetching : i; + r !== void 0 && t.call(e, r, this.#l[s], this); } } purgeStale() { let t = false; - for (let e of this.#M({ allowStale: true })) this.#_(e) && (this.#A(this.#a[e], "expire"), t = true); + for (let e of this.#R({ allowStale: true })) this.#A(e) && (this.#W(this.#l[e], "expire"), t = true); return t; } info(t) { - let e = this.#u.get(t); + let e = this.#a.get(t); if (e === void 0) return; - let s = this.#i[e], i = this.#l(s) ? s.__staleWhileFetching : s; + let s = this.#r[e], i = this.#f(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(); + if (this.#g && this.#O) { + let h = this.#g[e], a = this.#O[e]; + if (h && a) { + let o = h - (this.#p.now() - a); + r.ttl = o, r.start = Date.now(); } } - return this.#O && (r.size = this.#O[e]), r; + return this.#E && (r.size = this.#E[e]), r; } dump() { let t = []; - for (let e of this.#k({ allowStale: true })) { - let s = this.#a[e], i = this.#i[e], r = this.#l(i) ? i.__staleWhileFetching : i; + for (let e of this.#x({ allowStale: true })) { + let s = this.#l[e], i = this.#r[e], r = this.#f(i) ? i.__staleWhileFetching : i; if (r === void 0 || s === void 0) continue; let h = { value: r }; - if (this.#g && this.#x) { + if (this.#g && this.#O) { h.ttl = this.#g[e]; - let o = this.#c.now() - this.#x[e]; - h.start = Math.floor(Date.now() - o); + let a = this.#p.now() - this.#O[e]; + h.start = Math.floor(Date.now() - a); } - this.#O && (h.size = this.#O[e]), t.unshift([s, h]); + this.#E && (h.size = this.#E[e]), t.unshift([s, h]); } return t; } @@ -104443,223 +136496,278 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur for (let [e, s] of t) { if (s.start) { let i = Date.now() - s.start; - s.start = this.#c.now() - i; + s.start = this.#p.now() - i; } - this.set(e, s.value, s); + this.#N(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 = true), 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(false) : 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 = false, this.#F && this.#r?.(e, t, "add"); + let { status: i = O.metrics.hasSubscribers ? {} : void 0 } = s; + s.status = i, i && (i.op = "set", i.key = t, e !== void 0 && (i.value = e), i.cache = this); + let r = this.#N(t, e, s); + return i && O.metrics.hasSubscribers && O.metrics.publish(i), r; + } + #N(t, e, s, i) { + let { ttl: r = this.ttl, start: h, noDisposeOnSet: a = this.noDisposeOnSet, sizeCalculation: o = this.sizeCalculation, status: l } = s, c = this.#f(e); + if (e === void 0) return l && (l.set = "deleted"), this.delete(t), this; + let { noUpdateTTL: u = this.noUpdateTTL } = s; + l && !c && (l.value = e); + let p = this.#z(t, e, s.size || 0, o, l); + if (this.maxEntrySize && p > this.maxEntrySize) return this.#W(t, "set"), l && (l.set = "miss", l.maxEntrySizeExceeded = true), this; + let d = this.#o === 0 ? void 0 : this.#a.get(t); + if (d === void 0) d = this.#o === 0 ? this.#u : this.#v.length !== 0 ? this.#v.pop() : this.#o === this.#t ? this.#U(false) : this.#o, this.#l[d] = t, this.#r[d] = e, this.#a.set(t, d), this.#w[this.#u] = d, this.#_[d] = this.#u, this.#u = d, this.#o++, this.#j(d, p, l), l && (l.set = "add"), u = false, this.#P && !c && this.#h?.(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); + this.#K(d); + let g = this.#r[d]; + if (e !== g) { + if (!a) if (this.#f(g)) { + g !== i && g.__abortController.abort(new Error("replaced")); + let { __staleWhileFetching: f } = g; + f !== void 0 && f !== e && (this.#C && this.#e?.(f, t, "set"), this.#s && this.#y?.push([f, t, "set"])); + } else this.#C && this.#e?.(g, t, "set"), this.#s && this.#y?.push([g, t, "set"]); + if (this.#D(d), this.#j(d, p, l), this.#r[d] = e, !c) { + let f = g && this.#f(g) ? g.__staleWhileFetching : g, b = f === void 0 ? "add" : e !== f ? "replace" : "update"; + l && (l.set = b, f !== void 0 && (l.oldValue = f)), this.#P && this.onInsert?.(e, t, b); + } + } else c || (l && (l.set = "update"), this.#P && this.onInsert?.(e, t, "update")); + } + if (r !== 0 && !this.#g && this.#T(), this.#g && (u || this.#B(d, r, h), l && this.#F(l, d)), !a && this.#s && this.#y) { + let g = this.#y, f; + for (; f = g?.shift(); ) this.#n?.(...f); } return this; } pop() { try { for (; this.#o; ) { - let t = this.#i[this.#y]; - if (this.#G(true), this.#l(t)) { + let t = this.#r[this.#b]; + if (this.#U(true), this.#f(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); + if (this.#s && this.#y) { + let t = this.#y, e; + for (; e = t?.shift(); ) this.#n?.(...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; + #U(t) { + let e = this.#b, s = this.#l[e], i = this.#r[e], r = this.#f(i); + r && i.__abortController.abort(new Error("evicted")); + let h = r ? i.__staleWhileFetching : i; + return (this.#C || this.#s) && h !== void 0 && (this.#C && this.#e?.(h, s, "evict"), this.#s && this.#y?.push([h, s, "evict"])), this.#D(e), this.#S?.[e] && (clearTimeout(this.#S[e]), this.#S[e] = void 0), t && (this.#l[e] = void 0, this.#r[e] = void 0, this.#v.push(e)), this.#o === 1 ? (this.#b = this.#u = 0, this.#v.length = 0) : this.#b = this.#w[e], this.#a.delete(s), this.#o--, e; } has(t, e = {}) { - let { updateAgeOnHas: s = this.updateAgeOnHas, status: i } = e, r = this.#u.get(t); + let { status: s = O.metrics.hasSubscribers ? {} : void 0 } = e; + e.status = s, s && (s.op = "has", s.key = t, s.cache = this); + let i = this.#V(t, e); + return O.metrics.hasSubscribers && O.metrics.publish(s), i; + } + #V(t, e = {}) { + let { updateAgeOnHas: s = this.updateAgeOnHas, status: i } = e, r = this.#a.get(t); if (r !== void 0) { - let h = this.#i[r]; - if (this.#l(h) && h.__staleWhileFetching === void 0) return false; - 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)), true; + let h = this.#r[r]; + if (this.#f(h) && h.__staleWhileFetching === void 0) return false; + if (this.#A(r)) i && (i.has = "stale", this.#F(i, r)); + else return s && this.#k(r), i && (i.has = "hit", this.#F(i, r)), true; } else i && (i.has = "miss"); return false; } 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 = false) => { - 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 = true, s.status.fetchError = h.signal.reason, v && (s.status.fetchAbortIgnored = true)) : s.status.fetchResolved = true), 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 = true), this.set(t, p, a.options))), p; - }, f = (p) => (s.status && (s.status.fetchRejected = true, s.status.fetchError = p), c(p, false)), 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 = true), 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, true))); - }); + let { status: s = Ne() ? {} : void 0 } = e; + s && (s.op = "peek", s.key = t, s.cache = this), e.status = s; + let i = this.#q(t, e); + return O.metrics.hasSubscribers && O.metrics.publish(s), i; + } + #q(t, e) { + let { status: s, allowStale: i = this.allowStale } = e, r = this.#a.get(t); + if (r === void 0 || !i && this.#A(r)) { + s && (s.peek = r === void 0 ? "miss" : "stale"); + return; + } + let h = this.#r[r], a = this.#f(h) ? h.__staleWhileFetching : h; + return s && (a !== void 0 ? (s.peek = "hit", s.value = a) : s.peek = "miss"), a; + } + #L(t, e, s, i) { + let r = e === void 0 ? void 0 : this.#r[e]; + if (this.#f(r)) return r; + let h = new AbortController(), { signal: a } = s; + a?.addEventListener("abort", () => h.abort(a.reason), { signal: h.signal }); + let o = { signal: h.signal, options: s, context: i }, l = (f, b = false) => { + let { aborted: m } = h.signal, y = s.ignoreFetchAbort && f !== void 0, _2 = s.ignoreFetchAbort || !!(s.allowStaleOnFetchAbort && f !== void 0); + if (s.status && (m && !b ? (s.status.fetchAborted = true, s.status.fetchError = h.signal.reason, y && (s.status.fetchAbortIgnored = true)) : s.status.fetchResolved = true), m && !y && !b) return u(h.signal.reason, _2); + let v = d, S = this.#r[e]; + return (S === d || S === void 0 && y && b) && (f === void 0 ? v.__staleWhileFetching !== void 0 ? this.#r[e] = v.__staleWhileFetching : this.#W(t, "fetch") : (s.status && (s.status.fetchUpdated = true), this.#N(t, f, o.options, v))), f; + }, c = (f) => (s.status && (s.status.fetchRejected = true, s.status.fetchError = f), u(f, false)), u = (f, b) => { + let { aborted: m } = h.signal, y = m && s.allowStaleOnFetchAbort, _2 = y || s.allowStaleOnFetchRejection, v = _2 || s.noDeleteOnFetchRejection, S = d; + if (this.#r[e] === d && (!v || !b && S.__staleWhileFetching === void 0 ? this.#W(t, "fetch") : y || (this.#r[e] = S.__staleWhileFetching)), _2) return s.status && S.__staleWhileFetching !== void 0 && (s.status.returnedStale = true), S.__staleWhileFetching; + if (S.__returned === S) throw f; + }, p = (f, b) => { + let m = this.#d?.(t, r, o); + h.signal.addEventListener("abort", () => { + (!s.ignoreFetchAbort || s.allowStaleOnFetchAbort) && (f(void 0), s.allowStaleOnFetchAbort && (f = (y) => l(y, true))); + }), m && m instanceof Promise ? m.then((y) => f(y === void 0 ? void 0 : y), b) : m !== void 0 && f(m); }; s.status && (s.status.fetchDispatched = true); - 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; + let d = new Promise(p).then(l, c), g = Object.assign(d, { __abortController: h, __staleWhileFetching: r, __returned: void 0 }); + return e === void 0 ? (this.#N(t, g, { ...o.options, status: void 0 }), e = this.#a.get(t)) : this.#r[e] = g, g; } - #l(t) { - if (!this.#T) return false; + #f(t) { + if (!this.#M) return false; 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 = false, 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 !!e && e instanceof Promise && e.hasOwnProperty("__staleWhileFetching") && e.__abortController instanceof AbortController; + } + fetch(t, e = {}) { + let s = O.tracing.hasSubscribers, { status: i = Ne() ? {} : void 0 } = e; + e.status = i, i && e.context && (i.context = e.context); + let r = this.#H(t, e); + return i && s && (i.trace = true, O.tracing.tracePromise(() => r, i).catch(() => { + })), r; + } + async #H(t, e = {}) { + let { allowStale: s = this.allowStale, updateAgeOnGet: i = this.updateAgeOnGet, noDeleteOnStaleGet: r = this.noDeleteOnStaleGet, ttl: h = this.ttl, noDisposeOnSet: a = this.noDisposeOnSet, size: o = 0, sizeCalculation: l = this.sizeCalculation, noUpdateTTL: c = this.noUpdateTTL, noDeleteOnFetchRejection: u = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection: p = this.allowStaleOnFetchRejection, ignoreFetchAbort: d = this.ignoreFetchAbort, allowStaleOnFetchAbort: g = this.allowStaleOnFetchAbort, context: f, forceRefresh: b = false, status: m, signal: y } = e; + if (m && (m.op = "fetch", m.key = t, b && (m.forceRefresh = true), m.cache = this), !this.#M) return m && (m.fetch = "get"), this.#X(t, { allowStale: s, updateAgeOnGet: i, noDeleteOnStaleGet: r, status: m }); + let _2 = { allowStale: s, updateAgeOnGet: i, noDeleteOnStaleGet: r, ttl: h, noDisposeOnSet: a, size: o, sizeCalculation: l, noUpdateTTL: c, noDeleteOnFetchRejection: u, allowStaleOnFetchRejection: p, allowStaleOnFetchAbort: g, ignoreFetchAbort: d, status: m, signal: y }, v = this.#a.get(t); + if (v === void 0) { + m && (m.fetch = "miss"); + let S = this.#L(t, v, _2, f); 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 = true)), 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 = true)), et ? U.__staleWhileFetching : U.__returned = U; - } - } - async forceFetch(t, e = {}) { - let s = await this.fetch(t, e); + let S = this.#r[v]; + if (this.#f(S)) { + let nt = s && S.__staleWhileFetching !== void 0; + return m && (m.fetch = "inflight", nt && (m.returnedStale = true)), nt ? S.__staleWhileFetching : S.__returned = S; + } + let K = this.#A(v); + if (!b && !K) return m && (m.fetch = "hit"), this.#K(v), i && this.#k(v), m && this.#F(m, v), S; + let z = this.#L(t, v, _2, f), $ = z.__staleWhileFetching !== void 0 && s; + return m && (m.fetch = K ? "stale" : "refresh", $ && K && (m.returnedStale = true)), $ ? z.__staleWhileFetching : z.__returned = z; + } + } + forceFetch(t, e = {}) { + let s = O.tracing.hasSubscribers, { status: i = Ne() ? {} : void 0 } = e; + e.status = i, i && e.context && (i.context = e.context); + let r = this.#I(t, e); + return i && s && (i.trace = true, O.tracing.tracePromise(() => r, i).catch(() => { + })), r; + } + async #I(t, e = {}) { + let s = await this.#H(t, e); if (s === void 0) throw new Error("fetch() returned undefined"); return s; } memo(t, e = {}) { - let s = this.#w; + let { status: s = O.metrics.hasSubscribers ? {} : void 0 } = e; + e.status = s, s && (s.op = "memo", s.key = t, e.context && (s.context = e.context), s.cache = this); + let i = this.#J(t, e); + return s && (s.value = i), O.metrics.hasSubscribers && O.metrics.publish(s), i; + } + #J(t, e = {}) { + let s = this.#c; 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; + let { context: i, status: r, forceRefresh: h, ...a } = e; + r && h && (r.forceRefresh = true); + let o = this.#X(t, a), l = h || o === void 0; + if (r && (r.memo = l ? "miss" : "hit", l || (r.value = o)), !l) return o; + let c = s(t, o, { options: a, context: i }); + return r && (r.value = c), this.#N(t, c, a), c; } 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 = true), s ? a.__staleWhileFetching : void 0) : (r || this.#A(t, "expire"), h && s && (h.returnedStale = true), s ? a : void 0)) : (h && (h.get = "hit"), l ? a.__staleWhileFetching : (this.#N(o), i && this.#C(o), a)); - } else h && (h.get = "miss"); + let { status: s = O.metrics.hasSubscribers ? {} : void 0 } = e; + e.status = s, s && (s.op = "get", s.key = t, s.cache = this); + let i = this.#X(t, e); + return s && (i !== void 0 && (s.value = i), O.metrics.hasSubscribers && O.metrics.publish(s)), i; + } + #X(t, e = {}) { + let { allowStale: s = this.allowStale, updateAgeOnGet: i = this.updateAgeOnGet, noDeleteOnStaleGet: r = this.noDeleteOnStaleGet, status: h } = e, a = this.#a.get(t); + if (a === void 0) { + h && (h.get = "miss"); + return; + } + let o = this.#r[a], l = this.#f(o); + return h && this.#F(h, a), this.#A(a) ? l ? (h && (h.get = "stale-fetching"), s && o.__staleWhileFetching !== void 0 ? (h && (h.returnedStale = true), o.__staleWhileFetching) : void 0) : (r || this.#W(t, "expire"), h && (h.get = "stale"), s ? (h && (h.returnedStale = true), o) : void 0) : (h && (h.get = l ? "fetching" : "hit"), this.#K(a), i && this.#k(a), l ? o.__staleWhileFetching : o); } - #U(t, e) { - this.#v[e] = t, this.#d[t] = e; + #Y(t, e) { + this.#_[e] = t, this.#w[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); + #K(t) { + t !== this.#u && (t === this.#b ? this.#b = this.#w[t] : this.#Y(this.#_[t], this.#w[t]), this.#Y(this.#u, t), this.#u = t); } delete(t) { - return this.#A(t, "delete"); + return this.#W(t, "delete"); } - #A(t, e) { + #W(t, e) { + O.metrics.hasSubscribers && O.metrics.publish({ op: "delete", delete: e, key: t, cache: this }); let s = false; 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 = true, this.#o === 1) this.#q(e); + let i = this.#a.get(t); + if (i !== void 0) if (this.#S?.[i] && (clearTimeout(this.#S[i]), this.#S[i] = void 0), s = true, this.#o === 1) this.#Z(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]; + this.#D(i); + let r = this.#r[i]; + if (this.#f(r) ? r.__abortController.abort(new Error("deleted")) : (this.#C || this.#s) && (this.#C && this.#e?.(r, t, e), this.#s && this.#y?.push([r, t, e])), this.#a.delete(t), this.#l[i] = void 0, this.#r[i] = void 0, i === this.#u) this.#u = this.#_[i]; + else if (i === this.#b) this.#b = this.#w[i]; else { - let h = this.#v[i]; - this.#d[h] = this.#d[i]; - let o = this.#d[i]; - this.#v[o] = this.#v[i]; + let h = this.#_[i]; + this.#w[h] = this.#w[i]; + let a = this.#w[i]; + this.#_[a] = this.#_[i]; } - this.#o--, this.#R.push(i); + this.#o--, this.#v.push(i); } } - if (this.#e && this.#m?.length) { - let i = this.#m, r; - for (; r = i?.shift(); ) this.#h?.(...r); + if (this.#s && this.#y?.length) { + let i = this.#y, r; + for (; r = i?.shift(); ) this.#n?.(...r); } return s; } clear() { - return this.#q("delete"); + return this.#Z("delete"); } - #q(t) { - for (let e of this.#M({ allowStale: true })) { - let s = this.#i[e]; - if (this.#l(s)) s.__abortController.abort(new Error("deleted")); + #Z(t) { + for (let e of this.#R({ allowStale: true })) { + let s = this.#r[e]; + if (this.#f(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]); + let i = this.#l[e]; + this.#C && this.#e?.(s, i, t), this.#s && this.#y?.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.#a.clear(), this.#r.fill(void 0), this.#l.fill(void 0), this.#g && this.#O) { + this.#g.fill(0), this.#O.fill(0); + for (let e of this.#S ?? []) e !== void 0 && clearTimeout(e); + this.#S?.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); + if (this.#E && this.#E.fill(0), this.#b = 0, this.#u = 0, this.#v.length = 0, this.#m = 0, this.#o = 0, this.#s && this.#y) { + let e = this.#y, s; + for (; s = e?.shift(); ) this.#n?.(...s); } } }; - Wt.LRUCache = rr; + Ut.LRUCache = wr; }); - var Oe = R((P) => { + var $e = x((j) => { "use strict"; - var nr = P && P.__importDefault || function(n) { + var br = j && j.__importDefault || function(n) { return n && n.__esModule ? n : { default: n }; }; - Object.defineProperty(P, "__esModule", { value: true }); - 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"), or2 = (n) => !!n && typeof n == "object" && (n instanceof qt || n instanceof ws.default || (0, P.isReadable)(n) || (0, P.isWritable)(n)); - P.isStream = or2; - 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 $ = /* @__PURE__ */ Symbol("EOF"), q = /* @__PURE__ */ Symbol("maybeEmitEnd"), K = /* @__PURE__ */ Symbol("emittedEnd"), Bt = /* @__PURE__ */ Symbol("emittingEnd"), lt2 = /* @__PURE__ */ Symbol("emittedError"), It = /* @__PURE__ */ Symbol("closed"), ps = /* @__PURE__ */ Symbol("read"), Gt = /* @__PURE__ */ Symbol("flush"), ms = /* @__PURE__ */ Symbol("flushChunk"), L = /* @__PURE__ */ Symbol("encoding"), rt = /* @__PURE__ */ Symbol("decoder"), x = /* @__PURE__ */ Symbol("flowing"), ct = /* @__PURE__ */ Symbol("paused"), nt = /* @__PURE__ */ Symbol("resume"), T = /* @__PURE__ */ Symbol("buffer"), M = /* @__PURE__ */ Symbol("pipes"), C = /* @__PURE__ */ Symbol("bufferLength"), we = /* @__PURE__ */ Symbol("bufferPush"), zt = /* @__PURE__ */ Symbol("bufferShift"), k = /* @__PURE__ */ Symbol("objectMode"), O = /* @__PURE__ */ Symbol("destroyed"), be = /* @__PURE__ */ Symbol("error"), ye = /* @__PURE__ */ Symbol("emitData"), gs = /* @__PURE__ */ Symbol("emitEnd"), Se = /* @__PURE__ */ Symbol("emitEnd2"), I = /* @__PURE__ */ Symbol("async"), ve = /* @__PURE__ */ Symbol("abort"), Ut = /* @__PURE__ */ Symbol("aborted"), ut = /* @__PURE__ */ Symbol("signal"), Z = /* @__PURE__ */ Symbol("dataListeners"), D = /* @__PURE__ */ Symbol("discarded"), ft = (n) => Promise.resolve().then(n), cr2 = (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 { + Object.defineProperty(j, "__esModule", { value: true }); + j.Minipass = j.isWritable = j.isReadable = j.isStream = void 0; + var Gs = typeof process == "object" && process ? process : { stdout: null, stderr: null }, Ue = require("node:events"), qs = br(require("node:stream")), yr = require("node:string_decoder"), Sr = (n) => !!n && typeof n == "object" && (n instanceof Yt || n instanceof qs.default || (0, j.isReadable)(n) || (0, j.isWritable)(n)); + j.isStream = Sr; + var vr = (n) => !!n && typeof n == "object" && n instanceof Ue.EventEmitter && typeof n.pipe == "function" && n.pipe !== qs.default.Writable.prototype.pipe; + j.isReadable = vr; + var _r2 = (n) => !!n && typeof n == "object" && n instanceof Ue.EventEmitter && typeof n.write == "function" && typeof n.end == "function"; + j.isWritable = _r2; + var H = /* @__PURE__ */ Symbol("EOF"), X = /* @__PURE__ */ Symbol("maybeEmitEnd"), J = /* @__PURE__ */ Symbol("emittedEnd"), $t = /* @__PURE__ */ Symbol("emittingEnd"), pt = /* @__PURE__ */ Symbol("emittedError"), qt = /* @__PURE__ */ Symbol("closed"), Is = /* @__PURE__ */ Symbol("read"), Ht = /* @__PURE__ */ Symbol("flush"), Us = /* @__PURE__ */ Symbol("flushChunk"), W = /* @__PURE__ */ Symbol("encoding"), ot = /* @__PURE__ */ Symbol("decoder"), A = /* @__PURE__ */ Symbol("flowing"), mt = /* @__PURE__ */ Symbol("paused"), at = /* @__PURE__ */ Symbol("resume"), k = /* @__PURE__ */ Symbol("buffer"), F = /* @__PURE__ */ Symbol("pipes"), M = /* @__PURE__ */ Symbol("bufferLength"), Le = /* @__PURE__ */ Symbol("bufferPush"), Xt = /* @__PURE__ */ Symbol("bufferShift"), P = /* @__PURE__ */ Symbol("objectMode"), C = /* @__PURE__ */ Symbol("destroyed"), We = /* @__PURE__ */ Symbol("error"), Be = /* @__PURE__ */ Symbol("emitData"), $s = /* @__PURE__ */ Symbol("emitEnd"), ze = /* @__PURE__ */ Symbol("emitEnd2"), G = /* @__PURE__ */ Symbol("async"), Ge = /* @__PURE__ */ Symbol("abort"), Kt = /* @__PURE__ */ Symbol("aborted"), gt = /* @__PURE__ */ Symbol("signal"), st = /* @__PURE__ */ Symbol("dataListeners"), D = /* @__PURE__ */ Symbol("discarded"), wt = (n) => Promise.resolve().then(n), Er = (n) => n(), Or = (n) => n === "end" || n === "finish" || n === "prefinish", Cr = (n) => n instanceof ArrayBuffer || !!n && typeof n == "object" && n.constructor && n.constructor.name === "ArrayBuffer" && n.byteLength >= 0, Ar = (n) => !Buffer.isBuffer(n) && ArrayBuffer.isView(n), Vt = 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); + this.src = t, this.dest = e, this.opts = s, this.ondrain = () => t[at](), this.dest.on("drain", this.ondrain); } unpipe() { this.dest.removeListener("drain", this.ondrain); @@ -104669,47 +136777,47 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur end() { this.unpipe(), this.opts.end && this.dest.end(); } - }, Ee = class extends $t { + }, Ie = class extends Vt { 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] = false; - [ct] = false; - [M] = []; - [T] = []; - [k]; - [L]; - [I]; - [rt]; - [$] = false; - [K] = false; - [Bt] = false; - [It] = false; - [lt2] = null; - [C] = 0; - [O] = false; - [ut]; - [Ut] = false; - [Z] = 0; + }, kr = (n) => !!n.objectMode, Mr = (n) => !n.objectMode && !!n.encoding && n.encoding !== "buffer", Yt = class extends Ue.EventEmitter { + [A] = false; + [mt] = false; + [F] = []; + [k] = []; + [P]; + [W]; + [G]; + [ot]; + [H] = false; + [J] = false; + [$t] = false; + [qt] = false; + [pt] = null; + [M] = 0; + [C] = false; + [gt]; + [Kt] = false; + [st] = 0; [D] = false; writable = true; readable = true; 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] = true, this[L] = null) : mr(e) ? (this[L] = e.encoding, this[k] = false) : (this[k] = false, this[L] = null), this[I] = !!e.async, this[rt] = this[L] ? new hr.StringDecoder(this[L]) : null, e && e.debugExposeBuffer === true && Object.defineProperty(this, "buffer", { get: () => this[T] }), e && e.debugExposePipes === true && Object.defineProperty(this, "pipes", { get: () => this[M] }); + kr(e) ? (this[P] = true, this[W] = null) : Mr(e) ? (this[W] = e.encoding, this[P] = false) : (this[P] = false, this[W] = null), this[G] = !!e.async, this[ot] = this[W] ? new yr.StringDecoder(this[W]) : null, e && e.debugExposeBuffer === true && Object.defineProperty(this, "buffer", { get: () => this[k] }), e && e.debugExposePipes === true && Object.defineProperty(this, "pipes", { get: () => this[F] }); let { signal: s } = e; - s && (this[ut] = s, s.aborted ? this[ve]() : s.addEventListener("abort", () => this[ve]())); + s && (this[gt] = s, s.aborted ? this[Ge]() : s.addEventListener("abort", () => this[Ge]())); } get bufferLength() { - return this[C]; + return this[M]; } get encoding() { - return this[L]; + return this[W]; } set encoding(t) { throw new Error("Encoding must be set at instantiation time"); @@ -104718,110 +136826,110 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur throw new Error("Encoding must be set at instantiation time"); } get objectMode() { - return this[k]; + return this[P]; } set objectMode(t) { throw new Error("objectMode must be set at instantiation time"); } get async() { - return this[I]; + return this[G]; } set async(t) { - this[I] = this[I] || !!t; + this[G] = this[G] || !!t; } - [ve]() { - this[Ut] = true, this.emit("abort", this[ut]?.reason), this.destroy(this[ut]?.reason); + [Ge]() { + this[Kt] = true, this.emit("abort", this[gt]?.reason), this.destroy(this[gt]?.reason); } get aborted() { - return this[Ut]; + return this[Kt]; } set aborted(t) { } write(t, e, s) { - if (this[Ut]) return false; - 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" })), true; + if (this[Kt]) return false; + if (this[H]) throw new Error("write after end"); + if (this[C]) return this.emit("error", Object.assign(new Error("Cannot call write after a stream was destroyed"), { code: "ERR_STREAM_DESTROYED" })), true; typeof e == "function" && (s = e, e = "utf8"), e || (e = "utf8"); - let i = this[I] ? ft : cr2; - 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); + let i = this[G] ? wt : Er; + if (!this[P] && !Buffer.isBuffer(t)) { + if (Ar(t)) t = Buffer.from(t.buffer, t.byteOffset, t.byteLength); + else if (Cr(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](true), 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](true), 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]); + return this[P] ? (this[A] && this[M] !== 0 && this[Ht](true), this[A] ? this.emit("data", t) : this[Le](t), this[M] !== 0 && this.emit("readable"), s && i(s), this[A]) : t.length ? (typeof t == "string" && !(e === this[W] && !this[ot]?.lastNeed) && (t = Buffer.from(t, e)), Buffer.isBuffer(t) && this[W] && (t = this[ot].write(t)), this[A] && this[M] !== 0 && this[Ht](true), this[A] ? this.emit("data", t) : this[Le](t), this[M] !== 0 && this.emit("readable"), s && i(s), this[A]) : (this[M] !== 0 && this.emit("readable"), s && i(s), this[A]); } read(t) { - if (this[O]) return null; - if (this[D] = false, 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](); + if (this[C]) return null; + if (this[D] = false, this[M] === 0 || t === 0 || t && t > this[M]) return this[X](), null; + this[P] && (t = null), this[k].length > 1 && !this[P] && (this[k] = [this[W] ? this[k].join("") : Buffer.concat(this[k], this[M])]); + let e = this[Is](t || null, this[k][0]); + return this[X](), e; + } + [Is](t, e) { + if (this[P]) this[Xt](); 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); + t === s.length || t === null ? this[Xt]() : typeof s == "string" ? (this[k][0] = s.slice(t), e = s.slice(0, t), this[M] -= t) : (this[k][0] = s.subarray(t), e = s.subarray(0, t), this[M] -= t); } - return this.emit("data", e), !this[T].length && !this[$] && this.emit("drain"), e; + return this.emit("data", e), !this[k].length && !this[H] && 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[$] = true, this.writable = false, (this[x] || !this[ct]) && this[q](), this; + 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[H] = true, this.writable = false, (this[A] || !this[mt]) && this[X](), this; } - [nt]() { - this[O] || (!this[Z] && !this[M].length && (this[D] = true), this[ct] = false, this[x] = true, this.emit("resume"), this[T].length ? this[Gt]() : this[$] ? this[q]() : this.emit("drain")); + [at]() { + this[C] || (!this[st] && !this[F].length && (this[D] = true), this[mt] = false, this[A] = true, this.emit("resume"), this[k].length ? this[Ht]() : this[H] ? this[X]() : this.emit("drain")); } resume() { - return this[nt](); + return this[at](); } pause() { - this[x] = false, this[ct] = true, this[D] = false; + this[A] = false, this[mt] = true, this[D] = false; } get destroyed() { - return this[O]; + return this[C]; } get flowing() { - return this[x]; + return this[A]; } get paused() { - return this[ct]; + return this[mt]; } - [we](t) { - this[k] ? this[C] += 1 : this[C] += t.length, this[T].push(t); + [Le](t) { + this[P] ? this[M] += 1 : this[M] += t.length, this[k].push(t); } - [zt]() { - return this[k] ? this[C] -= 1 : this[C] -= this[T][0].length, this[T].shift(); + [Xt]() { + return this[P] ? this[M] -= 1 : this[M] -= this[k][0].length, this[k].shift(); } - [Gt](t = false) { + [Ht](t = false) { do ; - while (this[ms](this[zt]()) && this[T].length); - !t && !this[T].length && !this[$] && this.emit("drain"); + while (this[Us](this[Xt]()) && this[k].length); + !t && !this[k].length && !this[H] && this.emit("drain"); } - [ms](t) { - return this.emit("data", t), this[x]; + [Us](t) { + return this.emit("data", t), this[A]; } pipe(t, e) { - if (this[O]) return t; + if (this[C]) return t; this[D] = false; - let s = this[K]; - return e = e || {}, t === ds.stdout || t === ds.stderr ? e.end = false : e.end = e.end !== false, 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; + let s = this[J]; + return e = e || {}, t === Gs.stdout || t === Gs.stderr ? e.end = false : e.end = e.end !== false, e.proxyErrors = !!e.proxyErrors, s ? e.end && t.end() : (this[F].push(e.proxyErrors ? new Ie(this, t, e) : new Vt(this, t, e)), this[G] ? wt(() => this[at]()) : this[at]()), t; } unpipe(t) { - let e = this[M].find((s) => s.dest === t); - e && (this[M].length === 1 ? (this[x] && this[Z] === 0 && (this[x] = false), this[M] = []) : this[M].splice(this[M].indexOf(e), 1), e.unpipe()); + let e = this[F].find((s) => s.dest === t); + e && (this[F].length === 1 ? (this[A] && this[st] === 0 && (this[A] = false), 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[D] = false, 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[lt2]) { + if (t === "data") this[D] = false, this[st]++, !this[F].length && !this[A] && this[at](); + else if (t === "readable" && this[M] !== 0) super.emit("readable"); + else if (Or(t) && this[J]) super.emit(t), this.removeAllListeners(t); + else if (t === "error" && this[pt]) { let i = e; - this[I] ? ft(() => i.call(this, this[lt2])) : i.call(this, this[lt2]); + this[G] ? wt(() => i.call(this, this[pt])) : i.call(this, this[pt]); } return s; } @@ -104830,77 +136938,77 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur } 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] = false)), s; + return t === "data" && (this[st] = this.listeners("data").length, this[st] === 0 && !this[D] && !this[F].length && (this[A] = false)), s; } removeAllListeners(t) { let e = super.removeAllListeners(t); - return (t === "data" || t === void 0) && (this[Z] = 0, !this[D] && !this[M].length && (this[x] = false)), e; + return (t === "data" || t === void 0) && (this[st] = 0, !this[D] && !this[F].length && (this[A] = false)), e; } get emittedEnd() { - return this[K]; + return this[J]; } - [q]() { - !this[Bt] && !this[K] && !this[O] && this[T].length === 0 && this[$] && (this[Bt] = true, this.emit("end"), this.emit("prefinish"), this.emit("finish"), this[It] && this.emit("close"), this[Bt] = false); + [X]() { + !this[$t] && !this[J] && !this[C] && this[k].length === 0 && this[H] && (this[$t] = true, this.emit("end"), this.emit("prefinish"), this.emit("finish"), this[qt] && this.emit("close"), this[$t] = false); } emit(t, ...e) { let s = e[0]; - if (t !== "error" && t !== "close" && t !== O && this[O]) return false; - if (t === "data") return !this[k] && !s ? false : this[I] ? (ft(() => this[ye](s)), true) : this[ye](s); - if (t === "end") return this[gs](); + if (t !== "error" && t !== "close" && t !== C && this[C]) return false; + if (t === "data") return !this[P] && !s ? false : this[G] ? (wt(() => this[Be](s)), true) : this[Be](s); + if (t === "end") return this[$s](); if (t === "close") { - if (this[It] = true, !this[K] && !this[O]) return false; + if (this[qt] = true, !this[J] && !this[C]) return false; let r = super.emit("close"); return this.removeAllListeners("close"), r; } else if (t === "error") { - this[lt2] = s, super.emit(be, s); - let r = !this[ut] || this.listeners("error").length ? super.emit("error", s) : false; - return this[q](), r; + this[pt] = s, super.emit(We, s); + let r = !this[gt] || this.listeners("error").length ? super.emit("error", s) : false; + return this[X](), r; } else if (t === "resume") { let r = super.emit("resume"); - return this[q](), r; + return this[X](), 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; + return this[X](), i; } - [ye](t) { - for (let s of this[M]) s.dest.write(t) === false && this.pause(); + [Be](t) { + for (let s of this[F]) s.dest.write(t) === false && this.pause(); let e = this[D] ? false : super.emit("data", t); - return this[q](), e; + return this[X](), e; } - [gs]() { - return this[K] ? false : (this[K] = true, this.readable = false, this[I] ? (ft(() => this[Se]()), true) : this[Se]()); + [$s]() { + return this[J] ? false : (this[J] = true, this.readable = false, this[G] ? (wt(() => this[ze]()), true) : this[ze]()); } - [Se]() { - if (this[rt]) { - let e = this[rt].end(); + [ze]() { + if (this[ot]) { + let e = this[ot].end(); if (e) { - for (let s of this[M]) s.dest.write(e); + for (let s of this[F]) s.dest.write(e); this[D] || super.emit("data", e); } } - for (let e of this[M]) e.end(); + 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); + this[P] || (t.dataLength = 0); let e = this.promise(); return this.on("data", (s) => { - t.push(s), this[k] || (t.dataLength += s.length); + t.push(s), this[P] || (t.dataLength += s.length); }), await e, t; } async concat() { - if (this[k]) throw new Error("cannot concat in objectMode"); + if (this[P]) throw new Error("cannot concat in objectMode"); let t = await this.collect(); - return this[L] ? t.join("") : Buffer.concat(t, t.dataLength); + return this[W] ? 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()); + this.on(C, () => e(new Error("stream destroyed"))), this.on("error", (s) => e(s)), this.on("end", () => t()); }); } [Symbol.asyncIterator]() { @@ -104910,16 +137018,16 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur if (t) return e(); let i = this.read(); if (i !== null) return Promise.resolve({ done: false, 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[$] }); + if (this[H]) return e(); + let r, h, a = (u) => { + this.off("data", o), this.off("end", l), this.off(C, c), e(), h(u); + }, o = (u) => { + this.off("error", a), this.off("end", l), this.off(C, c), this.pause(), r({ value: u, done: !!this[H] }); }, l = () => { - this.off("error", o), this.off("data", a), this.off(O, f), e(), r({ done: true, 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); + this.off("error", a), this.off("data", o), this.off(C, c), e(), r({ done: true, value: void 0 }); + }, c = () => a(new Error("stream destroyed")); + return new Promise((u, p) => { + h = p, r = u, this.once(C, c), this.once("error", a), this.once("end", l), this.once("data", o); }); }, throw: e, return: e, [Symbol.asyncIterator]() { return this; @@ -104928,31 +137036,31 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur } [Symbol.iterator]() { this[D] = false; - let t = false, e = () => (this.pause(), this.off(be, e), this.off(O, e), this.off("end", e), t = true, { done: true, value: void 0 }), s = () => { + let t = false, e = () => (this.pause(), this.off(We, e), this.off(C, e), this.off("end", e), t = true, { done: true, value: void 0 }), s = () => { if (t) return e(); let i = this.read(); return i === null ? e() : { done: false, 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.once("end", e), this.once(We, e), this.once(C, 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] = true, this[D] = true, this[T].length = 0, this[C] = 0; + if (this[C]) return t ? this.emit("error", t) : this.emit(C), this; + this[C] = true, this[D] = true, this[k].length = 0, this[M] = 0; let e = this; - return typeof e.close == "function" && !this[It] && e.close(), t ? this.emit("error", t) : this.emit(O), this; + return typeof e.close == "function" && !this[qt] && e.close(), t ? this.emit("error", t) : this.emit(C), this; } static get isStream() { - return P.isStream; + return j.isStream; } }; - P.Minipass = qt; + j.Minipass = Yt; }); - var Ms = R((_2) => { + var ni = x((E) => { "use strict"; - var gr = _2 && _2.__createBinding || (Object.create ? (function(n, t, e, s) { + var xr = E && E.__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: true, get: function() { @@ -104960,41 +137068,50 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur } }), Object.defineProperty(n, s, i); }) : (function(n, t, e, s) { s === void 0 && (s = e), n[s] = t[e]; - })), wr = _2 && _2.__setModuleDefault || (Object.create ? (function(n, t) { + })), Rr = E && E.__setModuleDefault || (Object.create ? (function(n, t) { Object.defineProperty(n, "default", { enumerable: true, value: t }); }) : function(n, t) { n.default = t; - }), br = _2 && _2.__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(_2, "__esModule", { value: true }); - _2.PathScurry = _2.Path = _2.PathScurryDarwin = _2.PathScurryPosix = _2.PathScurryWin32 = _2.PathScurryBase = _2.PathPosix = _2.PathWin32 = _2.PathBase = _2.ChildrenCache = _2.ResolveCache = void 0; - var Qt = fs32(), 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); + }), Pr = E && E.__importStar || /* @__PURE__ */ (function() { + var n = function(t) { + return n = Object.getOwnPropertyNames || function(e) { + var s = []; + for (var i in e) Object.prototype.hasOwnProperty.call(e, i) && (s[s.length] = i); + return s; + }, n(t); + }; + return function(t) { + if (t && t.__esModule) return t; + var e = {}; + if (t != null) for (var s = n(t), i = 0; i < s.length; i++) s[i] !== "default" && xr(e, t, s[i]); + return Rr(e, t), e; + }; + })(); + Object.defineProperty(E, "__esModule", { value: true }); + E.PathScurry = E.Path = E.PathScurryDarwin = E.PathScurryPosix = E.PathScurryWin32 = E.PathScurryBase = E.PathPosix = E.PathWin32 = E.PathBase = E.ChildrenCache = E.ResolveCache = void 0; + var re = zs(), ee = require("node:path"), Tr = require("node:url"), yt = require("fs"), Fr = Pr(require("node:fs")), jr = yt.realpathSync.native, Zt = require("node:fs/promises"), Hs = $e(), St = { lstatSync: yt.lstatSync, readdir: yt.readdir, readdirSync: yt.readdirSync, readlinkSync: yt.readlinkSync, realpathSync: jr, promises: { lstat: Zt.lstat, readdir: Zt.readdir, readlink: Zt.readlink, realpath: Zt.realpath } }, Js = (n) => !n || n === St || n === Fr ? St : { ...St, ...n, promises: { ...St.promises, ...n.promises } }, Dr = /^\\\\\?\\([a-z]:)\\?$/i, Nr = /^\\\\\?\\UNC\\([^\\]+\\[^\\]+)\\?$/i, Lr = /^\\\\[^\\?]+\\[^\\]+$/, Xs = (n) => n.replace(/\//g, "\\").replace(Dr, "$1\\").replace(Nr, "\\\\$1\\").replace(Lr, "$&\\"), Wr = /^[\\/]{2}\?[\\/]unc[\\/][^\\/]+[\\/][^\\/]+(?:[\\/]|$)/i, Br = /^[\\/]{2}\?[\\/](?=[a-z]:)/i, zr = /^[\\/]{2}\?[\\/]unc(?=[\\/][^\\/]+[\\/][^\\/])/i, Gr = /[\\/]/, L = 0, Qs = 1, ti = 2, I = 4, ei = 6, si = 8, it = 10, ii = 12, N = 15, bt = ~N, qe = 16, Ks = 32, vt = 64, B = 128, Jt = 256, te = 512, Vs = vt | B | te, Ir = 1023, He = (n) => n.isFile() ? si : n.isDirectory() ? I : n.isSymbolicLink() ? it : n.isCharacterDevice() ? ti : n.isBlockDevice() ? ei : n.isSocket() ? ii : n.isFIFO() ? Qs : L, Ys = new re.LRUCache({ max: 2 ** 12 }), _t2 = (n) => { + let t = Ys.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); + return Ys.set(n, e), e; + }, Zs = new re.LRUCache({ max: 2 ** 12 }), Qt = (n) => { + let t = Zs.get(n); if (t) return t; - let e = wt(n.toLowerCase()); - return Es.set(n, e), e; - }, bt = class extends Qt.LRUCache { + let e = _t2(n.toLowerCase()); + return Zs.set(n, e), e; + }, Et = class extends re.LRUCache { constructor() { super({ max: 256 }); } }; - _2.ResolveCache = bt; - var Jt = class extends Qt.LRUCache { + E.ResolveCache = Et; + var se = class extends re.LRUCache { constructor(t = 16 * 1024) { super({ maxSize: t, sizeCalculation: (e) => e.length + 1 }); } }; - _2.ChildrenCache = Jt; - var ks = /* @__PURE__ */ Symbol("PathScurry setAsCwd"), A = class { + E.ChildrenCache = se; + var ri = /* @__PURE__ */ Symbol("PathScurry setAsCwd"), R = class { name; root; roots; @@ -105002,141 +137119,144 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur nocase; isCWD = false; #t; - #s; + #i; get dev() { - return this.#s; + return this.#i; } - #n; + #e; get mode() { - return this.#n; + return this.#e; } - #r; + #h; get nlink() { - return this.#r; + return this.#h; } - #h; + #n; get uid() { - return this.#h; + return this.#n; } - #S; + #d; get gid() { - return this.#S; + return this.#d; } - #w; + #c; get rdev() { - return this.#w; + return this.#c; } - #c; + #p; get blksize() { - return this.#c; + return this.#p; } #o; get ino() { return this.#o; } - #f; + #m; get size() { - return this.#f; + return this.#m; } - #u; + #a; get blocks() { - return this.#u; + return this.#a; } - #a; + #l; get atimeMs() { - return this.#a; + return this.#l; } - #i; + #r; get mtimeMs() { - return this.#i; + return this.#r; } - #d; + #w; get ctimeMs() { - return this.#d; + return this.#w; } - #v; + #_; get birthtimeMs() { - return this.#v; + return this.#_; } - #y; + #b; get atime() { - return this.#y; + return this.#b; } - #p; + #u; get mtime() { - return this.#p; + return this.#u; } - #R; + #v; get ctime() { - return this.#R; + return this.#v; } - #m; + #y; get birthtime() { - return this.#m; + return this.#y; } + #E; #O; - #x; #g; - #b; - #E; - #T; - #e; - #F; - #P; + #S; #C; + #M; + #s; + #P; + #T; + #k; 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); + constructor(t, e = L, s, i, r, h, a) { + this.name = t, this.#E = r ? Qt(t) : _t2(t), this.#s = e & Ir, this.nocase = r, this.roots = i, this.root = s || this, this.#P = h, this.#g = a.fullpath, this.#C = a.relative, this.#M = a.relativePosix, this.parent = a.parent, this.parent ? this.#t = this.parent.#t : this.#t = Js(a.fs); + } + get fs() { + return this.#t; } depth() { - return this.#x !== void 0 ? this.#x : this.parent ? this.#x = this.parent.depth() + 1 : this.#x = 0; + return this.#O !== void 0 ? this.#O : this.parent ? this.#O = this.parent.depth() + 1 : this.#O = 0; } childrenCache() { - return this.#F; + return this.#P; } 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); + return e ? this.getRoot(e).#F(i) : this.#F(i); } - #D(t) { + #F(t) { let e = this; for (let s of t) e = e.child(s); return e; } children() { - let t = this.#F.get(this); + let t = this.#P.get(this); if (t) return t; let e = Object.assign([], { provisional: 0 }); - return this.#F.set(this, e), this.#e &= ~xe, e; + return this.#P.set(this, e), this.#s &= ~qe, 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; + let s = this.children(), i = this.nocase ? Qt(t) : _t2(t); + for (let o of s) if (o.#E === i) return o; + let r = this.parent ? this.sep : "", h = this.#g ? this.#g + r + t : void 0, a = this.newChild(t, L, { ...e, parent: this, fullpath: h }); + return this.canReaddir() || (a.#s |= B), s.push(a), a; } relative() { if (this.isCWD) return ""; - if (this.#E !== void 0) return this.#E; + if (this.#C !== void 0) return this.#C; let t = this.name, e = this.parent; - if (!e) return this.#E = this.name; + if (!e) return this.#C = 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; + if (this.#M !== void 0) return this.#M; let t = this.name, e = this.parent; - if (!e) return this.#T = this.fullpathPosix(); + if (!e) return this.#M = this.fullpathPosix(); let s = e.relativePosix(); return s + (!s || !e.parent ? "" : "/") + t; } @@ -105148,17 +137268,17 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur return this.#g = i; } fullpathPosix() { - if (this.#b !== void 0) return this.#b; - if (this.sep === "/") return this.#b = this.fullpath(); + if (this.#S !== void 0) return this.#S; + if (this.sep === "/") return this.#S = this.fullpath(); if (!this.parent) { let i = this.fullpath().replace(/\\/g, "/"); - return /^[a-z]:\//i.test(i) ? this.#b = `//?/${i}` : this.#b = i; + return /^[a-z]:\//i.test(i) ? this.#S = `//?/${i}` : this.#S = i; } let t = this.parent, e = t.fullpathPosix(), s = e + (!e || !t.parent ? "" : "/") + this.name; - return this.#b = s; + return this.#S = s; } isUnknown() { - return (this.#e & j) === N; + return (this.#s & N) === L; } isType(t) { return this[`is${t}`](); @@ -105167,152 +137287,152 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur 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; + return (this.#s & N) === si; } isDirectory() { - return (this.#e & j) === G; + return (this.#s & N) === I; } isCharacterDevice() { - return (this.#e & j) === Ts; + return (this.#s & N) === ti; } isBlockDevice() { - return (this.#e & j) === Cs; + return (this.#s & N) === ei; } isFIFO() { - return (this.#e & j) === xs; + return (this.#s & N) === Qs; } isSocket() { - return (this.#e & j) === As; + return (this.#s & N) === ii; } isSymbolicLink() { - return (this.#e & Q) === Q; + return (this.#s & it) === it; } lstatCached() { - return this.#e & ys ? this : void 0; + return this.#s & Ks ? this : void 0; } readlinkCached() { - return this.#P; + return this.#T; } realpathCached() { - return this.#C; + return this.#k; } readdirCached() { let t = this.children(); return t.slice(0, t.provisional); } canReadlink() { - if (this.#P) return true; + if (this.#T) return true; if (!this.parent) return false; - let t = this.#e & j; - return !(t !== N && t !== Q || this.#e & Vt || this.#e & W); + let t = this.#s & N; + return !(t !== L && t !== it || this.#s & Jt || this.#s & B); } calledReaddir() { - return !!(this.#e & xe); + return !!(this.#s & qe); } isENOENT() { - return !!(this.#e & W); + return !!(this.#s & B); } isNamed(t) { - return this.nocase ? this.#O === Kt(t) : this.#O === wt(t); + return this.nocase ? this.#E === Qt(t) : this.#E === _t2(t); } async readlink() { - let t = this.#P; + let t = this.#T; 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; + if (s) return this.#T = s; } catch (e) { - this.#M(e.code); + this.#R(e.code); return; } } readlinkSync() { - let t = this.#P; + let t = this.#T; 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; + if (s) return this.#T = s; } catch (e) { - this.#M(e.code); + this.#R(e.code); return; } } - #W(t) { - this.#e |= xe; + #B(t) { + this.#s |= qe; for (let e = t.provisional; e < t.length; e++) { let s = t[e]; - s && s.#_(); + s && s.#A(); } } - #_() { - this.#e & W || (this.#e = (this.#e | W) & dt, this.#$()); + #A() { + this.#s & B || (this.#s = (this.#s | B) & bt, this.#$()); } #$() { let t = this.children(); t.provisional = 0; - for (let e of t) e.#_(); + for (let e of t) e.#A(); } - #L() { - this.#e |= Xt, this.#j(); + #D() { + this.#s |= te, this.#j(); } #j() { - if (this.#e & gt) return; - let t = this.#e; - (t & j) === G && (t &= dt), this.#e = t | gt, this.#$(); + if (this.#s & vt) return; + let t = this.#s; + (t & N) === I && (t &= bt), this.#s = t | vt, this.#$(); } - #B(t = "") { - t === "ENOTDIR" || t === "EPERM" ? this.#j() : t === "ENOENT" ? this.#_() : this.children().provisional = 0; + #z(t = "") { + t === "ENOTDIR" || t === "EPERM" ? this.#j() : t === "ENOENT" ? this.#A() : this.children().provisional = 0; } - #k(t = "") { - t === "ENOTDIR" ? this.parent.#j() : t === "ENOENT" && this.#_(); + #x(t = "") { + t === "ENOTDIR" ? this.parent.#j() : t === "ENOENT" && this.#A(); } - #M(t = "") { - let e = this.#e; - e |= Vt, t === "ENOENT" && (e |= W), (t === "EINVAL" || t === "UNKNOWN") && (e &= dt), this.#e = e, t === "ENOTDIR" && this.parent && this.parent.#j(); - } - #I(t, e) { - return this.#z(t, e) || this.#G(t, e); + #R(t = "") { + let e = this.#s; + e |= Jt, t === "ENOENT" && (e |= B), (t === "EINVAL" || t === "UNKNOWN") && (e &= bt), this.#s = e, t === "ENOTDIR" && this.parent && this.parent.#j(); } #G(t, e) { - let s = Te(t), i = this.newChild(t.name, s, { parent: this }), r = i.#e & j; - return r !== G && r !== Q && r !== N && (i.#e |= gt), e.unshift(i), e.provisional++, i; + return this.#U(t, e) || this.#N(t, e); + } + #N(t, e) { + let s = He(t), i = this.newChild(t.name, s, { parent: this }), r = i.#s & N; + return r !== I && r !== it && r !== L && (i.#s |= vt), e.unshift(i), e.provisional++, i; } - #z(t, e) { + #U(t, e) { for (let s = e.provisional; s < e.length; s++) { let i = e[s]; - if ((this.nocase ? Kt(t.name) : wt(t.name)) === i.#O) return this.#l(t, i, s, e); + if ((this.nocase ? Qt(t.name) : _t2(t.name)) === i.#E) return this.#V(t, i, s, e); } } - #l(t, e, s, i) { + #V(t, e, s, i) { let r = e.name; - return e.#e = e.#e & dt | Te(t), r !== t.name && (e.name = t.name), s !== i.provisional && (s === i.length - 1 ? i.pop() : i.splice(s, 1), i.unshift(e)), i.provisional++, e; + return e.#s = e.#s & bt | He(t), r !== t.name && (e.name = t.name), s !== i.provisional && (s === i.length - 1 ? i.pop() : i.splice(s, 1), i.unshift(e)), i.provisional++, e; } async lstat() { - if ((this.#e & W) === 0) try { - return this.#U(await this.#t.promises.lstat(this.fullpath())), this; + if ((this.#s & B) === 0) try { + return this.#q(await this.#t.promises.lstat(this.fullpath())), this; } catch (t) { - this.#k(t.code); + this.#x(t.code); } } lstatSync() { - if ((this.#e & W) === 0) try { - return this.#U(this.#t.lstatSync(this.fullpath())), this; + if ((this.#s & B) === 0) try { + return this.#q(this.#t.lstatSync(this.fullpath())), this; } catch (t) { - this.#k(t.code); + this.#x(t.code); } } - #U(t) { - let { atime: e, atimeMs: s, birthtime: i, birthtimeMs: r, blksize: h, blocks: o, ctime: a, ctimeMs: l, dev: f, gid: c, ino: d, mode: u, mtime: m, mtimeMs: p, nlink: b, rdev: w, size: v, uid: E } = t; - this.#y = e, this.#a = s, this.#m = i, this.#v = r, this.#c = h, this.#u = o, this.#R = a, this.#d = l, this.#s = f, this.#S = c, this.#o = d, this.#n = u, this.#p = m, this.#i = p, this.#r = b, this.#w = w, this.#f = v, this.#h = E; - let y = Te(t); - this.#e = this.#e & dt | y | ys, y !== N && y !== G && y !== Q && (this.#e |= gt); - } - #N = []; - #A = false; #q(t) { - this.#A = false; - let e = this.#N.slice(); - this.#N.length = 0, e.forEach((s) => s(null, t)); + let { atime: e, atimeMs: s, birthtime: i, birthtimeMs: r, blksize: h, blocks: a, ctime: o, ctimeMs: l, dev: c, gid: u, ino: p, mode: d, mtime: g, mtimeMs: f, nlink: b, rdev: m, size: y, uid: _2 } = t; + this.#b = e, this.#l = s, this.#y = i, this.#_ = r, this.#p = h, this.#a = a, this.#v = o, this.#w = l, this.#i = c, this.#d = u, this.#o = p, this.#e = d, this.#u = g, this.#r = f, this.#h = b, this.#c = m, this.#m = y, this.#n = _2; + let v = He(t); + this.#s = this.#s & bt | v | Ks, v !== L && v !== I && v !== it && (this.#s |= vt); + } + #L = []; + #f = false; + #H(t) { + this.#f = false; + let e = this.#L.slice(); + this.#L.length = 0, e.forEach((s) => s(null, t)); } readdirCB(t, e = false) { if (!this.canReaddir()) { @@ -105325,36 +137445,36 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur e ? t(null, r) : queueMicrotask(() => t(null, r)); return; } - if (this.#N.push(t), this.#A) return; - this.#A = true; + if (this.#L.push(t), this.#f) return; + this.#f = true; let i = this.fullpath(); this.#t.readdir(i, { withFileTypes: true }, (r, h) => { - if (r) this.#B(r.code), s.provisional = 0; + if (r) this.#z(r.code), s.provisional = 0; else { - for (let o of h) this.#I(o, s); - this.#W(s); + for (let a of h) this.#G(a, s); + this.#B(s); } - this.#q(s.slice(0, s.provisional)); + this.#H(s.slice(0, s.provisional)); }); } - #H; + #I; 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; + if (this.#I) await this.#I; else { let s = () => { }; - this.#H = new Promise((i) => s = i); + this.#I = new Promise((i) => s = i); try { - for (let i of await this.#t.promises.readdir(e, { withFileTypes: true })) this.#I(i, t); - this.#W(t); + for (let i of await this.#t.promises.readdir(e, { withFileTypes: true })) this.#G(i, t); + this.#B(t); } catch (i) { - this.#B(i.code), t.provisional = 0; + this.#z(i.code), t.provisional = 0; } - this.#H = void 0, s(); + this.#I = void 0, s(); } return t.slice(0, t.provisional); } @@ -105364,75 +137484,75 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur if (this.calledReaddir()) return t.slice(0, t.provisional); let e = this.fullpath(); try { - for (let s of this.#t.readdirSync(e, { withFileTypes: true })) this.#I(s, t); - this.#W(t); + for (let s of this.#t.readdirSync(e, { withFileTypes: true })) this.#G(s, t); + this.#B(t); } catch (s) { - this.#B(s.code), t.provisional = 0; + this.#z(s.code), t.provisional = 0; } return t.slice(0, t.provisional); } canReaddir() { - if (this.#e & Ss) return false; - let t = j & this.#e; - return t === N || t === G || t === Q; + if (this.#s & Vs) return false; + let t = N & this.#s; + return t === L || t === I || t === it; } shouldWalk(t, e) { - return (this.#e & G) === G && !(this.#e & Ss) && !t.has(this) && (!e || e(this)); + return (this.#s & I) === I && !(this.#s & Vs) && !t.has(this) && (!e || e(this)); } async realpath() { - if (this.#C) return this.#C; - if (!((Xt | Vt | W) & this.#e)) try { + if (this.#k) return this.#k; + if (!((te | Jt | B) & this.#s)) try { let t = await this.#t.promises.realpath(this.fullpath()); - return this.#C = this.resolve(t); + return this.#k = this.resolve(t); } catch { - this.#L(); + this.#D(); } } realpathSync() { - if (this.#C) return this.#C; - if (!((Xt | Vt | W) & this.#e)) try { + if (this.#k) return this.#k; + if (!((te | Jt | B) & this.#s)) try { let t = this.#t.realpathSync(this.fullpath()); - return this.#C = this.resolve(t); + return this.#k = this.resolve(t); } catch { - this.#L(); + this.#D(); } } - [ks](t) { + [ri](t) { if (t === this) return; t.isCWD = false, this.isCWD = true; let e = /* @__PURE__ */ 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; + for (; i && i.parent; ) e.add(i), i.#C = s.join(this.sep), i.#M = s.join("/"), i = i.parent, s.push(".."); + for (i = t; i && i.parent && !e.has(i); ) i.#C = void 0, i.#M = void 0, i = i.parent; } }; - _2.PathBase = A; - var yt = class n extends A { + E.PathBase = R; + var Ot = class n extends R { sep = "\\"; - splitSep = _r; - constructor(t, e = N, s, i, r, h, o) { - super(t, e, s, i, r, h, o); + splitSep = Gr; + constructor(t, e = L, s, i, r, h, a) { + super(t, e, s, i, r, h, a); } - newChild(t, e = N, s = {}) { + newChild(t, e = L, s = {}) { return new n(t, e, this.root, this.roots, this.nocase, this.childrenCache(), s); } getRootString(t) { - return Yt.win32.parse(t).root; + return Wr.exec(t)?.[0] ?? ee.win32.parse(t).root; } getRoot(t) { - if (t = Er(t.toUpperCase()), t === this.root.name) return this.root; + if (t = Xs(t.toUpperCase()), t === this.root.name || /^[\\/]$/.test(t)) 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; + return this.roots[t] = new kt(t, { nocase: this.nocase, fs: this.fs }).root; } sameRoot(t, e = this.root.name) { - return t = t.toUpperCase().replace(/\//g, "\\").replace(Os, "$1\\"), t === e; + return Xs(t.toUpperCase()) === e; } }; - _2.PathWin32 = yt; - var St = class n extends A { + E.PathWin32 = Ot; + var Ct = class n extends R { splitSep = "/"; sep = "/"; - constructor(t, e = N, s, i, r, h, o) { - super(t, e, s, i, r, h, o); + constructor(t, e = L, s, i, r, h, a) { + super(t, e, s, i, r, h, a); } getRootString(t) { return t.startsWith("/") ? "/" : ""; @@ -105440,32 +137560,32 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur getRoot(t) { return this.root; } - newChild(t, e = N, s = {}) { + newChild(t, e = L, s = {}) { return new n(t, e, this.root, this.roots, this.nocase, this.childrenCache(), s); } }; - _2.PathPosix = St; - var vt = class { + E.PathPosix = Ct; + var At = class { root; rootPath; roots; cwd; #t; - #s; - #n; + #i; + #e; 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 = /* @__PURE__ */ 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 = false; - 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 = true; + #h; + constructor(t = process.cwd(), e, s, { nocase: i, childrenCacheSize: r = 16 * 1024, fs: h = St } = {}) { + this.#h = Js(h), (t instanceof URL || t.startsWith("file://")) && (t = (0, Tr.fileURLToPath)(t)); + let a = e.resolve(t); + this.roots = /* @__PURE__ */ Object.create(null), this.rootPath = this.parseRootPath(a), this.#t = new Et(), this.#i = new Et(), this.#e = new se(r); + let o = a.substring(this.rootPath.length).split(s); + if (o.length === 1 && !o[0] && o.pop(), i === void 0) throw new TypeError("must provide nocase setting to PathScurryBase ctor"); + this.nocase = i, this.root = this.newRoot(this.#h), this.roots[this.rootPath] = this.root; + let l = this.root, c = o.length - 1, u = e.sep, p = this.rootPath, d = false; + for (let g of o) { + let f = c--; + l = l.child(g, { relative: new Array(f).fill("..").join(u), relativePosix: new Array(f).fill("..").join("/"), fullpath: p += (d ? "" : u) + g }), d = true; } this.cwd = l; } @@ -105473,7 +137593,7 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur return typeof t == "string" && (t = this.cwd.resolve(t)), t.depth(); } childrenCache() { - return this.#n; + return this.#e; } resolve(...t) { let e = ""; @@ -105492,10 +137612,10 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur let h = t[r]; if (!(!h || h === ".") && (e = e ? `${h}/${e}` : h, this.isAbsolute(h))) break; } - let s = this.#s.get(e); + let s = this.#i.get(e); if (s !== void 0) return s; let i = this.cwd.resolve(e).fullpathPosix(); - return this.#s.set(e, i), i; + return this.#i.set(e, i), i; } relative(t = this.cwd) { return typeof t == "string" && (t = this.cwd.resolve(t)), t.relative(); @@ -105510,7 +137630,7 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur return typeof t == "string" && (t = this.cwd.resolve(t)), (t.parent || t).fullpath(); } async readdir(t = this.cwd, e = { withFileTypes: true }) { - typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof A || (e = t, t = this.cwd); + 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(); @@ -105518,7 +137638,7 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur } else return []; } readdirSync(t = this.cwd, e = { withFileTypes: true }) { - typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof A || (e = t, t = this.cwd); + typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd); let { withFileTypes: s = true } = e; return t.canReaddir() ? s ? t.readdirSync() : t.readdirSync().map((i) => i.name) : []; } @@ -105529,275 +137649,279 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur return typeof t == "string" && (t = this.cwd.resolve(t)), t.lstatSync(); } async readlink(t = this.cwd, { withFileTypes: e } = { withFileTypes: false }) { - typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof A || (e = t.withFileTypes, t = this.cwd); + 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: false }) { - typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof A || (e = t.withFileTypes, t = this.cwd); + 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: false }) { - typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof A || (e = t.withFileTypes, t = this.cwd); + 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: false }) { - typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof A || (e = t.withFileTypes, t = this.cwd); + 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 A || (e = t, t = this.cwd); - let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: h } = e, o = []; - (!r || r(t)) && o.push(s ? t : t.fullpath()); - let a = /* @__PURE__ */ 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(); + typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd); + let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: h } = e, a = []; + (!r || r(t)) && a.push(s ? t : t.fullpath()); + let o = /* @__PURE__ */ new Set(), l = (u, p) => { + o.add(u), u.readdirCB((d, g) => { + if (d) return p(d); + let f = g.length; + if (!f) return p(); let b = () => { - --p === 0 && d(); + --f === 0 && p(); }; - 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(); + for (let m of g) (!r || r(m)) && a.push(s ? m : m.fullpath()), i && m.isSymbolicLink() ? m.realpath().then((y) => y?.isUnknown() ? y.lstat() : y).then((y) => y?.shouldWalk(o, h) ? l(y, b) : b()) : m.shouldWalk(o, h) ? l(m, b) : b(); }, true); - }, f = t; - return new Promise((c, d) => { - l(f, (u) => { - if (u) return d(u); - c(o); + }, c = t; + return new Promise((u, p) => { + l(c, (d) => { + if (d) return p(d); + u(a); }); }); } walkSync(t = this.cwd, e = {}) { - typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof A || (e = t, t = this.cwd); - let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: h } = e, o = []; - (!r || r(t)) && o.push(s ? t : t.fullpath()); - let a = /* @__PURE__ */ 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(); + typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd); + let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: h } = e, a = []; + (!r || r(t)) && a.push(s ? t : t.fullpath()); + let o = /* @__PURE__ */ new Set([t]); + for (let l of o) { + let c = l.readdirSync(); + for (let u of c) { + (!r || r(u)) && a.push(s ? u : u.fullpath()); + let p = u; + if (u.isSymbolicLink()) { + if (!(i && (p = u.realpathSync()))) continue; + p.isUnknown() && p.lstatSync(); } - d.shouldWalk(a, h) && a.add(d); + p.shouldWalk(o, h) && o.add(p); } } - return o; + return a; } [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](); + 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 A || (e = t, t = this.cwd); + typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd); let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: h } = e; (!r || r(t)) && (yield s ? t : t.fullpath()); - let o = /* @__PURE__ */ 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(); + let a = /* @__PURE__ */ new Set([t]); + for (let o of a) { + let l = o.readdirSync(); + for (let c of l) { + (!r || r(c)) && (yield s ? c : c.fullpath()); + let u = c; + if (c.isSymbolicLink()) { + if (!(i && (u = c.realpathSync()))) continue; + u.isUnknown() && u.lstatSync(); } - c.shouldWalk(o, h) && o.add(c); + u.shouldWalk(a, h) && a.add(u); } } } stream(t = this.cwd, e = {}) { - typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof A || (e = t, t = this.cwd); - let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: h } = e, o = new bs.Minipass({ objectMode: true }); - (!r || r(t)) && o.write(s ? t : t.fullpath()); - let a = /* @__PURE__ */ new Set(), l = [t], f = 0, c = () => { - let d = false; - for (; !d; ) { - let u = l.shift(); - if (!u) { - f === 0 && o.end(); + typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd); + let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: h } = e, a = new Hs.Minipass({ objectMode: true }); + (!r || r(t)) && a.write(s ? t : t.fullpath()); + let o = /* @__PURE__ */ new Set(), l = [t], c = 0, u = () => { + let p = false; + for (; !p; ) { + let d = l.shift(); + if (!d) { + c === 0 && a.end(); return; } - f++, a.add(u); - let m = (b, w, v = false) => { - 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, true)); + c++, o.add(d); + let g = (b, m, y = false) => { + if (b) return a.emit("error", b); + if (i && !y) { + let _2 = []; + for (let v of m) v.isSymbolicLink() && _2.push(v.realpath().then((S) => S?.isUnknown() ? S.lstat() : S)); + if (_2.length) { + Promise.all(_2).then(() => g(null, m, true)); return; } } - for (let E of w) E && (!r || r(E)) && (o.write(s ? E : E.fullpath()) || (d = true)); - f--; - for (let E of w) { - let y = E.realpathCached() || E; - y.shouldWalk(a, h) && l.push(y); + for (let _2 of m) _2 && (!r || r(_2)) && (a.write(s ? _2 : _2.fullpath()) || (p = true)); + c--; + for (let _2 of m) { + let v = _2.realpathCached() || _2; + v.shouldWalk(o, h) && l.push(v); } - d && !o.flowing ? o.once("drain", c) : p || c(); - }, p = true; - u.readdirCB(m, true), p = false; + p && !a.flowing ? a.once("drain", u) : f || u(); + }, f = true; + d.readdirCB(g, true), f = false; } }; - return c(), o; + return u(), a; } streamSync(t = this.cwd, e = {}) { - typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof A || (e = t, t = this.cwd); - let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: h } = e, o = new bs.Minipass({ objectMode: true }), a = /* @__PURE__ */ new Set(); - (!r || r(t)) && o.write(s ? t : t.fullpath()); - let l = [t], f = 0, c = () => { - let d = false; - for (; !d; ) { - let u = l.shift(); - if (!u) { - f === 0 && o.end(); + typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd); + let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: h } = e, a = new Hs.Minipass({ objectMode: true }), o = /* @__PURE__ */ new Set(); + (!r || r(t)) && a.write(s ? t : t.fullpath()); + let l = [t], c = 0, u = () => { + let p = false; + for (; !p; ) { + let d = l.shift(); + if (!d) { + c === 0 && a.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 = true)); - f--; - for (let p of m) { - let b = p; - if (p.isSymbolicLink()) { - if (!(i && (b = p.realpathSync()))) continue; + c++, o.add(d); + let g = d.readdirSync(); + for (let f of g) (!r || r(f)) && (a.write(s ? f : f.fullpath()) || (p = true)); + c--; + for (let f of g) { + let b = f; + if (f.isSymbolicLink()) { + if (!(i && (b = f.realpathSync()))) continue; b.isUnknown() && b.lstatSync(); } - b.shouldWalk(a, h) && l.push(b); + b.shouldWalk(o, h) && l.push(b); } } - d && !o.flowing && o.once("drain", c); + p && !a.flowing && a.once("drain", u); }; - return c(), o; + return u(), a; } chdir(t = this.cwd) { let e = this.cwd; - this.cwd = typeof t == "string" ? this.cwd.resolve(t) : t, this.cwd[ks](e); + this.cwd = typeof t == "string" ? this.cwd.resolve(t) : t, this.cwd[ri](e); } }; - _2.PathScurryBase = vt; - var Et = class extends vt { + E.PathScurryBase = At; + var kt = class extends At { sep = "\\"; constructor(t = process.cwd(), e = {}) { let { nocase: s = true } = e; - super(t, Yt.win32, "\\", { ...e, nocase: s }), this.nocase = s; + typeof t == "string" && !t.startsWith("file://") && (t = t.replace(Br, "").replace(zr, "\\")), super(t, ee.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(); + return ee.win32.parse(t).root.toUpperCase(); } newRoot(t) { - return new yt(this.rootPath, G, void 0, this.roots, this.nocase, this.childrenCache(), { fs: t }); + return new Ot(this.rootPath, I, void 0, this.roots, this.nocase, this.childrenCache(), { fs: t }); } isAbsolute(t) { return t.startsWith("/") || t.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(t); } }; - _2.PathScurryWin32 = Et; - var _t = class extends vt { + E.PathScurryWin32 = kt; + var Mt = class extends At { sep = "/"; constructor(t = process.cwd(), e = {}) { let { nocase: s = false } = e; - super(t, Yt.posix, "/", { ...e, nocase: s }), this.nocase = s; + super(t, ee.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 }); + return new Ct(this.rootPath, I, void 0, this.roots, this.nocase, this.childrenCache(), { fs: t }); } isAbsolute(t) { return t.startsWith("/"); } }; - _2.PathScurryPosix = _t; - var Zt = class extends _t { + E.PathScurryPosix = Mt; + var ie = class extends Mt { constructor(t = process.cwd(), e = {}) { let { nocase: s = true } = e; super(t, { ...e, nocase: s }); } }; - _2.PathScurryDarwin = Zt; - _2.Path = process.platform === "win32" ? yt : St; - _2.PathScurry = process.platform === "win32" ? Et : process.platform === "darwin" ? Zt : _t; + E.PathScurryDarwin = ie; + E.Path = process.platform === "win32" ? Ot : Ct; + E.PathScurry = process.platform === "win32" ? kt : process.platform === "darwin" ? ie : Mt; }); - var Re = R((te) => { + var Ke = x((ne) => { "use strict"; - Object.defineProperty(te, "__esModule", { value: true }); - te.Pattern = void 0; - var xr = H(), Tr = (n) => n.length >= 1, Cr = (n) => n.length >= 1, Rr = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), Ce = class n { + Object.defineProperty(ne, "__esModule", { value: true }); + ne.Pattern = void 0; + var Ur = Y(), $r = (n) => n.length >= 1, qr = (n) => n.length >= 1, Hr = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), Xe = class n { #t; - #s; - #n; + #i; + #e; length; - #r; #h; - #S; - #w; + #n; + #d; #c; + #p; #o; - #f = true; + #m = true; constructor(t, e, s, i) { - if (!Tr(t)) throw new TypeError("empty pattern list"); - if (!Cr(e)) throw new TypeError("empty glob list"); + if (!$r(t)) throw new TypeError("empty pattern list"); + if (!qr(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.#t = t, this.#i = e, this.#e = s, this.#h = i, this.#e === 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; + let r = this.#a() ? 6 : 4, h = this.#t.slice(0, r), a = this.#i.slice(0, r), o = this.#t.slice(r), l = this.#i.slice(r); + o[0] === "" && (o.shift(), l.shift()); + let c = [...h, ""].join("/"), u = [...a, ""].join("/"); + this.#t = [c, ...o], this.#i = [u, ...l], 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; + let [r, ...h] = this.#t, [a, ...o] = this.#i; + h[0] === "" && (h.shift(), o.shift()); + let l = `${r}/`, c = `${a}/`; + this.#t = [l, ...h], this.#i = [c, ...o], this.length = this.#t.length; } } } - [Rr]() { - return "Pattern <" + this.#s.slice(this.#n).join("/") + ">"; + [Hr]() { + return `Pattern <${this.#i.slice(this.#e).join("/")}>`; } pattern() { - return this.#t[this.#n]; + return this.#t[this.#e]; } isString() { - return typeof this.#t[this.#n] == "string"; + return typeof this.#t[this.#e] == "string"; } isGlobstar() { - return this.#t[this.#n] === xr.GLOBSTAR; + return this.#t[this.#e] === Ur.GLOBSTAR; } - isRegExp() { - return this.#t[this.#n] instanceof RegExp; + isMatcher() { + return typeof this.#t[this.#e] == "object"; } 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("/")); + return this.#d = this.#d || (this.#e === 0 ? this.isAbsolute() ? this.#i[0] + this.#i.slice(1).join("/") : this.#i.join("/") : this.#i.slice(this.#e).join("/")); } hasMore() { - return this.length > this.#n + 1; + return this.length > this.#e + 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; + return this.#n !== void 0 ? this.#n : this.hasMore() ? (this.#n = new n(this.#t, this.#i, this.#e + 1, this.#h), this.#n.#o = this.#o, this.#n.#p = this.#p, this.#n.#c = this.#c, this.#n) : this.#n = null; } - isUNC() { + #a() { 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]; + return t[2] === "?" && typeof t[3] == "string" && /^unc$/i.test(t[3]); + } + isUNC() { + let t = this.#t, e = this.#a() ? 4 : 2; + return this.#p !== void 0 ? this.#p : this.#p = this.#h === "win32" && this.#e === 0 && t[0] === "" && t[1] === "" && typeof t[e] == "string" && !!t[e] && typeof t[e + 1] == "string" && !!t[e + 1]; } 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]); + return this.#c !== void 0 ? this.#c : this.#c = this.#h === "win32" && this.#e === 0 && this.length > 1 && typeof t[0] == "string" && /^[a-z]:$/i.test(t[0]); } isAbsolute() { let t = this.#t; @@ -105805,40 +137929,43 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur } root() { let t = this.#t[0]; - return typeof t == "string" && this.isAbsolute() && this.#n === 0 ? t : ""; + return typeof t == "string" && this.isAbsolute() && this.#e === 0 ? t : ""; } checkFollowGlobstar() { - return !(this.#n === 0 || !this.isGlobstar() || !this.#f); + return !(this.#e === 0 || !this.isGlobstar() || !this.#m); } markFollowGlobstar() { - return this.#n === 0 || !this.isGlobstar() || !this.#f ? false : (this.#f = false, true); + return this.#e === 0 || !this.isGlobstar() || !this.#m ? false : (this.#m = false, true); } }; - te.Pattern = Ce; + ne.Pattern = Xe; }); - var ke = R((ee) => { + var Ze = x((he) => { "use strict"; - Object.defineProperty(ee, "__esModule", { value: true }); - ee.Ignore = void 0; - var Ps = H(), Ar = Re(), kr = typeof process == "object" && process && typeof process.platform == "string" ? process.platform : "linux", Ae = class { + Object.defineProperty(he, "__esModule", { value: true }); + he.Ignore = void 0; + var Ve = Y(), Xr = Ke(), Kr = typeof process == "object" && process && typeof process.platform == "string" ? process.platform : "linux", Ye = 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: true, nobrace: e, nocase: s, noext: i, noglobstar: r, optimizationLevel: 2, platform: h, nocomment: true, nonegate: true }; - for (let o of t) this.add(o); + slashRoot; + constructor(t, { nobrace: e, nocase: s, noext: i, noglobstar: r, normalize: h, platform: a = Kr, root: o, windowsPathsNoEscape: l, allowWindowsEscape: c }, u) { + this.relative = [], this.absolute = [], this.relativeChildren = [], this.absoluteChildren = [], this.platform = a, l = !!l || c === false, this.mmopts = { dot: true, nobrace: e, nocase: s, noext: i, noglobstar: r, normalize: h, optimizationLevel: 2, platform: a, nocomment: true, nonegate: true, windowsPathsNoEscape: l }; + let p = u?.resolve(o ?? "/").fullpath() ?? "/"; + this.slashRoot = (0, Ve.escape)(p.replace(/\\/g, "/").replace(/\/$/, ""), { windowsPathsNoEscape: l }); + for (let d of t) this.add(d); } add(t) { - let e = new Ps.Minimatch(t, this.mmopts); + let e = new Ve.Minimatch(t, this.mmopts); for (let s = 0; s < e.set.length; s++) { let i = e.set[s], r = e.globParts[s]; if (!i || !r) throw new Error("invalid pattern object"); for (; i[0] === "." && r[0] === "."; ) i.shift(), r.shift(); - let h = new Ar.Pattern(i, r, 0, this.platform), o = new Ps.Minimatch(h.globString(), this.mmopts), a = r[r.length - 1] === "**", l = h.isAbsolute(); - l ? this.absolute.push(o) : this.relative.push(o), a && (l ? this.absoluteChildren.push(o) : this.relativeChildren.push(o)); + let h = new Xr.Pattern(i, r, 0, this.platform), a = h.root() === "/" ? `${this.slashRoot}/${h.rest()?.globString() ?? ""}` : h.globString(), o = new Ve.Minimatch(a, this.mmopts), l = r[r.length - 1] === "**", c = h.isAbsolute(); + c ? this.absolute.push(o) : this.relative.push(o), l && (c ? this.absoluteChildren.push(o) : this.relativeChildren.push(o)); } } ignored(t) { @@ -105848,47 +137975,51 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur return false; } childrenIgnored(t) { - let e = t.fullpath() + "/", s = (t.relative() || ".") + "/"; + let e = `${t.fullpath()}/`, s = `${t.relative() || "."}/`; for (let i of this.relativeChildren) if (i.match(s)) return true; for (let i of this.absoluteChildren) if (i.match(e)) return true; return false; } }; - ee.Ignore = Ae; + he.Ignore = Ye; }); - var Fs = R((z) => { + var oi = x((U) => { "use strict"; - Object.defineProperty(z, "__esModule", { value: true }); - z.Processor = z.SubWalks = z.MatchRecord = z.HasWalkedCache = void 0; - var Ds = H(), se = class n { + Object.defineProperty(U, "__esModule", { value: true }); + U.Processor = U.SubWalks = U.MatchRecord = U.HasWalkedCache = void 0; + var hi = Y(), oe = class n { + parent; store; - constructor(t = /* @__PURE__ */ new Map()) { - this.store = t; + constructor(t) { + this.parent = t; } copy() { - return new n(new Map(this.store)); + return new n(this); + } + #t(t) { + let e = this.store?.get(t); + return e || !this.parent ? e : this.parent.#t(t); } hasWalked(t, e) { - return this.store.get(t.fullpath())?.has(e.globString()); + return !!this.#t(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, /* @__PURE__ */ new Set([e.globString()])); + let s = t.fullpath(), i = this.#t(s); + i ? i.add(e.globString()) : (this.store ??= /* @__PURE__ */ new Map()).set(s, /* @__PURE__ */ new Set([e.globString()])); } }; - z.HasWalkedCache = se; - var ie = class { + U.HasWalkedCache = oe; + var ae = class n { + static ABSOLUTE = 2; + static IF_DIR = 1; store = /* @__PURE__ */ new Map(); add(t, e, s) { - let i = (e ? 2 : 0) | (s ? 1 : 0), r = this.store.get(t); + let i = (e ? n.ABSOLUTE : 0) | (s ? n.IF_DIR : 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 { + U.MatchRecord = ae; + var le = class { store = /* @__PURE__ */ new Map(); add(t, e) { if (!t.canReaddir()) return; @@ -105907,53 +138038,53 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur return [...this.store.keys()].filter((t) => t.canReaddir()); } }; - z.SubWalks = re; - var Me = class n { + U.SubWalks = le; + var Je = class n { hasWalkedCache; - matches = new ie(); - subwalks = new re(); + matches = new ae(); + subwalks = new le(); 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(); + 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 h = r.root(), o = r.isAbsolute() && this.opts.absolute !== false; + let h = r.root(), a = r.isAbsolute() && this.opts.absolute !== false; if (h) { i = i.resolve(h === "/" && this.opts.root !== void 0 ? this.opts.root : h); - let c = r.rest(); - if (c) r = c; + let u = r.rest(); + if (u) r = u; else { this.matches.add(i, true, false); continue; } } if (i.isENOENT()) continue; - let a, l, f = false; - for (; typeof (a = r.pattern()) == "string" && (l = r.rest()); ) i = i.resolve(a), r = l, f = true; - if (a = r.pattern(), l = r.rest(), f) { + let o, l, c = false; + for (; typeof (o = r.pattern()) == "string" && (l = r.rest()); ) i = i.resolve(o), r = l, c = true; + if (o = r.pattern(), l = r.rest(), c) { 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); + if (typeof o == "string") { + let u = o === ".." || o === "" || o === "."; + this.matches.add(i.resolve(o), a, u); continue; - } else if (a === Ds.GLOBSTAR) { + } else if (o === hi.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, true); + let u = l?.pattern(), p = l?.rest(); + if (!l || (u === "" || u === ".") && !p) this.matches.add(i, a, u === "" || u === "."); + else if (u === "..") { + let d = i.parent || i; + p ? this.hasWalkedCache.hasWalked(d, p) || this.subwalks.add(d, p) : this.matches.add(d, a, true); } - } else a instanceof RegExp && this.subwalks.add(i, r); + } else typeof o == "object" && this.subwalks.add(i, r); } return this; } @@ -105966,8 +138097,8 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur 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); + let a = h.isAbsolute(), o = h.pattern(), l = h.rest(); + o === hi.GLOBSTAR ? i.testGlobstar(r, h, l, a) : typeof o == "object" ? i.testMatcher(r, o, l, a) : i.testString(r, o, l, a); } return i; } @@ -105978,23 +138109,23 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur else if (r === "..") { let h = t.parent || t; this.subwalks.add(h, s); - } else r instanceof RegExp && this.testRegExp(t, r, s.rest(), i); + } else typeof r == "object" && this.testMatcher(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, false)); + testMatcher(t, e, s, i) { + e.testUnchecked(t.name) && (s ? this.subwalks.add(t, s) : this.matches.add(t, i, false)); } testString(t, e, s, i) { t.isNamed(e) && (s ? this.subwalks.add(t, s) : this.matches.add(t, i, false)); } }; - z.Processor = Me; + U.Processor = Je; }); - var Ls = R((X) => { + var li = x((Q) => { "use strict"; - Object.defineProperty(X, "__esModule", { value: true }); - 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 { + Object.defineProperty(Q, "__esModule", { value: true }); + Q.GlobStream = Q.GlobWalker = Q.GlobUtil = void 0; + var Vr = $e(), ai = Ze(), Qe = oi(), { ABSOLUTE: ce, IF_DIR: ue } = Qe.MatchRecord, Yr = (n, t, e) => typeof n == "string" ? new ai.Ignore([n], t, e) : Array.isArray(n) ? new ai.Ignore(n, t, e) : n, xt = class { path; patterns; opts; @@ -106002,13 +138133,13 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur paused = false; aborted = false; #t = []; - #s; - #n; + #i; + #e; 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 !== false, (s.ignore || !this.includeChildMatches) && (this.#s = Pr(s.ignore ?? [], s), !this.includeChildMatches && typeof this.#s.add != "function")) { + if (this.patterns = t, this.path = e, this.opts = s, this.#e = !s.posix && s.platform === "win32" ? "\\" : "/", this.includeChildMatches = s.includeChildMatches !== false, (s.ignore || !this.includeChildMatches) && (this.#i = Yr(s.ignore ?? [], s, e), !this.includeChildMatches && typeof this.#i.add != "function")) { let i = "cannot ignore child matches, ignore lacks add() method."; throw new Error(i); } @@ -106016,11 +138147,11 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur this.#t.length = 0; })); } - #r(t) { - return this.seen.has(t) || !!this.#s?.ignored?.(t); - } #h(t) { - return !!this.#s?.childrenIgnored?.(t); + return this.seen.has(t) || !!this.#i?.ignored?.(t); + } + #n(t) { + return !!this.#i?.childrenIgnored?.(t); } pause() { this.paused = true; @@ -106032,55 +138163,57 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur for (; !this.paused && (t = this.#t.shift()); ) t(); } onResume(t) { - this.signal?.aborted || (this.paused ? this.#t.push(t) : t()); + this.paused ? this.#t.push(t) : t(); } async matchCheck(t, e) { if (e && this.opts.nodir) return; - let s; + let s, i; 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(); + i = s; + } else i = t; + let h = i.isUnknown() || this.opts.stat ? await i.lstat() : i; + if (this.opts.follow && this.opts.nodir && h?.isSymbolicLink()) { + let a = await h.realpath(); + a && (a.isUnknown() || this.opts.stat) && await a.lstat(); } - return this.matchCheckTest(r, e); + return this.matchCheckTest(h, 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; + 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.#h(t) ? t : void 0; } matchCheckSync(t, e) { if (e && this.opts.nodir) return; - let s; + let s, i; if (this.opts.realpath) { if (s = t.realpathCached() || t.realpathSync(), !s) return; - t = s; + i = s; + } else i = t; + let h = i.isUnknown() || this.opts.stat ? i.lstatSync() : i; + if (this.opts.follow && this.opts.nodir && h?.isSymbolicLink()) { + let a = h.realpathSync(); + a && (a?.isUnknown() || this.opts.stat) && a.lstatSync(); } - 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); + return this.matchCheckTest(h, e); } matchFinish(t, e) { - if (this.#r(t)) return; - if (!this.includeChildMatches && this.#s?.add) { + this.#h(t) || this.#d(t, e); + } + #d(t, e) { + if (!this.includeChildMatches && this.#i?.add) { let r = `${t.relativePosix()}/**`; - this.#s.add(r); + this.#i.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 : ""; + let i = this.opts.mark && t.isDirectory() ? this.#e : ""; 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); + let r = this.opts.posix ? t.relativePosix() : t.relative(), h = this.opts.dotRelative && !r.startsWith(`..${this.#e}`) ? `.${this.#e}` : ""; + this.matchEmit(r ? h + r + i : `.${i}`); } } async match(t, e, s) { @@ -106089,14 +138222,15 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur } matchSync(t, e, s) { let i = this.matchCheckSync(t, s); - i && this.matchFinish(i, e); + i && this.#d(i, e); } walkCB(t, e, s) { - this.signal?.aborted && s(), this.walkCB2(t, e, new Ns.Processor(this.opts), s); + if (this.signal?.aborted) return s(); + this.walkCB2(t, e, new Qe.Processor(this.opts), s); } walkCB2(t, e, s, i) { - if (this.#h(t)) return i(); - if (this.signal?.aborted && i(), this.paused) { + if (this.#n(t) || this.signal?.aborted) return i(); + if (this.paused) { this.onResume(() => this.walkCB2(t, e, s, i)); return; } @@ -106104,30 +138238,30 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur 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; + for (let [a, o] of s.matches.store) this.#h(a) || (r++, this.match(a, !!(o & ce), !!(o & ue)).then(() => h())); + for (let a of s.subwalkTargets()) { + if (this.maxDepth !== 1 / 0 && a.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), true); + let o = a.readdirCached(); + a.calledReaddir() ? this.walkCB3(a, o, s, h) : a.readdirCB((l, c) => this.walkCB3(a, c, s, h), true); } h(); } walkCB3(t, e, s, i) { - s = s.filterEntries(t, e); - let r = 1, h = () => { - --r === 0 && i(); + let r = s.filterEntries(t, e), h = 1, a = () => { + --h === 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(); + for (let [o, l] of r.matches.store) this.#h(o) || (h++, this.match(o, !!(l & ce), !!(l & ue)).then(() => a())); + for (let [o, l] of r.subwalks.entries()) h++, this.walkCB2(o, l, r.child(), a); + a(); } walkCBSync(t, e, s) { - this.signal?.aborted && s(), this.walkCB2Sync(t, e, new Ns.Processor(this.opts), s); + if (this.signal?.aborted) return s(); + this.walkCB2Sync(t, e, new Qe.Processor(this.opts), s); } walkCB2Sync(t, e, s, i) { - if (this.#h(t)) return i(); - if (this.signal?.aborted && i(), this.paused) { + if (this.#n(t) || this.signal?.aborted) return i(); + if (this.paused) { this.onResume(() => this.walkCB2Sync(t, e, s, i)); return; } @@ -106135,33 +138269,32 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur 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; + for (let [a, o] of s.matches.store) this.#h(a) || this.matchSync(a, !!(o & ce), !!(o & ue)); + for (let a of s.subwalkTargets()) { + if (this.maxDepth !== 1 / 0 && a.depth() >= this.maxDepth) continue; r++; - let a = o.readdirSync(); - this.walkCB3Sync(o, a, s, h); + let o = a.readdirSync(); + this.walkCB3Sync(a, o, s, h); } h(); } walkCB3Sync(t, e, s, i) { - s = s.filterEntries(t, e); - let r = 1, h = () => { - --r === 0 && i(); + let r = s.filterEntries(t, e), h = 1, a = () => { + --h === 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(); + for (let [o, l] of r.matches.store) this.#h(o) || this.matchSync(o, !!(l & ce), !!(l & ue)); + for (let [o, l] of r.subwalks.entries()) h++, this.walkCB2Sync(o, l, r.child(), a); + a(); } }; - X.GlobUtil = Ot; - var Pe = class extends Ot { - matches = /* @__PURE__ */ new Set(); + Q.GlobUtil = xt; + var ts = class extends xt { + matches = []; constructor(t, e, s) { super(t, e, s); } matchEmit(t) { - this.matches.add(t); + this.matches.push(t); } async walk() { if (this.signal?.aborted) throw this.signal.reason; @@ -106178,11 +138311,11 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur }), this.matches; } }; - X.GlobWalker = Pe; - var De = class extends Ot { + Q.GlobWalker = ts; + var es = class extends xt { results; constructor(t, e, s) { - super(t, e, s), this.results = new Mr.Minipass({ signal: this.signal, objectMode: true }), this.results.on("drain", () => this.resume()), this.results.on("resume", () => this.resume()); + super(t, e, s), this.results = new Vr.Minipass({ signal: this.signal, objectMode: true }), this.results.on("drain", () => this.resume()), this.results.on("resume", () => this.resume()); } matchEmit(t) { this.results.write(t), this.results.flowing || this.pause(); @@ -106197,13 +138330,13 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur return this.path.isUnknown() && this.path.lstatSync(), this.walkCBSync(this.path, this.patterns, () => this.results.end()), this.results; } }; - X.GlobStream = De; + Q.GlobStream = es; }); - var je = R((oe) => { + var is = x((pe) => { "use strict"; - Object.defineProperty(oe, "__esModule", { value: true }); - 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 { + Object.defineProperty(pe, "__esModule", { value: true }); + pe.Glob = void 0; + var Zr = Y(), Jr = require("node:url"), fe = ni(), Qr = Ke(), de = li(), tn = typeof process == "object" && process && typeof process.platform == "string" ? process.platform : "linux", ss = class { absolute; cwd; root; @@ -106233,36 +138366,37 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur 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 !== false, 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 === false, this.windowsPathsNoEscape && (t = t.map((a) => a.replace(/\\/g, "/"))), this.matchBase) { + 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, Jr.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 !== false, 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"); + let s = typeof t == "string" ? [t] : t; + if (this.windowsPathsNoEscape = !!e.windowsPathsNoEscape || e.allowWindowsEscape === false, this.windowsPathsNoEscape && (s = s.map((l) => l.replace(/\\/g, "/"))), this.matchBase) { if (e.noglobstar) throw new TypeError("base matching requires globstar"); - t = t.map((a) => a.includes("/") ? a : `./**/${a}`); + s = s.map((l) => l.includes("/") ? l : `./**/${l}`); } - if (this.pattern = t, this.platform = e.platform || Nr, this.opts = { ...e, platform: this.platform }, e.scurry) { + if (this.pattern = s, this.platform = e.platform || tn, 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 }); + let l = e.platform === "win32" ? fe.PathScurryWin32 : e.platform === "darwin" ? fe.PathScurryDarwin : e.platform ? fe.PathScurryPosix : fe.PathScurry; + this.scurry = new l(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: true, noext: this.noext, nonegate: true, 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); + let i = this.platform === "darwin" || this.platform === "win32", r = { braceExpandMax: 1e4, ...e, dot: this.dot, matchBase: this.matchBase, nobrace: this.nobrace, nocase: this.nocase, nocaseMagicOnly: i, nocomment: true, noext: this.noext, nonegate: true, optimizationLevel: 2, platform: this.platform, windowsPathsNoEscape: this.windowsPathsNoEscape }, h = this.pattern.map((l) => new Zr.Minimatch(l, r)), [a, o] = h.reduce((l, c) => (l[0].push(...c.set), l[1].push(...c.globParts), l), [[], []]); + this.patterns = a.map((l, c) => { + let u = o[c]; + if (!u) throw new Error("invalid pattern object"); + return new Qr.Pattern(l, u, 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()]; + return await new de.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()]; + return new de.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(); + return new de.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(); + return new de.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](); @@ -106277,80 +138411,79 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur return this.iterate(); } }; - oe.Glob = Fe; + pe.Glob = ss; }); - var Ne = R((ae) => { + var rs = x((me) => { "use strict"; - Object.defineProperty(ae, "__esModule", { value: true }); - 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 true; + Object.defineProperty(me, "__esModule", { value: true }); + me.hasMagic = void 0; + var en = Y(), sn = (n, t = {}) => { + for (let e of Array.isArray(n) ? n : [n]) if (new en.Minimatch(e, t).hasMagic()) return true; return false; }; - ae.hasMagic = Wr; + me.hasMagic = sn; }); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.glob = exports2.sync = exports2.iterate = exports2.iterateSync = exports2.stream = exports2.streamSync = exports2.Ignore = exports2.hasMagic = exports2.Glob = exports2.unescape = exports2.escape = void 0; - exports2.globStreamSync = xt; - exports2.globStream = Le; - exports2.globSync = We; - exports2.globIterateSync = Tt; - exports2.globIterate = Be; - var Ws = H(); - var tt = je(); - var Br = Ne(); - var Is = H(); + exports2.globStreamSync = Rt; + exports2.globStream = ns; + exports2.globSync = hs; + exports2.globIterateSync = Pt; + exports2.globIterate = os8; + var ci = Y(); + var rt = is(); + var rn = rs(); + var fi = Y(); Object.defineProperty(exports2, "escape", { enumerable: true, get: function() { - return Is.escape; + return fi.escape; } }); Object.defineProperty(exports2, "unescape", { enumerable: true, get: function() { - return Is.unescape; + return fi.unescape; } }); - var Ir = je(); + var nn = is(); Object.defineProperty(exports2, "Glob", { enumerable: true, get: function() { - return Ir.Glob; + return nn.Glob; } }); - var Gr = Ne(); + var hn = rs(); Object.defineProperty(exports2, "hasMagic", { enumerable: true, get: function() { - return Gr.hasMagic; + return hn.hasMagic; } }); - var zr = ke(); + var on = Ze(); Object.defineProperty(exports2, "Ignore", { enumerable: true, get: function() { - return zr.Ignore; + return on.Ignore; } }); - function xt(n, t = {}) { - return new tt.Glob(n, t).streamSync(); + function Rt(n, t = {}) { + return new rt.Glob(n, t).streamSync(); } - function Le(n, t = {}) { - return new tt.Glob(n, t).stream(); + function ns(n, t = {}) { + return new rt.Glob(n, t).stream(); } - function We(n, t = {}) { - return new tt.Glob(n, t).walkSync(); + function hs(n, t = {}) { + return new rt.Glob(n, t).walkSync(); } - async function Bs(n, t = {}) { - return new tt.Glob(n, t).walk(); + async function ui(n, t = {}) { + return new rt.Glob(n, t).walk(); } - function Tt(n, t = {}) { - return new tt.Glob(n, t).iterateSync(); + function Pt(n, t = {}) { + return new rt.Glob(n, t).iterateSync(); } - function Be(n, t = {}) { - return new tt.Glob(n, t).iterate(); + function os8(n, t = {}) { + return new rt.Glob(n, t).iterate(); } - exports2.streamSync = xt; - exports2.stream = Object.assign(Le, { sync: xt }); - exports2.iterateSync = Tt; - exports2.iterate = Object.assign(Be, { sync: Tt }); - exports2.sync = Object.assign(We, { stream: xt, iterate: Tt }); - exports2.glob = Object.assign(Bs, { glob: Bs, globSync: We, sync: exports2.sync, globStream: Le, stream: exports2.stream, globStreamSync: xt, streamSync: exports2.streamSync, globIterate: Be, iterate: exports2.iterate, globIterateSync: Tt, iterateSync: exports2.iterateSync, Glob: tt.Glob, hasMagic: Br.hasMagic, escape: Ws.escape, unescape: Ws.unescape }); + exports2.streamSync = Rt; + exports2.stream = Object.assign(ns, { sync: Rt }); + exports2.iterateSync = Pt; + exports2.iterate = Object.assign(os8, { sync: Pt }); + exports2.sync = Object.assign(hs, { stream: Rt, iterate: Pt }); + exports2.glob = Object.assign(ui, { glob: ui, globSync: hs, sync: exports2.sync, globStream: ns, stream: exports2.stream, globStreamSync: Rt, streamSync: exports2.streamSync, globIterate: os8, iterate: exports2.iterate, globIterateSync: Pt, iterateSync: exports2.iterateSync, Glob: rt.Glob, hasMagic: rn.hasMagic, escape: ci.escape, unescape: ci.unescape }); exports2.glob.glob = exports2.glob; } }); // node_modules/archiver-utils/file.js -var require_file3 = __commonJS({ +var require_file2 = __commonJS({ "node_modules/archiver-utils/file.js"(exports2, module2) { - var fs32 = require_graceful_fs(); + var fs34 = require_graceful_fs(); var path30 = require("path"); var flatten = require_flatten(); var difference = require_difference(); @@ -106377,7 +138510,7 @@ var require_file3 = __commonJS({ }; file.exists = function() { var filepath = path30.join.apply(path30, arguments); - return fs32.existsSync(filepath); + return fs34.existsSync(filepath); }; file.expand = function(...args) { var options = isPlainObject4(args[0]) ? args.shift() : {}; @@ -106395,7 +138528,7 @@ var require_file3 = __commonJS({ if (typeof options.filter === "function") { return options.filter(filepath); } else { - return fs32.statSync(filepath)[options.filter](); + return fs34.statSync(filepath)[options.filter](); } } catch (e) { return false; @@ -106503,7 +138636,7 @@ var require_file3 = __commonJS({ // node_modules/archiver-utils/index.js var require_archiver_utils = __commonJS({ "node_modules/archiver-utils/index.js"(exports2, module2) { - var fs32 = require_graceful_fs(); + var fs34 = require_graceful_fs(); var path30 = require("path"); var isStream2 = require_is_stream(); var lazystream = require_lazystream(); @@ -106512,7 +138645,7 @@ var require_archiver_utils = __commonJS({ var Stream = require("stream").Stream; var PassThrough3 = require_ours().PassThrough; var utils = module2.exports = {}; - utils.file = require_file3(); + utils.file = require_file2(); utils.collectStream = function(source, callback) { var collection = []; var size = 0; @@ -106552,7 +138685,7 @@ var require_archiver_utils = __commonJS({ }; utils.lazyReadStream = function(filepath) { return new lazystream.Readable(function() { - return fs32.createReadStream(filepath); + return fs34.createReadStream(filepath); }); }; utils.normalizeInputSource = function(source) { @@ -106580,7 +138713,7 @@ var require_archiver_utils = __commonJS({ callback = base; base = dirpath; } - fs32.readdir(dirpath, function(err, list) { + fs34.readdir(dirpath, function(err, list) { var i = 0; var file; var filepath; @@ -106593,7 +138726,7 @@ var require_archiver_utils = __commonJS({ return callback(null, results); } filepath = path30.join(dirpath, file); - fs32.stat(filepath, function(err2, stats) { + fs34.stat(filepath, function(err2, stats) { results.push({ path: filepath, relative: path30.relative(base, filepath).replace(/\\/g, "/"), @@ -106622,7 +138755,7 @@ var require_archiver_utils = __commonJS({ // node_modules/@actions/artifact/node_modules/archiver/lib/error.js var require_error3 = __commonJS({ "node_modules/@actions/artifact/node_modules/archiver/lib/error.js"(exports2, module2) { - var util3 = require("util"); + var util4 = require("util"); var ERROR_CODES2 = { "ABORTED": "archive was aborted", "DIRECTORYDIRPATHREQUIRED": "diretory dirpath argument must be a non-empty string value", @@ -106647,7 +138780,7 @@ var require_error3 = __commonJS({ this.code = code; this.data = data; } - util3.inherits(ArchiverError2, Error); + util4.inherits(ArchiverError2, Error); exports2 = module2.exports = ArchiverError2; } }); @@ -106655,11 +138788,11 @@ var require_error3 = __commonJS({ // node_modules/@actions/artifact/node_modules/archiver/lib/core.js var require_core2 = __commonJS({ "node_modules/@actions/artifact/node_modules/archiver/lib/core.js"(exports2, module2) { - var fs32 = require("fs"); + var fs34 = require("fs"); var glob2 = require_readdir_glob(); var async = require_async(); var path30 = require("path"); - var util3 = require_archiver_utils(); + var util4 = require_archiver_utils(); var inherits = require("util").inherits; var ArchiverError2 = require_error3(); var Transform5 = require_ours().Transform; @@ -106672,7 +138805,7 @@ var require_core2 = __commonJS({ options = format; format = "zip"; } - options = this.options = util3.defaults(options, { + options = this.options = util4.defaults(options, { highWaterMark: 1024 * 1024, statConcurrency: 4 }); @@ -106719,7 +138852,7 @@ var require_core2 = __commonJS({ data.sourcePath = filepath; task.data = data; this._entriesCount++; - if (data.stats && data.stats instanceof fs32.Stats) { + if (data.stats && data.stats instanceof fs34.Stats) { task = this._updateQueueTaskWithStats(task, data.stats); if (task) { if (data.stats.size) { @@ -106809,7 +138942,7 @@ var require_core2 = __commonJS({ this._state.modulePiped = false; }; Archiver2.prototype._normalizeEntryData = function(data, stats) { - data = util3.defaults(data, { + data = util4.defaults(data, { type: "file", name: null, date: null, @@ -106827,7 +138960,7 @@ var require_core2 = __commonJS({ data.name = data.prefix + "/" + data.name; data.prefix = null; } - data.name = util3.sanitizePath(data.name); + data.name = util4.sanitizePath(data.name); if (data.type !== "symlink" && data.name.slice(-1) === "/") { isDir = true; data.type = "directory"; @@ -106856,7 +138989,7 @@ var require_core2 = __commonJS({ if (data.stats && data.date === null) { data.date = data.stats.mtime; } else { - data.date = util3.dateify(data.date); + data.date = util4.dateify(data.date); } return data; }; @@ -106890,7 +139023,7 @@ var require_core2 = __commonJS({ callback(); return; } - fs32.lstat(task.filepath, function(err, stats) { + fs34.lstat(task.filepath, function(err, stats) { if (this._state.aborted) { setImmediate(callback); return; @@ -106925,15 +139058,15 @@ var require_core2 = __commonJS({ if (stats.isFile()) { task.data.type = "file"; task.data.sourceType = "stream"; - task.source = util3.lazyReadStream(task.filepath); + task.source = util4.lazyReadStream(task.filepath); } else if (stats.isDirectory() && this._moduleSupports("directory")) { - task.data.name = util3.trailingSlashIt(task.data.name); + task.data.name = util4.trailingSlashIt(task.data.name); task.data.type = "directory"; - task.data.sourcePath = util3.trailingSlashIt(task.filepath); + task.data.sourcePath = util4.trailingSlashIt(task.filepath); task.data.sourceType = "buffer"; task.source = Buffer.concat([]); } else if (stats.isSymbolicLink() && this._moduleSupports("symlink")) { - var linkPath = fs32.readlinkSync(task.filepath); + var linkPath = fs34.readlinkSync(task.filepath); var dirName = path30.dirname(task.filepath); task.data.type = "symlink"; task.data.linkname = path30.relative(dirName, path30.resolve(dirName, linkPath)); @@ -106973,10 +139106,10 @@ var require_core2 = __commonJS({ this.emit("error", new ArchiverError2("DIRECTORYNOTSUPPORTED", { name: data.name })); return this; } - source = util3.normalizeInputSource(source); + source = util4.normalizeInputSource(source); if (Buffer.isBuffer(source)) { data.sourceType = "buffer"; - } else if (util3.isStream(source)) { + } else if (util4.isStream(source)) { data.sourceType = "stream"; } else { this.emit("error", new ArchiverError2("INPUTSTEAMBUFFERREQUIRED", { name: data.name })); @@ -107069,7 +139202,7 @@ var require_core2 = __commonJS({ }; Archiver2.prototype.glob = function(pattern, options, data) { this._pending++; - options = util3.defaults(options, { + options = util4.defaults(options, { stat: true, pattern }); @@ -107110,11 +139243,11 @@ var require_core2 = __commonJS({ this._finalize(); } var self2 = this; - return new Promise(function(resolve14, reject) { + return new Promise(function(resolve15, reject) { var errored; self2._module.on("end", function() { if (!errored) { - resolve14(); + resolve15(); } }); self2._module.on("error", function(err) { @@ -107204,10 +139337,10 @@ var require_archive_entry = __commonJS({ }); // node_modules/@actions/artifact/node_modules/compress-commons/lib/archivers/zip/util.js -var require_util14 = __commonJS({ +var require_util12 = __commonJS({ "node_modules/@actions/artifact/node_modules/compress-commons/lib/archivers/zip/util.js"(exports2, module2) { - var util3 = module2.exports = {}; - util3.dateToDos = function(d, forceLocalTime) { + var util4 = module2.exports = {}; + util4.dateToDos = function(d, forceLocalTime) { forceLocalTime = forceLocalTime || false; var year = forceLocalTime ? d.getFullYear() : d.getUTCFullYear(); if (year < 1980) { @@ -107225,36 +139358,36 @@ var require_util14 = __commonJS({ }; return val.year - 1980 << 25 | val.month + 1 << 21 | val.date << 16 | val.hours << 11 | val.minutes << 5 | val.seconds / 2; }; - util3.dosToDate = function(dos) { + util4.dosToDate = function(dos) { return new Date((dos >> 25 & 127) + 1980, (dos >> 21 & 15) - 1, dos >> 16 & 31, dos >> 11 & 31, dos >> 5 & 63, (dos & 31) << 1); }; - util3.fromDosTime = function(buf) { - return util3.dosToDate(buf.readUInt32LE(0)); + util4.fromDosTime = function(buf) { + return util4.dosToDate(buf.readUInt32LE(0)); }; - util3.getEightBytes = function(v) { + util4.getEightBytes = function(v) { var buf = Buffer.alloc(8); buf.writeUInt32LE(v % 4294967296, 0); buf.writeUInt32LE(v / 4294967296 | 0, 4); return buf; }; - util3.getShortBytes = function(v) { + util4.getShortBytes = function(v) { var buf = Buffer.alloc(2); buf.writeUInt16LE((v & 65535) >>> 0, 0); return buf; }; - util3.getShortBytesValue = function(buf, offset) { + util4.getShortBytesValue = function(buf, offset) { return buf.readUInt16LE(offset); }; - util3.getLongBytes = function(v) { + util4.getLongBytes = function(v) { var buf = Buffer.alloc(4); buf.writeUInt32LE((v & 4294967295) >>> 0, 0); return buf; }; - util3.getLongBytesValue = function(buf, offset) { + util4.getLongBytesValue = function(buf, offset) { return buf.readUInt32LE(offset); }; - util3.toDosTime = function(d) { - return util3.getLongBytes(util3.dateToDos(d)); + util4.toDosTime = function(d) { + return util4.getLongBytes(util4.dateToDos(d)); }; } }); @@ -107262,7 +139395,7 @@ var require_util14 = __commonJS({ // node_modules/@actions/artifact/node_modules/compress-commons/lib/archivers/zip/general-purpose-bit.js var require_general_purpose_bit = __commonJS({ "node_modules/@actions/artifact/node_modules/compress-commons/lib/archivers/zip/general-purpose-bit.js"(exports2, module2) { - var zipUtil = require_util14(); + var zipUtil = require_util12(); var DATA_DESCRIPTOR_FLAG2 = 1 << 3; var ENCRYPTION_FLAG2 = 1 << 0; var NUMBER_OF_SHANNON_FANO_TREES_FLAG2 = 1 << 2; @@ -107389,7 +139522,7 @@ var require_unix_stat = __commonJS({ }); // node_modules/@actions/artifact/node_modules/compress-commons/lib/archivers/zip/constants.js -var require_constants13 = __commonJS({ +var require_constants14 = __commonJS({ "node_modules/@actions/artifact/node_modules/compress-commons/lib/archivers/zip/constants.js"(exports2, module2) { module2.exports = { WORD: 4, @@ -107473,8 +139606,8 @@ var require_zip_archive_entry = __commonJS({ var ArchiveEntry2 = require_archive_entry(); var GeneralPurposeBit2 = require_general_purpose_bit(); var UnixStat = require_unix_stat(); - var constants = require_constants13(); - var zipUtil = require_util14(); + var constants = require_constants14(); + var zipUtil = require_util12(); var ZipArchiveEntry2 = module2.exports = function(name) { if (!(this instanceof ZipArchiveEntry2)) { return new ZipArchiveEntry2(name); @@ -107654,13 +139787,13 @@ var require_is_stream2 = __commonJS({ }); // node_modules/@actions/artifact/node_modules/compress-commons/lib/util/index.js -var require_util15 = __commonJS({ +var require_util13 = __commonJS({ "node_modules/@actions/artifact/node_modules/compress-commons/lib/util/index.js"(exports2, module2) { var Stream = require("stream").Stream; var PassThrough3 = require_ours().PassThrough; var isStream2 = require_is_stream2(); - var util3 = module2.exports = {}; - util3.normalizeInputSource = function(source) { + var util4 = module2.exports = {}; + util4.normalizeInputSource = function(source) { if (source === null) { return Buffer.alloc(0); } else if (typeof source === "string") { @@ -107682,7 +139815,7 @@ var require_archive_output_stream = __commonJS({ var isStream2 = require_is_stream2(); var Transform5 = require_ours().Transform; var ArchiveEntry2 = require_archive_entry(); - var util3 = require_util15(); + var util4 = require_util13(); var ArchiveOutputStream2 = module2.exports = function(options) { if (!(this instanceof ArchiveOutputStream2)) { return new ArchiveOutputStream2(options); @@ -107732,7 +139865,7 @@ var require_archive_output_stream = __commonJS({ this._archive.processing = true; this._normalizeEntry(ae); this._entry = ae; - source = util3.normalizeInputSource(source); + source = util4.normalizeInputSource(source); if (Buffer.isBuffer(source)) { this._appendBuffer(ae, source, callback); } else if (isStream2(source)) { @@ -107965,9 +140098,9 @@ var require_zip_archive_output_stream = __commonJS({ var ArchiveOutputStream2 = require_archive_output_stream(); var ZipArchiveEntry2 = require_zip_archive_entry(); var GeneralPurposeBit2 = require_general_purpose_bit(); - var constants = require_constants13(); - var util3 = require_util15(); - var zipUtil = require_util14(); + var constants = require_constants14(); + var util4 = require_util13(); + var zipUtil = require_util12(); var ZipArchiveOutputStream2 = module2.exports = function(options) { if (!(this instanceof ZipArchiveOutputStream2)) { return new ZipArchiveOutputStream2(options); @@ -108258,7 +140391,7 @@ var require_zip_stream = __commonJS({ var inherits = require("util").inherits; var ZipArchiveOutputStream2 = require_compress_commons().ZipArchiveOutputStream; var ZipArchiveEntry2 = require_compress_commons().ZipArchiveEntry; - var util3 = require_archiver_utils(); + var util4 = require_archiver_utils(); var ZipStream2 = module2.exports = function(options) { if (!(this instanceof ZipStream2)) { return new ZipStream2(options); @@ -108280,7 +140413,7 @@ var require_zip_stream = __commonJS({ }; inherits(ZipStream2, ZipArchiveOutputStream2); ZipStream2.prototype._normalizeFileData = function(data) { - data = util3.defaults(data, { + data = util4.defaults(data, { type: "file", name: null, namePrependSlash: this.options.namePrependSlash, @@ -108293,7 +140426,7 @@ var require_zip_stream = __commonJS({ var isDir = data.type === "directory"; var isSymlink = data.type === "symlink"; if (data.name) { - data.name = util3.sanitizePath(data.name); + data.name = util4.sanitizePath(data.name); if (!isSymlink && data.name.slice(-1) === "/") { isDir = true; data.type = "directory"; @@ -108304,7 +140437,7 @@ var require_zip_stream = __commonJS({ if (isDir || isSymlink) { data.store = true; } - data.date = util3.dateify(data.date); + data.date = util4.dateify(data.date); return data; }; ZipStream2.prototype.entry = function(source, data, callback) { @@ -108359,12 +140492,12 @@ var require_zip_stream = __commonJS({ var require_zip = __commonJS({ "node_modules/@actions/artifact/node_modules/archiver/lib/plugins/zip.js"(exports2, module2) { var engine2 = require_zip_stream(); - var util3 = require_archiver_utils(); + var util4 = require_archiver_utils(); var Zip2 = function(options) { if (!(this instanceof Zip2)) { return new Zip2(options); } - options = this.options = util3.defaults(options, { + options = this.options = util4.defaults(options, { comment: "", forceUTC: false, namePrependSlash: false, @@ -109033,7 +141166,7 @@ var require_streamx = __commonJS({ if (typeof cb !== "function") cb = null; this.stream._duplexState |= READ_PIPE_DRAINED; this.pipeTo = pipeTo; - this.pipeline = new Pipeline(this.stream, pipeTo, cb); + this.pipeline = new Pipeline2(this.stream, pipeTo, cb); if (cb) this.stream.on("error", noop3); if (isStreamx(pipeTo)) { pipeTo._writableState.pipeline = this.pipeline; @@ -109167,7 +141300,7 @@ var require_streamx = __commonJS({ this.afterFinal = null; } }; - var Pipeline = class { + var Pipeline2 = class { constructor(src, dst, cb) { this.from = src; this.to = dst; @@ -109367,7 +141500,7 @@ var require_streamx = __commonJS({ } } }; - var Readable3 = class _Readable extends Stream { + var Readable4 = class _Readable extends Stream { constructor(opts) { super(opts); this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD; @@ -109473,8 +141606,8 @@ var require_streamx = __commonJS({ return this; }, next() { - return new Promise(function(resolve14, reject) { - promiseResolve = resolve14; + return new Promise(function(resolve15, reject) { + promiseResolve = resolve15; promiseReject = reject; const data = stream2.read(); if (data !== null) ondata(data); @@ -109503,11 +141636,11 @@ var require_streamx = __commonJS({ } function destroy(err) { stream2.destroy(err); - return new Promise((resolve14, reject) => { - if (stream2._duplexState & DESTROYED) return resolve14({ value: void 0, done: true }); + return new Promise((resolve15, reject) => { + if (stream2._duplexState & DESTROYED) return resolve15({ value: void 0, done: true }); stream2.once("close", function() { if (err) reject(err); - else resolve14({ value: void 0, done: true }); + else resolve15({ value: void 0, done: true }); }); }); } @@ -109551,8 +141684,8 @@ var require_streamx = __commonJS({ const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0); if (writes === 0) return Promise.resolve(true); if (state.drains === null) state.drains = []; - return new Promise((resolve14) => { - state.drains.push({ writes, resolve: resolve14 }); + return new Promise((resolve15) => { + state.drains.push({ writes, resolve: resolve15 }); }); } write(data) { @@ -109565,7 +141698,7 @@ var require_streamx = __commonJS({ return this; } }; - var Duplex = class extends Readable3 { + var Duplex4 = class extends Readable4 { // and Writable constructor(opts) { super(opts); @@ -109603,7 +141736,7 @@ var require_streamx = __commonJS({ return this; } }; - var Transform5 = class extends Duplex { + var Transform5 = class extends Duplex4 { constructor(opts) { super(opts); this._transformState = new TransformState(this); @@ -109657,10 +141790,10 @@ var require_streamx = __commonJS({ cb(null); } function pipelinePromise(...streams) { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { return pipeline2(...streams, (err) => { if (err) return reject(err); - resolve14(); + resolve15(); }); }); } @@ -109746,7 +141879,7 @@ var require_streamx = __commonJS({ this.destroy(new Error("Stream aborted.")); } function isWritev(s) { - return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev; + return s._writev !== Writable.prototype._writev && s._writev !== Duplex4.prototype._writev; } module2.exports = { pipeline: pipeline2, @@ -109758,8 +141891,8 @@ var require_streamx = __commonJS({ getStreamError, Stream, Writable, - Readable: Readable3, - Duplex, + Readable: Readable4, + Duplex: Duplex4, Transform: Transform5, // Export PassThrough for compatibility with Node.js core's stream module PassThrough: PassThrough3 @@ -110031,7 +142164,7 @@ var require_headers2 = __commonJS({ // node_modules/tar-stream/extract.js var require_extract = __commonJS({ "node_modules/tar-stream/extract.js"(exports2, module2) { - var { Writable, Readable: Readable3, getStreamError } = require_streamx(); + var { Writable, Readable: Readable4, getStreamError } = require_streamx(); var FIFO = require_fast_fifo(); var b4a = require_b4a(); var headers = require_headers2(); @@ -110078,7 +142211,7 @@ var require_extract = __commonJS({ return buf.subarray(this._offset, this._offset += size); } }; - var Source = class extends Readable3 { + var Source = class extends Readable4 { constructor(self2, header, offset) { super(); this.header = header; @@ -110303,16 +142436,16 @@ var require_extract = __commonJS({ entryCallback = null; cb(err); } - function onnext(resolve14, reject) { + function onnext(resolve15, reject) { if (error3) { return reject(error3); } if (entryStream) { - resolve14({ value: entryStream, done: false }); + resolve15({ value: entryStream, done: false }); entryStream = null; return; } - promiseResolve = resolve14; + promiseResolve = resolve15; promiseReject = reject; consumeCallback(null); if (extract2._finished && promiseResolve) { @@ -110340,11 +142473,11 @@ var require_extract = __commonJS({ function destroy(err) { extract2.destroy(err); consumeCallback(err); - return new Promise((resolve14, reject) => { - if (extract2.destroyed) return resolve14({ value: void 0, done: true }); + return new Promise((resolve15, reject) => { + if (extract2.destroyed) return resolve15({ value: void 0, done: true }); extract2.once("close", function() { if (err) reject(err); - else resolve14({ value: void 0, done: true }); + else resolve15({ value: void 0, done: true }); }); }); } @@ -110363,7 +142496,7 @@ var require_extract = __commonJS({ }); // node_modules/tar-stream/constants.js -var require_constants14 = __commonJS({ +var require_constants15 = __commonJS({ "node_modules/tar-stream/constants.js"(exports2, module2) { var constants = { // just for envs without fs @@ -110385,9 +142518,9 @@ var require_constants14 = __commonJS({ // node_modules/tar-stream/pack.js var require_pack = __commonJS({ "node_modules/tar-stream/pack.js"(exports2, module2) { - var { Readable: Readable3, Writable, getStreamError } = require_streamx(); + var { Readable: Readable4, Writable, getStreamError } = require_streamx(); var b4a = require_b4a(); - var constants = require_constants14(); + var constants = require_constants15(); var headers = require_headers2(); var DMODE = 493; var FMODE = 420; @@ -110478,7 +142611,7 @@ var require_pack = __commonJS({ cb(); } }; - var Pack = class extends Readable3 { + var Pack = class extends Readable4 { constructor(opts) { super(opts); this._drain = noop3; @@ -110629,12 +142762,12 @@ var require_tar2 = __commonJS({ "node_modules/@actions/artifact/node_modules/archiver/lib/plugins/tar.js"(exports2, module2) { var zlib3 = require("zlib"); var engine2 = require_tar_stream(); - var util3 = require_archiver_utils(); + var util4 = require_archiver_utils(); var Tar2 = function(options) { if (!(this instanceof Tar2)) { return new Tar2(options); } - options = this.options = util3.defaults(options, { + options = this.options = util4.defaults(options, { gzip: false }); if (typeof options.gzipOptions !== "object") { @@ -110675,7 +142808,7 @@ var require_tar2 = __commonJS({ }); source.pipe(entry); } else if (data.sourceType === "stream") { - util3.collectStream(source, append); + util4.collectStream(source, append); } }; Tar2.prototype.finalize = function() { @@ -110703,7 +142836,7 @@ var require_tar2 = __commonJS({ }); // node_modules/buffer-crc32/dist/index.cjs -var require_dist6 = __commonJS({ +var require_dist5 = __commonJS({ "node_modules/buffer-crc32/dist/index.cjs"(exports2, module2) { "use strict"; function getDefaultExportFromCjs(x) { @@ -110980,9 +143113,9 @@ var require_dist6 = __commonJS({ } } function bufferizeInt2(num) { - const tmp = ensureBuffer2(4); - tmp.writeInt32BE(num, 0); - return tmp; + const tmp2 = ensureBuffer2(4); + tmp2.writeInt32BE(num, 0); + return tmp2; } function _crc322(buf, previous) { buf = ensureBuffer2(buf); @@ -111015,13 +143148,13 @@ var require_json = __commonJS({ "node_modules/@actions/artifact/node_modules/archiver/lib/plugins/json.js"(exports2, module2) { var inherits = require("util").inherits; var Transform5 = require_ours().Transform; - var crc325 = require_dist6(); - var util3 = require_archiver_utils(); + var crc325 = require_dist5(); + var util4 = require_archiver_utils(); var Json2 = function(options) { if (!(this instanceof Json2)) { return new Json2(options); } - options = this.options = util3.defaults(options, {}); + options = this.options = util4.defaults(options, {}); Transform5.call(this, options); this.supports = { directory: true, @@ -111053,7 +143186,7 @@ var require_json = __commonJS({ if (data.sourceType === "buffer") { onend(null, source); } else if (data.sourceType === "stream") { - util3.collectStream(source, onend); + util4.collectStream(source, onend); } }; Json2.prototype.finalize = function() { @@ -111074,10 +143207,10 @@ var require_archiver = __commonJS({ }; vending.create = function(format, options) { if (formats[format]) { - var instance = new Archiver2(format, options); - instance.setFormat(format); - instance.setModule(new formats[format](options)); - return instance; + var instance8 = new Archiver2(format, options); + instance8.setFormat(format); + instance8.setModule(new formats[format](options)); + return instance8; } else { throw new Error("create(" + format + "): format not registered"); } @@ -111140,11 +143273,11 @@ var require_zip2 = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -111160,7 +143293,7 @@ var require_zip2 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -111170,7 +143303,7 @@ var require_zip2 = __commonJS({ var stream2 = __importStar2(require("stream")); var promises_1 = require("fs/promises"); var archiver = __importStar2(require_archiver()); - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); var config_1 = require_config2(); exports2.DEFAULT_COMPRESSION_LEVEL = 6; var ZipUploadStream = class extends stream2.Transform { @@ -111187,7 +143320,7 @@ var require_zip2 = __commonJS({ exports2.ZipUploadStream = ZipUploadStream; function createZipUploadStream(uploadSpecification_1) { return __awaiter2(this, arguments, void 0, function* (uploadSpecification, compressionLevel = exports2.DEFAULT_COMPRESSION_LEVEL) { - core31.debug(`Creating Artifact archive with compressionLevel: ${compressionLevel}`); + core29.debug(`Creating Artifact archive with compressionLevel: ${compressionLevel}`); const zip = archiver.create("zip", { highWaterMark: (0, config_1.getUploadChunkSize)(), zlib: { level: compressionLevel } @@ -111211,8 +143344,8 @@ var require_zip2 = __commonJS({ } const bufferSize = (0, config_1.getUploadChunkSize)(); const zipUploadStream = new ZipUploadStream(bufferSize); - core31.debug(`Zip write high watermark value ${zipUploadStream.writableHighWaterMark}`); - core31.debug(`Zip read high watermark value ${zipUploadStream.readableHighWaterMark}`); + core29.debug(`Zip write high watermark value ${zipUploadStream.writableHighWaterMark}`); + core29.debug(`Zip read high watermark value ${zipUploadStream.readableHighWaterMark}`); zip.pipe(zipUploadStream); zip.finalize(); return zipUploadStream; @@ -111220,24 +143353,24 @@ var require_zip2 = __commonJS({ } exports2.createZipUploadStream = createZipUploadStream; var zipErrorCallback = (error3) => { - core31.error("An error has occurred while creating the zip file for upload"); - core31.info(error3); + core29.error("An error has occurred while creating the zip file for upload"); + core29.info(error3); throw new Error("An error has occurred during zip creation for the artifact"); }; var zipWarningCallback = (error3) => { if (error3.code === "ENOENT") { - core31.warning("ENOENT warning during artifact zip creation. No such file or directory"); - core31.info(error3); + core29.warning("ENOENT warning during artifact zip creation. No such file or directory"); + core29.info(error3); } else { - core31.warning(`A non-blocking warning has occurred during artifact zip creation: ${error3.code}`); - core31.info(error3); + core29.warning(`A non-blocking warning has occurred during artifact zip creation: ${error3.code}`); + core29.info(error3); } }; var zipFinishCallback = () => { - core31.debug("Zip stream for upload has finished."); + core29.debug("Zip stream for upload has finished."); }; var zipEndCallback = () => { - core31.debug("Zip stream for upload has ended."); + core29.debug("Zip stream for upload has ended."); }; } }); @@ -111275,11 +143408,11 @@ var require_upload_artifact = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -111295,19 +143428,19 @@ var require_upload_artifact = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.uploadArtifact = void 0; - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); var retention_1 = require_retention(); var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation(); var artifact_twirp_client_1 = require_artifact_twirp_client2(); var upload_zip_specification_1 = require_upload_zip_specification(); - var util_1 = require_util11(); + var util_1 = require_util9(); var blob_upload_1 = require_blob_upload(); var zip_1 = require_zip2(); var generated_1 = require_generated(); @@ -111349,13 +143482,13 @@ var require_upload_artifact = __commonJS({ value: `sha256:${uploadResult.sha256Hash}` }); } - core31.info(`Finalizing artifact upload`); + core29.info(`Finalizing artifact upload`); const finalizeArtifactResp = yield artifactClient.FinalizeArtifact(finalizeArtifactReq); if (!finalizeArtifactResp.ok) { throw new errors_1.InvalidResponseError("FinalizeArtifact: response from backend was not ok"); } const artifactId = BigInt(finalizeArtifactResp.artifactId); - core31.info(`Artifact ${name}.zip successfully finalized. Artifact ID ${artifactId}`); + core29.info(`Artifact ${name}.zip successfully finalized. Artifact ID ${artifactId}`); return { size: uploadResult.uploadSize, digest: uploadResult.sha256Hash, @@ -111380,7 +143513,7 @@ var require_context2 = __commonJS({ * Hydrate the context from the environment */ constructor() { - var _a2, _b, _c; + var _a6, _b2, _c2; this.payload = {}; if (process.env.GITHUB_EVENT_PATH) { if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { @@ -111400,9 +143533,9 @@ var require_context2 = __commonJS({ this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10); this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); - this.apiUrl = (_a2 = process.env.GITHUB_API_URL) !== null && _a2 !== void 0 ? _a2 : `https://api.github.com`; - this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; - this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; + this.apiUrl = (_a6 = process.env.GITHUB_API_URL) !== null && _a6 !== void 0 ? _a6 : `https://api.github.com`; + this.serverUrl = (_b2 = process.env.GITHUB_SERVER_URL) !== null && _b2 !== void 0 ? _b2 : `https://github.com`; + this.graphqlUrl = (_c2 = process.env.GITHUB_GRAPHQL_URL) !== null && _c2 !== void 0 ? _c2 : `https://api.github.com/graphql`; } get issue() { const payload = this.payload; @@ -111447,7 +143580,7 @@ var require_proxy2 = __commonJS({ if (proxyVar) { try { return new DecodedURL(proxyVar); - } catch (_a2) { + } catch (_a6) { if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) return new DecodedURL(`http://${proxyVar}`); } @@ -111541,11 +143674,11 @@ var require_lib4 = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -111561,7 +143694,7 @@ var require_lib4 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -111647,26 +143780,26 @@ var require_lib4 = __commonJS({ } readBody() { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14) => __awaiter2(this, void 0, void 0, function* () { + return new Promise((resolve15) => __awaiter2(this, void 0, void 0, function* () { let output = Buffer.alloc(0); this.message.on("data", (chunk) => { output = Buffer.concat([output, chunk]); }); this.message.on("end", () => { - resolve14(output.toString()); + resolve15(output.toString()); }); })); }); } readBodyBuffer() { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14) => __awaiter2(this, void 0, void 0, function* () { + return new Promise((resolve15) => __awaiter2(this, void 0, void 0, function* () { const chunks = []; this.message.on("data", (chunk) => { chunks.push(chunk); }); this.message.on("end", () => { - resolve14(Buffer.concat(chunks)); + resolve15(Buffer.concat(chunks)); }); })); }); @@ -111875,14 +144008,14 @@ var require_lib4 = __commonJS({ */ requestRaw(info8, data) { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { function callbackForResult(err, res) { if (err) { reject(err); } else if (!res) { reject(new Error("Unknown error")); } else { - resolve14(res); + resolve15(res); } } this.requestRawWithCallback(info8, data, callbackForResult); @@ -112064,12 +144197,12 @@ var require_lib4 = __commonJS({ return __awaiter2(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise((resolve14) => setTimeout(() => resolve14(), ms)); + return new Promise((resolve15) => setTimeout(() => resolve15(), ms)); }); } _processResponse(res, options) { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14, reject) => __awaiter2(this, void 0, void 0, function* () { + return new Promise((resolve15, reject) => __awaiter2(this, void 0, void 0, function* () { const statusCode = res.message.statusCode || 0; const response = { statusCode, @@ -112077,7 +144210,7 @@ var require_lib4 = __commonJS({ headers: {} }; if (statusCode === HttpCodes.NotFound) { - resolve14(response); + resolve15(response); } function dateTimeDeserializer(key, value) { if (typeof value === "string") { @@ -112116,7 +144249,7 @@ var require_lib4 = __commonJS({ err.result = response.result; reject(err); } else { - resolve14(response); + resolve15(response); } })); }); @@ -112128,7 +144261,7 @@ var require_lib4 = __commonJS({ }); // node_modules/@actions/artifact/node_modules/@actions/github/lib/internal/utils.js -var require_utils8 = __commonJS({ +var require_utils9 = __commonJS({ "node_modules/@actions/artifact/node_modules/@actions/github/lib/internal/utils.js"(exports2) { "use strict"; var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { @@ -112160,11 +144293,11 @@ var require_utils8 = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -112180,7 +144313,7 @@ var require_utils8 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -112574,23 +144707,23 @@ var require_dist_node2 = __commonJS({ }); } } else { - const tmp = []; + const tmp2 = []; if (Array.isArray(value)) { value.filter(isDefined3).forEach(function(value2) { - tmp.push(encodeValue2(operator, value2)); + tmp2.push(encodeValue2(operator, value2)); }); } else { Object.keys(value).forEach(function(k) { if (isDefined3(value[k])) { - tmp.push(encodeUnreserved2(k)); - tmp.push(encodeValue2(operator, value[k].toString())); + tmp2.push(encodeUnreserved2(k)); + tmp2.push(encodeValue2(operator, value[k].toString())); } }); } if (isKeyOperator2(operator)) { - result.push(encodeUnreserved2(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); + result.push(encodeUnreserved2(key) + "=" + tmp2.join(",")); + } else if (tmp2.length !== 0) { + result.push(tmp2.join(",")); } } } @@ -112625,8 +144758,8 @@ var require_dist_node2 = __commonJS({ expression = expression.substr(1); } expression.split(/,/g).forEach(function(variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues2(context5, operator, tmp[1], tmp[2] || tmp[3])); + var tmp2 = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues2(context5, operator, tmp2[1], tmp2[2] || tmp2[3])); }); if (operator && operator !== "+") { var separator = ","; @@ -112650,7 +144783,7 @@ var require_dist_node2 = __commonJS({ return template.replace(/\/$/, ""); } } - function parse3(options) { + function parse4(options) { let method = options.method.toUpperCase(); let url2 = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); let headers = Object.assign({}, options.headers); @@ -112714,7 +144847,7 @@ var require_dist_node2 = __commonJS({ ); } function endpointWithDefaults2(defaults3, route, options) { - return parse3(merge2(defaults3, route, options)); + return parse4(merge2(defaults3, route, options)); } function withDefaults4(oldDefaults, newDefaults) { const DEFAULTS22 = merge2(oldDefaults, newDefaults); @@ -112723,7 +144856,7 @@ var require_dist_node2 = __commonJS({ DEFAULTS: DEFAULTS22, defaults: withDefaults4.bind(null, DEFAULTS22), merge: merge2.bind(null, DEFAULTS22), - parse: parse3 + parse: parse4 }); } var endpoint2 = withDefaults4(null, DEFAULTS2); @@ -112959,9 +145092,9 @@ var require_dist_node5 = __commonJS({ return response.arrayBuffer(); } function fetchWrapper2(requestOptions) { - var _a2, _b, _c, _d; + var _a6, _b2, _c2, _d2; const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - const parseSuccessResponseBody = ((_a2 = requestOptions.request) == null ? void 0 : _a2.parseSuccessResponseBody) !== false; + const parseSuccessResponseBody = ((_a6 = requestOptions.request) == null ? void 0 : _a6.parseSuccessResponseBody) !== false; if (isPlainObject4(requestOptions.body) || Array.isArray(requestOptions.body)) { requestOptions.body = JSON.stringify(requestOptions.body); } @@ -112969,7 +145102,7 @@ var require_dist_node5 = __commonJS({ let status; let url2; let { fetch } = globalThis; - if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + if ((_b2 = requestOptions.request) == null ? void 0 : _b2.fetch) { fetch = requestOptions.request.fetch; } if (!fetch) { @@ -112980,9 +145113,9 @@ var require_dist_node5 = __commonJS({ return fetch(requestOptions.url, { method: requestOptions.method, body: requestOptions.body, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + redirect: (_c2 = requestOptions.request) == null ? void 0 : _c2.redirect, headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.signal, + signal: (_d2 = requestOptions.request) == null ? void 0 : _d2.signal, // duplex must be set if request.body is ReadableStream or Async Iterables. // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. ...requestOptions.body && { duplex: "half" } @@ -113368,20 +145501,20 @@ var require_dist_node8 = __commonJS({ }; var consoleWarn2 = console.warn.bind(console); var consoleError2 = console.error.bind(console); - function createLogger2(logger = {}) { - if (typeof logger.debug !== "function") { - logger.debug = noop3; + function createLogger2(logger2 = {}) { + if (typeof logger2.debug !== "function") { + logger2.debug = noop3; } - if (typeof logger.info !== "function") { - logger.info = noop3; + if (typeof logger2.info !== "function") { + logger2.info = noop3; } - if (typeof logger.warn !== "function") { - logger.warn = consoleWarn2; + if (typeof logger2.warn !== "function") { + logger2.warn = consoleWarn2; } - if (typeof logger.error !== "function") { - logger.error = consoleError2; + if (typeof logger2.error !== "function") { + logger2.error = consoleError2; } - return logger; + return logger2; } var userAgentTrail2 = `octokit-core.js/${VERSION8} ${(0, import_universal_user_agent5.getUserAgent)()}`; var Octokit2 = class { @@ -116034,7 +148167,7 @@ var require_dist_node10 = __commonJS({ }); // node_modules/@actions/artifact/node_modules/@actions/github/lib/utils.js -var require_utils9 = __commonJS({ +var require_utils10 = __commonJS({ "node_modules/@actions/artifact/node_modules/@actions/github/lib/utils.js"(exports2) { "use strict"; var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { @@ -116067,7 +148200,7 @@ var require_utils9 = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getOctokitOptions = exports2.GitHub = exports2.defaults = exports2.context = void 0; var Context = __importStar2(require_context2()); - var Utils = __importStar2(require_utils8()); + var Utils = __importStar2(require_utils9()); var core_1 = require_dist_node8(); var plugin_rest_endpoint_methods_1 = require_dist_node9(); var plugin_paginate_rest_1 = require_dist_node10(); @@ -116081,7 +148214,7 @@ var require_utils9 = __commonJS({ } }; exports2.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports2.defaults); - function getOctokitOptions2(token, options) { + function getOctokitOptions(token, options) { const opts = Object.assign({}, options || {}); const auth2 = Utils.getAuthString(token, opts); if (auth2) { @@ -116089,7 +148222,7 @@ var require_utils9 = __commonJS({ } return opts; } - exports2.getOctokitOptions = getOctokitOptions2; + exports2.getOctokitOptions = getOctokitOptions; } }); @@ -116127,7 +148260,7 @@ var require_github2 = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getOctokit = exports2.context = void 0; var Context = __importStar2(require_context2()); - var utils_1 = require_utils9(); + var utils_1 = require_utils10(); exports2.context = new Context.Context(); function getOctokit(token, options, ...additionalPlugins) { const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); @@ -116955,7 +149088,7 @@ var require_binary = __commonJS({ }); return stream2; }; - exports2.parse = function parse3(buffer) { + exports2.parse = function parse4(buffer) { var self2 = words(function(bytes, cb) { return function(name) { if (offset + bytes <= buffer.length) { @@ -117089,7 +149222,7 @@ var require_binary = __commonJS({ var require_matcher_stream = __commonJS({ "node_modules/unzip-stream/lib/matcher-stream.js"(exports2, module2) { var Transform5 = require("stream").Transform; - var util3 = require("util"); + var util4 = require("util"); function MatcherStream(patternDesc, matchFn) { if (!(this instanceof MatcherStream)) { return new MatcherStream(); @@ -117103,7 +149236,7 @@ var require_matcher_stream = __commonJS({ this.bytesSoFar = 0; this.matchFn = matchFn; } - util3.inherits(MatcherStream, Transform5); + util4.inherits(MatcherStream, Transform5); MatcherStream.prototype.checkDataChunk = function(ignoreMatchZero) { var enoughData = this.data.length >= this.requiredLength; if (!enoughData) { @@ -117196,7 +149329,7 @@ var require_unzip_stream = __commonJS({ "use strict"; var binary = require_binary(); var stream2 = require("stream"); - var util3 = require("util"); + var util4 = require("util"); var zlib3 = require("zlib"); var MatcherStream = require_matcher_stream(); var Entry = require_entry(); @@ -117237,7 +149370,7 @@ var require_unzip_stream = __commonJS({ this.parsedEntity = null; this.outStreamInfo = {}; } - util3.inherits(UnzipStream, stream2.Transform); + util4.inherits(UnzipStream, stream2.Transform); UnzipStream.prototype.processDataChunk = function(chunk) { var requiredLength; switch (this.state) { @@ -117285,8 +149418,8 @@ var require_unzip_stream = __commonJS({ default: return chunk.length; } - var chunkLength = chunk.length; - if (chunkLength < requiredLength) { + var chunkLength2 = chunk.length; + if (chunkLength2 < requiredLength) { return 0; } switch (this.state) { @@ -117784,7 +149917,7 @@ var require_unzip_stream = __commonJS({ var require_parser_stream = __commonJS({ "node_modules/unzip-stream/lib/parser-stream.js"(exports2, module2) { var Transform5 = require("stream").Transform; - var util3 = require("util"); + var util4 = require("util"); var UnzipStream = require_unzip_stream(); function ParserStream(opts) { if (!(this instanceof ParserStream)) { @@ -117802,7 +149935,7 @@ var require_parser_stream = __commonJS({ self2.emit("error", error3); }); } - util3.inherits(ParserStream, Transform5); + util4.inherits(ParserStream, Transform5); ParserStream.prototype._transform = function(chunk, encoding, cb) { this.unzipStream.write(chunk, encoding, cb); }; @@ -117835,7 +149968,7 @@ var require_parser_stream = __commonJS({ var require_mkdirp = __commonJS({ "node_modules/mkdirp/index.js"(exports2, module2) { var path30 = require("path"); - var fs32 = require("fs"); + var fs34 = require("fs"); var _0777 = parseInt("0777", 8); module2.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; function mkdirP(p, opts, f, made) { @@ -117846,7 +149979,7 @@ var require_mkdirp = __commonJS({ opts = { mode: opts }; } var mode = opts.mode; - var xfs = opts.fs || fs32; + var xfs = opts.fs || fs34; if (mode === void 0) { mode = _0777; } @@ -117885,7 +150018,7 @@ var require_mkdirp = __commonJS({ opts = { mode: opts }; } var mode = opts.mode; - var xfs = opts.fs || fs32; + var xfs = opts.fs || fs34; if (mode === void 0) { mode = _0777; } @@ -117922,9 +150055,9 @@ var require_mkdirp = __commonJS({ // node_modules/unzip-stream/lib/extract.js var require_extract2 = __commonJS({ "node_modules/unzip-stream/lib/extract.js"(exports2, module2) { - var fs32 = require("fs"); + var fs34 = require("fs"); var path30 = require("path"); - var util3 = require("util"); + var util4 = require("util"); var mkdirp = require_mkdirp(); var Transform5 = require("stream").Transform; var UnzipStream = require_unzip_stream(); @@ -117943,7 +150076,7 @@ var require_extract2 = __commonJS({ self2.emit("error", error3); }); } - util3.inherits(Extract, Transform5); + util4.inherits(Extract, Transform5); Extract.prototype._transform = function(chunk, encoding, cb) { this.unzipStream.write(chunk, encoding, cb); }; @@ -117969,7 +150102,7 @@ var require_extract2 = __commonJS({ var directory = entry.isDirectory ? destPath : path30.dirname(destPath); this.unfinishedEntries++; var writeFileFn = function() { - var pipedStream = fs32.createWriteStream(destPath); + var pipedStream = fs34.createWriteStream(destPath); pipedStream.on("close", function() { self2.unfinishedEntries--; self2._notifyAwaiter(); @@ -118045,11 +150178,11 @@ var require_download_artifact = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -118065,7 +150198,7 @@ var require_download_artifact = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -118079,14 +150212,14 @@ var require_download_artifact = __commonJS({ var crypto3 = __importStar2(require("crypto")); var stream2 = __importStar2(require("stream")); var github5 = __importStar2(require_github2()); - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); var httpClient = __importStar2(require_lib()); var unzip_stream_1 = __importDefault2(require_unzip()); var user_agent_1 = require_user_agent2(); var config_1 = require_config2(); var artifact_twirp_client_1 = require_artifact_twirp_client2(); var generated_1 = require_generated(); - var util_1 = require_util11(); + var util_1 = require_util9(); var errors_1 = require_errors3(); var scrubQueryParameters = (url2) => { const parsed = new URL(url2); @@ -118115,8 +150248,8 @@ var require_download_artifact = __commonJS({ return yield streamExtractExternal(url2, directory); } catch (error3) { retryCount++; - core31.debug(`Failed to download artifact after ${retryCount} retries due to ${error3.message}. Retrying in 5 seconds...`); - yield new Promise((resolve14) => setTimeout(resolve14, 5e3)); + core29.debug(`Failed to download artifact after ${retryCount} retries due to ${error3.message}. Retrying in 5 seconds...`); + yield new Promise((resolve15) => setTimeout(resolve15, 5e3)); } } throw new Error(`Artifact download failed after ${retryCount} retries.`); @@ -118130,7 +150263,7 @@ var require_download_artifact = __commonJS({ throw new Error(`Unexpected HTTP response from blob storage: ${response.message.statusCode} ${response.message.statusMessage}`); } let sha256Digest = void 0; - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { const timerFn = () => { const timeoutError = new Error(`Blob storage chunk did not respond in ${opts.timeout}ms`); response.message.destroy(timeoutError); @@ -118145,7 +150278,7 @@ var require_download_artifact = __commonJS({ extractStream.on("data", () => { timer.refresh(); }).on("error", (error3) => { - core31.debug(`response.message: Artifact download failed: ${error3.message}`); + core29.debug(`response.message: Artifact download failed: ${error3.message}`); clearTimeout(timer); reject(error3); }).pipe(unzip_stream_1.default.Extract({ path: directory })).on("close", () => { @@ -118153,9 +150286,9 @@ var require_download_artifact = __commonJS({ if (hashStream) { hashStream.end(); sha256Digest = hashStream.read(); - core31.info(`SHA256 digest of downloaded artifact is ${sha256Digest}`); + core29.info(`SHA256 digest of downloaded artifact is ${sha256Digest}`); } - resolve14({ sha256Digest: `sha256:${sha256Digest}` }); + resolve15({ sha256Digest: `sha256:${sha256Digest}` }); }).on("error", (error3) => { reject(error3); }); @@ -118168,7 +150301,7 @@ var require_download_artifact = __commonJS({ const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path); const api = github5.getOctokit(token); let digestMismatch = false; - core31.info(`Downloading artifact '${artifactId}' from '${repositoryOwner}/${repositoryName}'`); + core29.info(`Downloading artifact '${artifactId}' from '${repositoryOwner}/${repositoryName}'`); const { headers, status } = yield api.rest.actions.downloadArtifact({ owner: repositoryOwner, repo: repositoryName, @@ -118185,16 +150318,16 @@ var require_download_artifact = __commonJS({ if (!location) { throw new Error(`Unable to redirect to artifact download url`); } - core31.info(`Redirecting to blob download url: ${scrubQueryParameters(location)}`); + core29.info(`Redirecting to blob download url: ${scrubQueryParameters(location)}`); try { - core31.info(`Starting download of artifact to: ${downloadPath}`); + core29.info(`Starting download of artifact to: ${downloadPath}`); const extractResponse = yield streamExtract(location, downloadPath); - core31.info(`Artifact download completed successfully.`); + core29.info(`Artifact download completed successfully.`); if (options === null || options === void 0 ? void 0 : options.expectedHash) { if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) { digestMismatch = true; - core31.debug(`Computed digest: ${extractResponse.sha256Digest}`); - core31.debug(`Expected digest: ${options.expectedHash}`); + core29.debug(`Computed digest: ${extractResponse.sha256Digest}`); + core29.debug(`Expected digest: ${options.expectedHash}`); } } } catch (error3) { @@ -118221,7 +150354,7 @@ var require_download_artifact = __commonJS({ Are you trying to download from a different run? Try specifying a github-token with \`actions:read\` scope.`); } if (artifacts.length > 1) { - core31.warning("Multiple artifacts found, defaulting to first."); + core29.warning("Multiple artifacts found, defaulting to first."); } const signedReq = { workflowRunBackendId: artifacts[0].workflowRunBackendId, @@ -118229,16 +150362,16 @@ Are you trying to download from a different run? Try specifying a github-token w name: artifacts[0].name }; const { signedUrl } = yield artifactClient.GetSignedArtifactURL(signedReq); - core31.info(`Redirecting to blob download url: ${scrubQueryParameters(signedUrl)}`); + core29.info(`Redirecting to blob download url: ${scrubQueryParameters(signedUrl)}`); try { - core31.info(`Starting download of artifact to: ${downloadPath}`); + core29.info(`Starting download of artifact to: ${downloadPath}`); const extractResponse = yield streamExtract(signedUrl, downloadPath); - core31.info(`Artifact download completed successfully.`); + core29.info(`Artifact download completed successfully.`); if (options === null || options === void 0 ? void 0 : options.expectedHash) { if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) { digestMismatch = true; - core31.debug(`Computed digest: ${extractResponse.sha256Digest}`); - core31.debug(`Expected digest: ${options.expectedHash}`); + core29.debug(`Computed digest: ${extractResponse.sha256Digest}`); + core29.debug(`Expected digest: ${options.expectedHash}`); } } } catch (error3) { @@ -118251,10 +150384,10 @@ Are you trying to download from a different run? Try specifying a github-token w function resolveOrCreateDirectory() { return __awaiter2(this, arguments, void 0, function* (downloadPath = (0, config_1.getGitHubWorkspaceDir)()) { if (!(yield exists(downloadPath))) { - core31.debug(`Artifact destination folder does not exist, creating: ${downloadPath}`); + core29.debug(`Artifact destination folder does not exist, creating: ${downloadPath}`); yield promises_1.default.mkdir(downloadPath, { recursive: true }); } else { - core31.debug(`Artifact destination folder already exists: ${downloadPath}`); + core29.debug(`Artifact destination folder already exists: ${downloadPath}`); } return downloadPath; }); @@ -118295,11 +150428,11 @@ var require_retry_options = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getRetryOptions = void 0; - var core31 = __importStar2(require_core()); + var core29 = __importStar2(require_core()); var defaultMaxRetryNumber = 5; var defaultExemptStatusCodes = [400, 401, 403, 404, 422]; function getRetryOptions(defaultOptions, retries = defaultMaxRetryNumber, exemptStatusCodes = defaultExemptStatusCodes) { - var _a2; + var _a6; if (retries <= 0) { return [{ enabled: false }, defaultOptions.request]; } @@ -118310,7 +150443,7 @@ var require_retry_options = __commonJS({ retryOptions.doNotRetry = exemptStatusCodes; } const requestOptions = Object.assign(Object.assign({}, defaultOptions.request), { retries }); - core31.debug(`GitHub client configured with: (retries: ${requestOptions.retries}, retry-exempt-status-code: ${(_a2 = retryOptions.doNotRetry) !== null && _a2 !== void 0 ? _a2 : "octokit default: [400, 401, 403, 404, 422]"})`); + core29.debug(`GitHub client configured with: (retries: ${requestOptions.retries}, retry-exempt-status-code: ${(_a6 = retryOptions.doNotRetry) !== null && _a6 !== void 0 ? _a6 : "octokit default: [400, 401, 403, 404, 422]"})`); return [retryOptions, requestOptions]; } exports2.getRetryOptions = getRetryOptions; @@ -118438,11 +150571,11 @@ var require_get_artifact = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -118458,7 +150591,7 @@ var require_get_artifact = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -118467,18 +150600,18 @@ var require_get_artifact = __commonJS({ exports2.getArtifactInternal = exports2.getArtifactPublic = void 0; var github_1 = require_github2(); var plugin_retry_1 = require_dist_node12(); - var core31 = __importStar2(require_core()); - var utils_1 = require_utils9(); + var core29 = __importStar2(require_core()); + var utils_1 = require_utils10(); var retry_options_1 = require_retry_options(); var plugin_request_log_1 = require_dist_node11(); - var util_1 = require_util11(); + var util_1 = require_util9(); var user_agent_1 = require_user_agent2(); var artifact_twirp_client_1 = require_artifact_twirp_client2(); var generated_1 = require_generated(); var errors_1 = require_errors3(); function getArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { return __awaiter2(this, void 0, void 0, function* () { - var _a2; + var _a6; const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); const opts = { log: void 0, @@ -118495,7 +150628,7 @@ var require_get_artifact = __commonJS({ name: artifactName }); if (getArtifactResp.status !== 200) { - throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${getArtifactResp.status} (${(_a2 = getArtifactResp === null || getArtifactResp === void 0 ? void 0 : getArtifactResp.headers) === null || _a2 === void 0 ? void 0 : _a2["x-github-request-id"]})`); + throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${getArtifactResp.status} (${(_a6 = getArtifactResp === null || getArtifactResp === void 0 ? void 0 : getArtifactResp.headers) === null || _a6 === void 0 ? void 0 : _a6["x-github-request-id"]})`); } if (getArtifactResp.data.artifacts.length === 0) { throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName} @@ -118505,7 +150638,7 @@ var require_get_artifact = __commonJS({ let artifact2 = getArtifactResp.data.artifacts[0]; if (getArtifactResp.data.artifacts.length > 1) { artifact2 = getArtifactResp.data.artifacts.sort((a, b) => b.id - a.id)[0]; - core31.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.id})`); + core29.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.id})`); } return { artifact: { @@ -118521,7 +150654,7 @@ var require_get_artifact = __commonJS({ exports2.getArtifactPublic = getArtifactPublic; function getArtifactInternal(artifactName) { return __awaiter2(this, void 0, void 0, function* () { - var _a2; + var _a6; const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); const req = { @@ -118538,7 +150671,7 @@ var require_get_artifact = __commonJS({ let artifact2 = res.artifacts[0]; if (res.artifacts.length > 1) { artifact2 = res.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; - core31.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`); + core29.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`); } return { artifact: { @@ -118546,7 +150679,7 @@ var require_get_artifact = __commonJS({ id: Number(artifact2.databaseId), size: Number(artifact2.size), createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0, - digest: (_a2 = artifact2.digest) === null || _a2 === void 0 ? void 0 : _a2.value + digest: (_a6 = artifact2.digest) === null || _a6 === void 0 ? void 0 : _a6.value } }; }); @@ -118561,11 +150694,11 @@ var require_delete_artifact = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -118581,7 +150714,7 @@ var require_delete_artifact = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -118592,17 +150725,17 @@ var require_delete_artifact = __commonJS({ var github_1 = require_github2(); var user_agent_1 = require_user_agent2(); var retry_options_1 = require_retry_options(); - var utils_1 = require_utils9(); + var utils_1 = require_utils10(); var plugin_request_log_1 = require_dist_node11(); var plugin_retry_1 = require_dist_node12(); var artifact_twirp_client_1 = require_artifact_twirp_client2(); - var util_1 = require_util11(); + var util_1 = require_util9(); var generated_1 = require_generated(); var get_artifact_1 = require_get_artifact(); var errors_1 = require_errors3(); function deleteArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { return __awaiter2(this, void 0, void 0, function* () { - var _a2; + var _a6; const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); const opts = { log: void 0, @@ -118619,7 +150752,7 @@ var require_delete_artifact = __commonJS({ artifact_id: getArtifactResp.artifact.id }); if (deleteArtifactResp.status !== 204) { - throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${deleteArtifactResp.status} (${(_a2 = deleteArtifactResp === null || deleteArtifactResp === void 0 ? void 0 : deleteArtifactResp.headers) === null || _a2 === void 0 ? void 0 : _a2["x-github-request-id"]})`); + throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${deleteArtifactResp.status} (${(_a6 = deleteArtifactResp === null || deleteArtifactResp === void 0 ? void 0 : deleteArtifactResp.headers) === null || _a6 === void 0 ? void 0 : _a6["x-github-request-id"]})`); } return { id: getArtifactResp.artifact.id @@ -118667,11 +150800,11 @@ var require_list_artifacts = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -118687,7 +150820,7 @@ var require_list_artifacts = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -118698,11 +150831,11 @@ var require_list_artifacts = __commonJS({ var github_1 = require_github2(); var user_agent_1 = require_user_agent2(); var retry_options_1 = require_retry_options(); - var utils_1 = require_utils9(); + var utils_1 = require_utils10(); var plugin_request_log_1 = require_dist_node11(); var plugin_retry_1 = require_dist_node12(); var artifact_twirp_client_1 = require_artifact_twirp_client2(); - var util_1 = require_util11(); + var util_1 = require_util9(); var config_1 = require_config2(); var generated_1 = require_generated(); var maximumArtifactCount = (0, config_1.getMaxArtifactListCount)(); @@ -118784,13 +150917,13 @@ var require_list_artifacts = __commonJS({ }; const res = yield artifactClient.ListArtifacts(req); let artifacts = res.artifacts.map((artifact2) => { - var _a2; + var _a6; return { name: artifact2.name, id: Number(artifact2.databaseId), size: Number(artifact2.size), createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0, - digest: (_a2 = artifact2.digest) === null || _a2 === void 0 ? void 0 : _a2.value + digest: (_a6 = artifact2.digest) === null || _a6 === void 0 ? void 0 : _a6.value }; }); if (latest) { @@ -118824,11 +150957,11 @@ var require_client2 = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -118844,7 +150977,7 @@ var require_client2 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -119016,7 +151149,7 @@ var require_artifact2 = __commonJS({ }); // node_modules/@actions/artifact-legacy/node_modules/@actions/core/lib/utils.js -var require_utils10 = __commonJS({ +var require_utils11 = __commonJS({ "node_modules/@actions/artifact-legacy/node_modules/@actions/core/lib/utils.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); @@ -119080,11 +151213,11 @@ var require_command2 = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.issue = exports2.issueCommand = void 0; - var os7 = __importStar2(require("os")); - var utils_1 = require_utils10(); + var os8 = __importStar2(require("os")); + var utils_1 = require_utils11(); function issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os7.EOL); + process.stdout.write(cmd.toString() + os8.EOL); } exports2.issueCommand = issueCommand; function issue(name, message = "") { @@ -119167,18 +151300,18 @@ var require_file_command2 = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.prepareKeyValueMessage = exports2.issueFileCommand = void 0; var crypto3 = __importStar2(require("crypto")); - var fs32 = __importStar2(require("fs")); - var os7 = __importStar2(require("os")); - var utils_1 = require_utils10(); + var fs34 = __importStar2(require("fs")); + var os8 = __importStar2(require("os")); + var utils_1 = require_utils11(); function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); } - if (!fs32.existsSync(filePath)) { + if (!fs34.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } - fs32.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os7.EOL}`, { + fs34.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os8.EOL}`, { encoding: "utf8" }); } @@ -119192,7 +151325,7 @@ var require_file_command2 = __commonJS({ if (convertedValue.includes(delimiter)) { throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); } - return `${key}<<${delimiter}${os7.EOL}${convertedValue}${os7.EOL}${delimiter}`; + return `${key}<<${delimiter}${os8.EOL}${convertedValue}${os8.EOL}${delimiter}`; } exports2.prepareKeyValueMessage = prepareKeyValueMessage; } @@ -119219,7 +151352,7 @@ var require_proxy3 = __commonJS({ if (proxyVar) { try { return new DecodedURL(proxyVar); - } catch (_a2) { + } catch (_a6) { if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) return new DecodedURL(`http://${proxyVar}`); } @@ -119313,11 +151446,11 @@ var require_lib5 = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -119333,7 +151466,7 @@ var require_lib5 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -119419,26 +151552,26 @@ var require_lib5 = __commonJS({ } readBody() { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14) => __awaiter2(this, void 0, void 0, function* () { + return new Promise((resolve15) => __awaiter2(this, void 0, void 0, function* () { let output = Buffer.alloc(0); this.message.on("data", (chunk) => { output = Buffer.concat([output, chunk]); }); this.message.on("end", () => { - resolve14(output.toString()); + resolve15(output.toString()); }); })); }); } readBodyBuffer() { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14) => __awaiter2(this, void 0, void 0, function* () { + return new Promise((resolve15) => __awaiter2(this, void 0, void 0, function* () { const chunks = []; this.message.on("data", (chunk) => { chunks.push(chunk); }); this.message.on("end", () => { - resolve14(Buffer.concat(chunks)); + resolve15(Buffer.concat(chunks)); }); })); }); @@ -119647,14 +151780,14 @@ var require_lib5 = __commonJS({ */ requestRaw(info8, data) { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { function callbackForResult(err, res) { if (err) { reject(err); } else if (!res) { reject(new Error("Unknown error")); } else { - resolve14(res); + resolve15(res); } } this.requestRawWithCallback(info8, data, callbackForResult); @@ -119836,12 +151969,12 @@ var require_lib5 = __commonJS({ return __awaiter2(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise((resolve14) => setTimeout(() => resolve14(), ms)); + return new Promise((resolve15) => setTimeout(() => resolve15(), ms)); }); } _processResponse(res, options) { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14, reject) => __awaiter2(this, void 0, void 0, function* () { + return new Promise((resolve15, reject) => __awaiter2(this, void 0, void 0, function* () { const statusCode = res.message.statusCode || 0; const response = { statusCode, @@ -119849,7 +151982,7 @@ var require_lib5 = __commonJS({ headers: {} }; if (statusCode === HttpCodes.NotFound) { - resolve14(response); + resolve15(response); } function dateTimeDeserializer(key, value) { if (typeof value === "string") { @@ -119888,7 +152021,7 @@ var require_lib5 = __commonJS({ err.result = response.result; reject(err); } else { - resolve14(response); + resolve15(response); } })); }); @@ -119905,11 +152038,11 @@ var require_auth2 = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -119925,7 +152058,7 @@ var require_auth2 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -120009,11 +152142,11 @@ var require_oidc_utils2 = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -120029,7 +152162,7 @@ var require_oidc_utils2 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -120062,7 +152195,7 @@ var require_oidc_utils2 = __commonJS({ return runtimeUrl; } static getCall(id_token_url) { - var _a2; + var _a6; return __awaiter2(this, void 0, void 0, function* () { const httpclient = _OidcClient.createHttpClient(); const res = yield httpclient.getJson(id_token_url).catch((error3) => { @@ -120072,7 +152205,7 @@ var require_oidc_utils2 = __commonJS({ Error Message: ${error3.message}`); }); - const id_token = (_a2 = res.result) === null || _a2 === void 0 ? void 0 : _a2.value; + const id_token = (_a6 = res.result) === null || _a6 === void 0 ? void 0 : _a6.value; if (!id_token) { throw new Error("Response json body do not have ID Token field"); } @@ -120107,11 +152240,11 @@ var require_summary2 = __commonJS({ "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -120127,7 +152260,7 @@ var require_summary2 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -120160,7 +152293,7 @@ var require_summary2 = __commonJS({ } try { yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); - } catch (_a2) { + } catch (_a6) { throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); } this._filePath = pathFromEnv; @@ -120473,11 +152606,11 @@ var require_io_util2 = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -120493,20 +152626,20 @@ var require_io_util2 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var _a2; + var _a6; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getCmdPath = exports2.tryGetExecutablePath = exports2.isRooted = exports2.isDirectory = exports2.exists = exports2.READONLY = exports2.UV_FS_O_EXLOCK = exports2.IS_WINDOWS = exports2.unlink = exports2.symlink = exports2.stat = exports2.rmdir = exports2.rm = exports2.rename = exports2.readlink = exports2.readdir = exports2.open = exports2.mkdir = exports2.lstat = exports2.copyFile = exports2.chmod = void 0; - var fs32 = __importStar2(require("fs")); + var fs34 = __importStar2(require("fs")); var path30 = __importStar2(require("path")); - _a2 = fs32.promises, exports2.chmod = _a2.chmod, exports2.copyFile = _a2.copyFile, exports2.lstat = _a2.lstat, exports2.mkdir = _a2.mkdir, exports2.open = _a2.open, exports2.readdir = _a2.readdir, exports2.readlink = _a2.readlink, exports2.rename = _a2.rename, exports2.rm = _a2.rm, exports2.rmdir = _a2.rmdir, exports2.stat = _a2.stat, exports2.symlink = _a2.symlink, exports2.unlink = _a2.unlink; + _a6 = fs34.promises, exports2.chmod = _a6.chmod, exports2.copyFile = _a6.copyFile, exports2.lstat = _a6.lstat, exports2.mkdir = _a6.mkdir, exports2.open = _a6.open, exports2.readdir = _a6.readdir, exports2.readlink = _a6.readlink, exports2.rename = _a6.rename, exports2.rm = _a6.rm, exports2.rmdir = _a6.rmdir, exports2.stat = _a6.stat, exports2.symlink = _a6.symlink, exports2.unlink = _a6.unlink; exports2.IS_WINDOWS = process.platform === "win32"; exports2.UV_FS_O_EXLOCK = 268435456; - exports2.READONLY = fs32.constants.O_RDONLY; + exports2.READONLY = fs34.constants.O_RDONLY; function exists(fsPath) { return __awaiter2(this, void 0, void 0, function* () { try { @@ -120610,8 +152743,8 @@ var require_io_util2 = __commonJS({ return (stats.mode & 1) > 0 || (stats.mode & 8) > 0 && stats.gid === process.getgid() || (stats.mode & 64) > 0 && stats.uid === process.getuid(); } function getCmdPath() { - var _a3; - return (_a3 = process.env["COMSPEC"]) !== null && _a3 !== void 0 ? _a3 : `cmd.exe`; + var _a7; + return (_a7 = process.env["COMSPEC"]) !== null && _a7 !== void 0 ? _a7 : `cmd.exe`; } exports2.getCmdPath = getCmdPath; } @@ -120646,11 +152779,11 @@ var require_io2 = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -120666,7 +152799,7 @@ var require_io2 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -120751,13 +152884,13 @@ var require_io2 = __commonJS({ }); } exports2.mkdirP = mkdirP; - function which9(tool, check) { + function which10(tool, check) { return __awaiter2(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } if (check) { - const result = yield which9(tool, false); + const result = yield which10(tool, false); if (!result) { if (ioUtil.IS_WINDOWS) { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); @@ -120774,7 +152907,7 @@ var require_io2 = __commonJS({ return ""; }); } - exports2.which = which9; + exports2.which = which10; function findInPath(tool) { return __awaiter2(this, void 0, void 0, function* () { if (!tool) { @@ -120894,11 +153027,11 @@ var require_toolrunner2 = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -120914,22 +153047,22 @@ var require_toolrunner2 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.argStringToArray = exports2.ToolRunner = void 0; - var os7 = __importStar2(require("os")); + var os8 = __importStar2(require("os")); var events = __importStar2(require("events")); var child = __importStar2(require("child_process")); var path30 = __importStar2(require("path")); - var io9 = __importStar2(require_io2()); + var io10 = __importStar2(require_io2()); var ioUtil = __importStar2(require_io_util2()); var timers_1 = require("timers"); var IS_WINDOWS = process.platform === "win32"; - var ToolRunner7 = class extends events.EventEmitter { + var ToolRunner8 = class extends events.EventEmitter { constructor(toolPath, args, options) { super(); if (!toolPath) { @@ -120976,12 +153109,12 @@ var require_toolrunner2 = __commonJS({ _processLineBuffer(data, strBuffer, onLine) { try { let s = strBuffer + data.toString(); - let n = s.indexOf(os7.EOL); + let n = s.indexOf(os8.EOL); while (n > -1) { const line = s.substring(0, n); onLine(line); - s = s.substring(n + os7.EOL.length); - n = s.indexOf(os7.EOL); + s = s.substring(n + os8.EOL.length); + n = s.indexOf(os8.EOL); } return s; } catch (err) { @@ -121141,8 +153274,8 @@ var require_toolrunner2 = __commonJS({ if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes("/") || IS_WINDOWS && this.toolPath.includes("\\"))) { this.toolPath = path30.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } - this.toolPath = yield io9.which(this.toolPath, true); - return new Promise((resolve14, reject) => __awaiter2(this, void 0, void 0, function* () { + this.toolPath = yield io10.which(this.toolPath, true); + return new Promise((resolve15, reject) => __awaiter2(this, void 0, void 0, function* () { this._debug(`exec tool: ${this.toolPath}`); this._debug("arguments:"); for (const arg of this.args) { @@ -121150,7 +153283,7 @@ var require_toolrunner2 = __commonJS({ } const optionsNonNull = this._cloneExecOptions(this.options); if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os7.EOL); + optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os8.EOL); } const state = new ExecState(optionsNonNull, this.toolPath); state.on("debug", (message) => { @@ -121225,7 +153358,7 @@ var require_toolrunner2 = __commonJS({ if (error3) { reject(error3); } else { - resolve14(exitCode); + resolve15(exitCode); } }); if (this.options.input) { @@ -121238,7 +153371,7 @@ var require_toolrunner2 = __commonJS({ }); } }; - exports2.ToolRunner = ToolRunner7; + exports2.ToolRunner = ToolRunner8; function argStringToArray(argString) { const args = []; let inQuotes = false; @@ -121378,11 +153511,11 @@ var require_exec2 = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -121398,7 +153531,7 @@ var require_exec2 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -121421,14 +153554,14 @@ var require_exec2 = __commonJS({ } exports2.exec = exec3; function getExecOutput(commandLine, args, options) { - var _a2, _b; + var _a6, _b2; return __awaiter2(this, void 0, void 0, function* () { let stdout = ""; let stderr = ""; const stdoutDecoder = new string_decoder_1.StringDecoder("utf8"); const stderrDecoder = new string_decoder_1.StringDecoder("utf8"); - const originalStdoutListener = (_a2 = options === null || options === void 0 ? void 0 : options.listeners) === null || _a2 === void 0 ? void 0 : _a2.stdout; - const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; + const originalStdoutListener = (_a6 = options === null || options === void 0 ? void 0 : options.listeners) === null || _a6 === void 0 ? void 0 : _a6.stdout; + const originalStdErrListener = (_b2 = options === null || options === void 0 ? void 0 : options.listeners) === null || _b2 === void 0 ? void 0 : _b2.stderr; const stdErrListener = (data) => { stderr += stderrDecoder.write(data); if (originalStdErrListener) { @@ -121489,11 +153622,11 @@ var require_platform2 = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -121509,7 +153642,7 @@ var require_platform2 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -121534,12 +153667,12 @@ var require_platform2 = __commonJS({ }; }); var getMacOsInfo = () => __awaiter2(void 0, void 0, void 0, function* () { - var _a2, _b, _c, _d; + var _a6, _b2, _c2, _d2; const { stdout } = yield exec3.getExecOutput("sw_vers", void 0, { silent: true }); - const version = (_b = (_a2 = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a2 === void 0 ? void 0 : _a2[1]) !== null && _b !== void 0 ? _b : ""; - const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ""; + const version = (_b2 = (_a6 = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a6 === void 0 ? void 0 : _a6[1]) !== null && _b2 !== void 0 ? _b2 : ""; + const name = (_d2 = (_c2 = stdout.match(/ProductName:\s*(.+)/)) === null || _c2 === void 0 ? void 0 : _c2[1]) !== null && _d2 !== void 0 ? _d2 : ""; return { name, version @@ -121608,11 +153741,11 @@ var require_core3 = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -121628,7 +153761,7 @@ var require_core3 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -121637,8 +153770,8 @@ var require_core3 = __commonJS({ exports2.platform = exports2.toPlatformPath = exports2.toWin32Path = exports2.toPosixPath = exports2.markdownSummary = exports2.summary = exports2.getIDToken = exports2.getState = exports2.saveState = exports2.group = exports2.endGroup = exports2.startGroup = exports2.info = exports2.notice = exports2.warning = exports2.error = exports2.debug = exports2.isDebug = exports2.setFailed = exports2.setCommandEcho = exports2.setOutput = exports2.getBooleanInput = exports2.getMultilineInput = exports2.getInput = exports2.addPath = exports2.setSecret = exports2.exportVariable = exports2.ExitCode = void 0; var command_1 = require_command2(); var file_command_1 = require_file_command2(); - var utils_1 = require_utils10(); - var os7 = __importStar2(require("os")); + var utils_1 = require_utils11(); + var os8 = __importStar2(require("os")); var path30 = __importStar2(require("path")); var oidc_utils_1 = require_oidc_utils2(); var ExitCode; @@ -121646,7 +153779,7 @@ var require_core3 = __commonJS({ ExitCode2[ExitCode2["Success"] = 0] = "Success"; ExitCode2[ExitCode2["Failure"] = 1] = "Failure"; })(ExitCode || (exports2.ExitCode = ExitCode = {})); - function exportVariable16(name, val) { + function exportVariable2(name, val) { const convertedVal = (0, utils_1.toCommandValue)(val); process.env[name] = convertedVal; const filePath = process.env["GITHUB_ENV"] || ""; @@ -121655,7 +153788,7 @@ var require_core3 = __commonJS({ } (0, command_1.issueCommand)("set-env", { name }, convertedVal); } - exports2.exportVariable = exportVariable16; + exports2.exportVariable = exportVariable2; function setSecret2(secret) { (0, command_1.issueCommand)("add-mask", {}, secret); } @@ -121706,7 +153839,7 @@ Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); if (filePath) { return (0, file_command_1.issueFileCommand)("OUTPUT", (0, file_command_1.prepareKeyValueMessage)(name, value)); } - process.stdout.write(os7.EOL); + process.stdout.write(os8.EOL); (0, command_1.issueCommand)("set-output", { name }, (0, utils_1.toCommandValue)(value)); } exports2.setOutput = setOutput7; @@ -121740,25 +153873,25 @@ Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); } exports2.notice = notice; function info8(message) { - process.stdout.write(message + os7.EOL); + process.stdout.write(message + os8.EOL); } exports2.info = info8; - function startGroup4(name) { + function startGroup3(name) { (0, command_1.issue)("group", name); } - exports2.startGroup = startGroup4; - function endGroup4() { + exports2.startGroup = startGroup3; + function endGroup3() { (0, command_1.issue)("endgroup"); } - exports2.endGroup = endGroup4; + exports2.endGroup = endGroup3; function group(name, fn) { return __awaiter2(this, void 0, void 0, function* () { - startGroup4(name); + startGroup3(name); let result; try { result = yield fn(); } finally { - endGroup4(); + endGroup3(); } return result; }); @@ -121895,25 +154028,25 @@ var require_upload_specification = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getUploadSpecification = void 0; - var fs32 = __importStar2(require("fs")); + var fs34 = __importStar2(require("fs")); var core_1 = require_core3(); var path_1 = require("path"); var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2(); function getUploadSpecification(artifactName, rootDirectory, artifactFiles) { const specifications = []; - if (!fs32.existsSync(rootDirectory)) { + if (!fs34.existsSync(rootDirectory)) { throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`); } - if (!fs32.statSync(rootDirectory).isDirectory()) { + if (!fs34.statSync(rootDirectory).isDirectory()) { throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`); } rootDirectory = (0, path_1.normalize)(rootDirectory); rootDirectory = (0, path_1.resolve)(rootDirectory); for (let file of artifactFiles) { - if (!fs32.existsSync(file)) { + if (!fs34.existsSync(file)) { throw new Error(`File ${file} does not exist`); } - if (!fs32.statSync(file).isDirectory()) { + if (!fs34.statSync(file).isDirectory()) { file = (0, path_1.normalize)(file); file = (0, path_1.resolve)(file); if (!file.startsWith(rootDirectory)) { @@ -121938,29 +154071,29 @@ var require_upload_specification = __commonJS({ // node_modules/tmp/lib/tmp.js var require_tmp = __commonJS({ "node_modules/tmp/lib/tmp.js"(exports2, module2) { - var fs32 = require("fs"); - var os7 = require("os"); + var fs34 = require("fs"); + var os8 = require("os"); var path30 = require("path"); var crypto3 = require("crypto"); - var _c = { fs: fs32.constants, os: os7.constants }; + var _c2 = { fs: fs34.constants, os: os8.constants }; var RANDOM_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; var TEMPLATE_PATTERN = /XXXXXX/; var DEFAULT_TRIES = 3; - var CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR); - var IS_WIN32 = os7.platform() === "win32"; - var EBADF = _c.EBADF || _c.os.errno.EBADF; - var ENOENT = _c.ENOENT || _c.os.errno.ENOENT; + var CREATE_FLAGS = (_c2.O_CREAT || _c2.fs.O_CREAT) | (_c2.O_EXCL || _c2.fs.O_EXCL) | (_c2.O_RDWR || _c2.fs.O_RDWR); + var IS_WIN32 = os8.platform() === "win32"; + var EBADF = _c2.EBADF || _c2.os.errno.EBADF; + var ENOENT = _c2.ENOENT || _c2.os.errno.ENOENT; var DIR_MODE = 448; var FILE_MODE = 384; var EXIT = "exit"; var _removeObjects = []; - var FN_RMDIR_SYNC = fs32.rmdirSync.bind(fs32); + var FN_RMDIR_SYNC = fs34.rmdirSync.bind(fs34); var _gracefulCleanup = false; function rimraf(dirPath, callback) { - return fs32.rm(dirPath, { recursive: true }, callback); + return fs34.rm(dirPath, { recursive: true }, callback); } function FN_RIMRAF_SYNC(dirPath) { - return fs32.rmSync(dirPath, { recursive: true }); + return fs34.rmSync(dirPath, { recursive: true }); } function tmpName(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; @@ -121970,7 +154103,7 @@ var require_tmp = __commonJS({ (function _getUniqueName() { try { const name = _generateTmpName(sanitizedOptions); - fs32.stat(name, function(err2) { + fs34.stat(name, function(err2) { if (!err2) { if (tries-- > 0) return _getUniqueName(); return cb(new Error("Could not get a unique tmp filename, max tries reached " + name)); @@ -121990,7 +154123,7 @@ var require_tmp = __commonJS({ do { const name = _generateTmpName(sanitizedOptions); try { - fs32.statSync(name); + fs34.statSync(name); } catch (e) { return name; } @@ -122001,10 +154134,10 @@ var require_tmp = __commonJS({ const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; tmpName(opts, function _tmpNameCreated(err, name) { if (err) return cb(err); - fs32.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) { + fs34.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) { if (err2) return cb(err2); if (opts.discardDescriptor) { - return fs32.close(fd, function _discardCallback(possibleErr) { + return fs34.close(fd, function _discardCallback(possibleErr) { return cb(possibleErr, name, void 0, _prepareTmpFileRemoveCallback(name, -1, opts, false)); }); } else { @@ -122018,9 +154151,9 @@ var require_tmp = __commonJS({ const args = _parseArguments(options), opts = args[0]; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); - let fd = fs32.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); + let fd = fs34.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); if (opts.discardDescriptor) { - fs32.closeSync(fd); + fs34.closeSync(fd); fd = void 0; } return { @@ -122033,7 +154166,7 @@ var require_tmp = __commonJS({ const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; tmpName(opts, function _tmpNameCreated(err, name) { if (err) return cb(err); - fs32.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) { + fs34.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) { if (err2) return cb(err2); cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); }); @@ -122042,7 +154175,7 @@ var require_tmp = __commonJS({ function dirSync(options) { const args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); - fs32.mkdirSync(name, opts.mode || DIR_MODE); + fs34.mkdirSync(name, opts.mode || DIR_MODE); return { name, removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) @@ -122056,20 +154189,20 @@ var require_tmp = __commonJS({ next(); }; if (0 <= fdPath[0]) - fs32.close(fdPath[0], function() { - fs32.unlink(fdPath[1], _handler); + fs34.close(fdPath[0], function() { + fs34.unlink(fdPath[1], _handler); }); - else fs32.unlink(fdPath[1], _handler); + else fs34.unlink(fdPath[1], _handler); } function _removeFileSync(fdPath) { let rethrownException = null; try { - if (0 <= fdPath[0]) fs32.closeSync(fdPath[0]); + if (0 <= fdPath[0]) fs34.closeSync(fdPath[0]); } catch (e) { if (!_isEBADF(e) && !_isENOENT(e)) throw e; } finally { try { - fs32.unlinkSync(fdPath[1]); + fs34.unlinkSync(fdPath[1]); } catch (e) { if (!_isENOENT(e)) rethrownException = e; } @@ -122085,7 +154218,7 @@ var require_tmp = __commonJS({ return sync ? removeCallbackSync : removeCallback; } function _prepareTmpDirRemoveCallback(name, opts, sync) { - const removeFunction = opts.unsafeCleanup ? rimraf : fs32.rmdir.bind(fs32); + const removeFunction = opts.unsafeCleanup ? rimraf : fs34.rmdir.bind(fs34); const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); @@ -122148,24 +154281,24 @@ var require_tmp = __commonJS({ } function _resolvePath(name, tmpDir, cb) { const pathToResolve = path30.isAbsolute(name) ? name : path30.join(tmpDir, name); - fs32.stat(pathToResolve, function(err) { + fs34.stat(pathToResolve, function(err) { if (err) { - fs32.realpath(path30.dirname(pathToResolve), function(err2, parentDir) { + fs34.realpath(path30.dirname(pathToResolve), function(err2, parentDir) { if (err2) return cb(err2); cb(null, path30.join(parentDir, path30.basename(pathToResolve))); }); } else { - fs32.realpath(pathToResolve, cb); + fs34.realpath(pathToResolve, cb); } }); } function _resolvePathSync(name, tmpDir) { const pathToResolve = path30.isAbsolute(name) ? name : path30.join(tmpDir, name); try { - fs32.statSync(pathToResolve); - return fs32.realpathSync(pathToResolve); + fs34.statSync(pathToResolve); + return fs34.realpathSync(pathToResolve); } catch (_err) { - const parentDir = fs32.realpathSync(path30.dirname(pathToResolve)); + const parentDir = fs34.realpathSync(path30.dirname(pathToResolve)); return path30.join(parentDir, path30.basename(pathToResolve)); } } @@ -122286,10 +154419,10 @@ var require_tmp = __commonJS({ _gracefulCleanup = true; } function _getTmpDir(options, cb) { - return fs32.realpath(options && options.tmpdir || os7.tmpdir(), cb); + return fs34.realpath(options && options.tmpdir || os8.tmpdir(), cb); } function _getTmpDirSync(options) { - return fs32.realpathSync(options && options.tmpdir || os7.tmpdir()); + return fs34.realpathSync(options && options.tmpdir || os8.tmpdir()); } process.addListener(EXIT, _garbageCollector); Object.defineProperty(module2.exports, "tmpdir", { @@ -122314,10 +154447,10 @@ var require_tmp_promise = __commonJS({ "node_modules/tmp-promise/index.js"(exports2, module2) { "use strict"; var { promisify } = require("util"); - var tmp = require_tmp(); - module2.exports.fileSync = tmp.fileSync; + var tmp2 = require_tmp(); + module2.exports.fileSync = tmp2.fileSync; var fileWithOptions = promisify( - (options, cb) => tmp.file( + (options, cb) => tmp2.file( options, (err, path30, fd, cleanup) => err ? cb(err) : cb(void 0, { path: path30, fd, cleanup: promisify(cleanup) }) ) @@ -122331,9 +154464,9 @@ var require_tmp_promise = __commonJS({ await cleanup(); } }; - module2.exports.dirSync = tmp.dirSync; + module2.exports.dirSync = tmp2.dirSync; var dirWithOptions = promisify( - (options, cb) => tmp.dir( + (options, cb) => tmp2.dir( options, (err, path30, cleanup) => err ? cb(err) : cb(void 0, { path: path30, cleanup: promisify(cleanup) }) ) @@ -122347,10 +154480,10 @@ var require_tmp_promise = __commonJS({ await cleanup(); } }; - module2.exports.tmpNameSync = tmp.tmpNameSync; - module2.exports.tmpName = promisify(tmp.tmpName); - module2.exports.tmpdir = tmp.tmpdir; - module2.exports.setGracefulCleanup = tmp.setGracefulCleanup; + module2.exports.tmpNameSync = tmp2.tmpNameSync; + module2.exports.tmpName = promisify(tmp2.tmpName); + module2.exports.tmpdir = tmp2.tmpdir; + module2.exports.setGracefulCleanup = tmp2.setGracefulCleanup; } }); @@ -122429,7 +154562,7 @@ var require_config_variables = __commonJS({ }); // node_modules/@actions/artifact-legacy/lib/internal/crc64.js -var require_crc64 = __commonJS({ +var require_crc642 = __commonJS({ "node_modules/@actions/artifact-legacy/lib/internal/crc64.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); @@ -122726,16 +154859,16 @@ var require_crc64 = __commonJS({ }); // node_modules/@actions/artifact-legacy/lib/internal/utils.js -var require_utils11 = __commonJS({ +var require_utils12 = __commonJS({ "node_modules/@actions/artifact-legacy/lib/internal/utils.js"(exports2) { "use strict"; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -122751,7 +154884,7 @@ var require_utils11 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -122767,7 +154900,7 @@ var require_utils11 = __commonJS({ var http_client_1 = require_lib5(); var auth_1 = require_auth2(); var config_variables_1 = require_config_variables(); - var crc64_1 = __importDefault2(require_crc64()); + var crc64_1 = __importDefault2(require_crc642()); function getExponentialRetryTimeInMilliseconds(retryCount) { if (retryCount < 0) { throw new Error("RetryCount should not be negative"); @@ -122961,19 +155094,19 @@ Header Information: ${JSON.stringify(response.message.headers, void 0, 2)} exports2.getProperRetention = getProperRetention; function sleep(milliseconds) { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14) => setTimeout(resolve14, milliseconds)); + return new Promise((resolve15) => setTimeout(resolve15, milliseconds)); }); } exports2.sleep = sleep; function digestForStream(stream2) { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { const crc64 = new crc64_1.default(); const md5 = crypto_1.default.createHash("md5"); stream2.on("data", (data) => { crc64.update(data); md5.update(data); - }).on("end", () => resolve14({ + }).on("end", () => resolve15({ crc64: crc64.digest("base64"), md5: md5.digest("base64") })).on("error", reject); @@ -123036,7 +155169,7 @@ var require_http_manager = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.HttpManager = void 0; - var utils_1 = require_utils11(); + var utils_1 = require_utils12(); var HttpManager = class { constructor(clientCount, userAgent2) { if (clientCount < 1) { @@ -123097,11 +155230,11 @@ var require_upload_gzip = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -123117,7 +155250,7 @@ var require_upload_gzip = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); @@ -123130,23 +155263,23 @@ var require_upload_gzip = __commonJS({ }, i); function verb(n) { i[n] = o[n] && function(v) { - return new Promise(function(resolve14, reject) { - v = o[n](v), settle(resolve14, reject, v.done, v.value); + return new Promise(function(resolve15, reject) { + v = o[n](v), settle(resolve15, reject, v.done, v.value); }); }; } - function settle(resolve14, reject, d, v) { + function settle(resolve15, reject, d, v) { Promise.resolve(v).then(function(v2) { - resolve14({ value: v2, done: d }); + resolve15({ value: v2, done: d }); }, reject); } }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.createGZipFileInBuffer = exports2.createGZipFileOnDisk = void 0; - var fs32 = __importStar2(require("fs")); + var fs34 = __importStar2(require("fs")); var zlib3 = __importStar2(require("zlib")); var util_1 = require("util"); - var stat2 = (0, util_1.promisify)(fs32.stat); + var stat2 = (0, util_1.promisify)(fs34.stat); var gzipExemptFileExtensions = [ ".gz", ".gzip", @@ -123178,14 +155311,14 @@ var require_upload_gzip = __commonJS({ return Number.MAX_SAFE_INTEGER; } } - return new Promise((resolve14, reject) => { - const inputStream = fs32.createReadStream(originalFilePath); + return new Promise((resolve15, reject) => { + const inputStream = fs34.createReadStream(originalFilePath); const gzip = zlib3.createGzip(); - const outputStream = fs32.createWriteStream(tempFilePath); + const outputStream = fs34.createWriteStream(tempFilePath); inputStream.pipe(gzip).pipe(outputStream); outputStream.on("finish", () => __awaiter2(this, void 0, void 0, function* () { const size = (yield stat2(tempFilePath)).size; - resolve14(size); + resolve15(size); })); outputStream.on("error", (error3) => { console.log(error3); @@ -123197,33 +155330,33 @@ var require_upload_gzip = __commonJS({ exports2.createGZipFileOnDisk = createGZipFileOnDisk; function createGZipFileInBuffer(originalFilePath) { return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve14) => __awaiter2(this, void 0, void 0, function* () { - var _a2, e_1, _b, _c; - const inputStream = fs32.createReadStream(originalFilePath); + return new Promise((resolve15) => __awaiter2(this, void 0, void 0, function* () { + var _a6, e_1, _b2, _c2; + const inputStream = fs34.createReadStream(originalFilePath); const gzip = zlib3.createGzip(); inputStream.pipe(gzip); const chunks = []; try { - for (var _d = true, gzip_1 = __asyncValues2(gzip), gzip_1_1; gzip_1_1 = yield gzip_1.next(), _a2 = gzip_1_1.done, !_a2; ) { - _c = gzip_1_1.value; - _d = false; + for (var _d2 = true, gzip_1 = __asyncValues2(gzip), gzip_1_1; gzip_1_1 = yield gzip_1.next(), _a6 = gzip_1_1.done, !_a6; ) { + _c2 = gzip_1_1.value; + _d2 = false; try { - const chunk = _c; + const chunk = _c2; chunks.push(chunk); } finally { - _d = true; + _d2 = true; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { - if (!_d && !_a2 && (_b = gzip_1.return)) yield _b.call(gzip_1); + if (!_d2 && !_a6 && (_b2 = gzip_1.return)) yield _b2.call(gzip_1); } finally { if (e_1) throw e_1.error; } } - resolve14(Buffer.concat(chunks)); + resolve15(Buffer.concat(chunks)); })); }); } @@ -123264,11 +155397,11 @@ var require_requestUtils2 = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -123284,15 +155417,15 @@ var require_requestUtils2 = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.retryHttpClientRequest = exports2.retry = void 0; - var utils_1 = require_utils11(); - var core31 = __importStar2(require_core3()); + var utils_1 = require_utils12(); + var core29 = __importStar2(require_core3()); var config_variables_1 = require_config_variables(); function retry2(name, operation, customErrorMessages, maxAttempts) { return __awaiter2(this, void 0, void 0, function* () { @@ -123319,13 +155452,13 @@ var require_requestUtils2 = __commonJS({ errorMessage = error3.message; } if (!isRetryable) { - core31.info(`${name} - Error is not retryable`); + core29.info(`${name} - Error is not retryable`); if (response) { (0, utils_1.displayHttpDiagnostics)(response); } break; } - core31.info(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); + core29.info(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); yield (0, utils_1.sleep)((0, utils_1.getExponentialRetryTimeInMilliseconds)(attempt)); attempt++; } @@ -123381,11 +155514,11 @@ var require_upload_http_client = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -123401,18 +155534,18 @@ var require_upload_http_client = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.UploadHttpClient = void 0; - var fs32 = __importStar2(require("fs")); - var core31 = __importStar2(require_core3()); - var tmp = __importStar2(require_tmp_promise()); + var fs34 = __importStar2(require("fs")); + var core29 = __importStar2(require_core3()); + var tmp2 = __importStar2(require_tmp_promise()); var stream2 = __importStar2(require("stream")); - var utils_1 = require_utils11(); + var utils_1 = require_utils12(); var config_variables_1 = require_config_variables(); var util_1 = require("util"); var url_1 = require("url"); @@ -123422,7 +155555,7 @@ var require_upload_http_client = __commonJS({ var http_manager_1 = require_http_manager(); var upload_gzip_1 = require_upload_gzip(); var requestUtils_1 = require_requestUtils2(); - var stat2 = (0, util_1.promisify)(fs32.stat); + var stat2 = (0, util_1.promisify)(fs34.stat); var UploadHttpClient = class { constructor() { this.uploadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getUploadFileConcurrency)(), "@actions/artifact-upload"); @@ -123474,7 +155607,7 @@ var require_upload_http_client = __commonJS({ return __awaiter2(this, void 0, void 0, function* () { const FILE_CONCURRENCY = (0, config_variables_1.getUploadFileConcurrency)(); const MAX_CHUNK_SIZE = (0, config_variables_1.getUploadChunkSize)(); - core31.debug(`File Concurrency: ${FILE_CONCURRENCY}, and Chunk Size: ${MAX_CHUNK_SIZE}`); + core29.debug(`File Concurrency: ${FILE_CONCURRENCY}, and Chunk Size: ${MAX_CHUNK_SIZE}`); const parameters = []; let continueOnError = true; if (options) { @@ -123511,15 +155644,15 @@ var require_upload_http_client = __commonJS({ } const startTime = perf_hooks_1.performance.now(); const uploadFileResult = yield this.uploadFileAsync(index2, currentFileParameters); - if (core31.isDebug()) { - core31.debug(`File: ${++completedFiles}/${filesToUpload.length}. ${currentFileParameters.file} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish upload`); + if (core29.isDebug()) { + core29.debug(`File: ${++completedFiles}/${filesToUpload.length}. ${currentFileParameters.file} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish upload`); } uploadFileSize += uploadFileResult.successfulUploadSize; totalFileSize += uploadFileResult.totalSize; if (uploadFileResult.isSuccess === false) { failedItemsToReport.push(currentFileParameters.file); if (!continueOnError) { - core31.error(`aborting artifact upload`); + core29.error(`aborting artifact upload`); abortPendingFileUploads = true; } } @@ -123528,7 +155661,7 @@ var require_upload_http_client = __commonJS({ }))); this.statusReporter.stop(); this.uploadHttpManager.disposeAndReplaceAllClients(); - core31.info(`Total size of all the files uploaded is ${uploadFileSize} bytes`); + core29.info(`Total size of all the files uploaded is ${uploadFileSize} bytes`); return { uploadSize: uploadFileSize, totalSize: totalFileSize, @@ -123554,16 +155687,16 @@ var require_upload_http_client = __commonJS({ let uploadFileSize = 0; let isGzip = true; if (!isFIFO && totalFileSize < 65536) { - core31.debug(`${parameters.file} is less than 64k in size. Creating a gzip file in-memory to potentially reduce the upload size`); + core29.debug(`${parameters.file} is less than 64k in size. Creating a gzip file in-memory to potentially reduce the upload size`); const buffer = yield (0, upload_gzip_1.createGZipFileInBuffer)(parameters.file); let openUploadStream; if (totalFileSize < buffer.byteLength) { - core31.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`); - openUploadStream = () => fs32.createReadStream(parameters.file); + core29.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`); + openUploadStream = () => fs34.createReadStream(parameters.file); isGzip = false; uploadFileSize = totalFileSize; } else { - core31.debug(`A gzip file created for ${parameters.file} helped with reducing the size of the original file. The file will be uploaded using gzip.`); + core29.debug(`A gzip file created for ${parameters.file} helped with reducing the size of the original file. The file will be uploaded using gzip.`); openUploadStream = () => { const passThrough = new stream2.PassThrough(); passThrough.end(buffer); @@ -123575,7 +155708,7 @@ var require_upload_http_client = __commonJS({ if (!result) { isUploadSuccessful = false; failedChunkSizes += uploadFileSize; - core31.warning(`Aborting upload for ${parameters.file} due to failure`); + core29.warning(`Aborting upload for ${parameters.file} due to failure`); } return { isSuccess: isUploadSuccessful, @@ -123583,17 +155716,17 @@ var require_upload_http_client = __commonJS({ totalSize: totalFileSize }; } else { - const tempFile = yield tmp.file(); - core31.debug(`${parameters.file} is greater than 64k in size. Creating a gzip file on-disk ${tempFile.path} to potentially reduce the upload size`); + const tempFile = yield tmp2.file(); + core29.debug(`${parameters.file} is greater than 64k in size. Creating a gzip file on-disk ${tempFile.path} to potentially reduce the upload size`); uploadFileSize = yield (0, upload_gzip_1.createGZipFileOnDisk)(parameters.file, tempFile.path); let uploadFilePath = tempFile.path; if (!isFIFO && totalFileSize < uploadFileSize) { - core31.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`); + core29.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`); uploadFileSize = totalFileSize; uploadFilePath = parameters.file; isGzip = false; } else { - core31.debug(`The gzip file created for ${parameters.file} is smaller than the original file. The file will be uploaded using gzip.`); + core29.debug(`The gzip file created for ${parameters.file} is smaller than the original file. The file will be uploaded using gzip.`); } let abortFileUpload = false; while (offset < uploadFileSize) { @@ -123605,7 +155738,7 @@ var require_upload_http_client = __commonJS({ failedChunkSizes += chunkSize; continue; } - const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, () => fs32.createReadStream(uploadFilePath, { + const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, () => fs34.createReadStream(uploadFilePath, { start: startChunkIndex, end: endChunkIndex, autoClose: false @@ -123613,7 +155746,7 @@ var require_upload_http_client = __commonJS({ if (!result) { isUploadSuccessful = false; failedChunkSizes += chunkSize; - core31.warning(`Aborting upload for ${parameters.file} due to failure`); + core29.warning(`Aborting upload for ${parameters.file} due to failure`); abortFileUpload = true; } else { if (uploadFileSize > 8388608) { @@ -123621,7 +155754,7 @@ var require_upload_http_client = __commonJS({ } } } - core31.debug(`deleting temporary gzip file ${tempFile.path}`); + core29.debug(`deleting temporary gzip file ${tempFile.path}`); yield tempFile.cleanup(); return { isSuccess: isUploadSuccessful, @@ -123660,7 +155793,7 @@ var require_upload_http_client = __commonJS({ if (response) { (0, utils_1.displayHttpDiagnostics)(response); } - core31.info(`Retry limit has been reached for chunk at offset ${start} to ${resourceUrl}`); + core29.info(`Retry limit has been reached for chunk at offset ${start} to ${resourceUrl}`); return true; } return false; @@ -123668,14 +155801,14 @@ var require_upload_http_client = __commonJS({ const backOff = (retryAfterValue) => __awaiter2(this, void 0, void 0, function* () { this.uploadHttpManager.disposeAndReplaceClient(httpClientIndex); if (retryAfterValue) { - core31.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the upload`); + core29.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the upload`); yield (0, utils_1.sleep)(retryAfterValue); } else { const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount); - core31.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the upload at offset ${start}`); + core29.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the upload at offset ${start}`); yield (0, utils_1.sleep)(backoffTime); } - core31.info(`Finished backoff for retry #${retryCount}, continuing with upload`); + core29.info(`Finished backoff for retry #${retryCount}, continuing with upload`); return; }); while (retryCount <= retryLimit) { @@ -123683,7 +155816,7 @@ var require_upload_http_client = __commonJS({ try { response = yield uploadChunkRequest(); } catch (error3) { - core31.info(`An error has been caught http-client index ${httpClientIndex}, retrying the upload`); + core29.info(`An error has been caught http-client index ${httpClientIndex}, retrying the upload`); console.log(error3); if (incrementAndCheckRetryLimit()) { return false; @@ -123695,13 +155828,13 @@ var require_upload_http_client = __commonJS({ if ((0, utils_1.isSuccessStatusCode)(response.message.statusCode)) { return true; } else if ((0, utils_1.isRetryableStatusCode)(response.message.statusCode)) { - core31.info(`A ${response.message.statusCode} status code has been received, will attempt to retry the upload`); + core29.info(`A ${response.message.statusCode} status code has been received, will attempt to retry the upload`); if (incrementAndCheckRetryLimit(response)) { return false; } (0, utils_1.isThrottledStatusCode)(response.message.statusCode) ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers)) : yield backOff(); } else { - core31.error(`Unexpected response. Unable to upload chunk to ${resourceUrl}`); + core29.error(`Unexpected response. Unable to upload chunk to ${resourceUrl}`); (0, utils_1.displayHttpDiagnostics)(response); return false; } @@ -123719,7 +155852,7 @@ var require_upload_http_client = __commonJS({ resourceUrl.searchParams.append("artifactName", artifactName); const parameters = { Size: size }; const data = JSON.stringify(parameters, null, 2); - core31.debug(`URL is ${resourceUrl.toString()}`); + core29.debug(`URL is ${resourceUrl.toString()}`); const client = this.uploadHttpManager.getClient(0); const headers = (0, utils_1.getUploadHeaders)("application/json", false); const customErrorMessages = /* @__PURE__ */ new Map([ @@ -123732,7 +155865,7 @@ var require_upload_http_client = __commonJS({ return client.patch(resourceUrl.toString(), data, headers); }), customErrorMessages); yield response.readBody(); - core31.debug(`Artifact ${artifactName} has been successfully uploaded, total size in bytes: ${size}`); + core29.debug(`Artifact ${artifactName} has been successfully uploaded, total size in bytes: ${size}`); }); } }; @@ -123773,11 +155906,11 @@ var require_download_http_client = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -123793,17 +155926,17 @@ var require_download_http_client = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DownloadHttpClient = void 0; - var fs32 = __importStar2(require("fs")); - var core31 = __importStar2(require_core3()); + var fs34 = __importStar2(require("fs")); + var core29 = __importStar2(require_core3()); var zlib3 = __importStar2(require("zlib")); - var utils_1 = require_utils11(); + var utils_1 = require_utils12(); var url_1 = require("url"); var status_reporter_1 = require_status_reporter(); var perf_hooks_1 = require("perf_hooks"); @@ -123855,11 +155988,11 @@ var require_download_http_client = __commonJS({ downloadSingleArtifact(downloadItems) { return __awaiter2(this, void 0, void 0, function* () { const DOWNLOAD_CONCURRENCY = (0, config_variables_1.getDownloadFileConcurrency)(); - core31.debug(`Download file concurrency is set to ${DOWNLOAD_CONCURRENCY}`); + core29.debug(`Download file concurrency is set to ${DOWNLOAD_CONCURRENCY}`); const parallelDownloads = [...new Array(DOWNLOAD_CONCURRENCY).keys()]; let currentFile = 0; let downloadedFiles = 0; - core31.info(`Total number of files that will be downloaded: ${downloadItems.length}`); + core29.info(`Total number of files that will be downloaded: ${downloadItems.length}`); this.statusReporter.setTotalNumberOfFilesToProcess(downloadItems.length); this.statusReporter.start(); yield Promise.all(parallelDownloads.map((index2) => __awaiter2(this, void 0, void 0, function* () { @@ -123868,8 +156001,8 @@ var require_download_http_client = __commonJS({ currentFile += 1; const startTime = perf_hooks_1.performance.now(); yield this.downloadIndividualFile(index2, currentFileToDownload.sourceLocation, currentFileToDownload.targetPath); - if (core31.isDebug()) { - core31.debug(`File: ${++downloadedFiles}/${downloadItems.length}. ${currentFileToDownload.targetPath} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish downloading`); + if (core29.isDebug()) { + core29.debug(`File: ${++downloadedFiles}/${downloadItems.length}. ${currentFileToDownload.targetPath} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish downloading`); } this.statusReporter.incrementProcessedCount(); } @@ -123891,7 +156024,7 @@ var require_download_http_client = __commonJS({ return __awaiter2(this, void 0, void 0, function* () { let retryCount = 0; const retryLimit = (0, config_variables_1.getRetryLimit)(); - let destinationStream = fs32.createWriteStream(downloadPath); + let destinationStream = fs34.createWriteStream(downloadPath); const headers = (0, utils_1.getDownloadHeaders)("application/json", true, true); const makeDownloadRequest = () => __awaiter2(this, void 0, void 0, function* () { const client = this.downloadHttpManager.getClient(httpClientIndex); @@ -123907,40 +156040,40 @@ var require_download_http_client = __commonJS({ } else { this.downloadHttpManager.disposeAndReplaceClient(httpClientIndex); if (retryAfterValue) { - core31.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the download`); + core29.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the download`); yield (0, utils_1.sleep)(retryAfterValue); } else { const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount); - core31.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the download`); + core29.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the download`); yield (0, utils_1.sleep)(backoffTime); } - core31.info(`Finished backoff for retry #${retryCount}, continuing with download`); + core29.info(`Finished backoff for retry #${retryCount}, continuing with download`); } }); const isAllBytesReceived = (expected, received) => { if (!expected || !received || process.env["ACTIONS_ARTIFACT_SKIP_DOWNLOAD_VALIDATION"]) { - core31.info("Skipping download validation."); + core29.info("Skipping download validation."); return true; } return parseInt(expected) === received; }; const resetDestinationStream = (fileDownloadPath) => __awaiter2(this, void 0, void 0, function* () { destinationStream.close(); - yield new Promise((resolve14) => { - destinationStream.on("close", resolve14); + yield new Promise((resolve15) => { + destinationStream.on("close", resolve15); if (destinationStream.writableFinished) { - resolve14(); + resolve15(); } }); yield (0, utils_1.rmFile)(fileDownloadPath); - destinationStream = fs32.createWriteStream(fileDownloadPath); + destinationStream = fs34.createWriteStream(fileDownloadPath); }); while (retryCount <= retryLimit) { let response; try { response = yield makeDownloadRequest(); } catch (error3) { - core31.info("An error occurred while attempting to download a file"); + core29.info("An error occurred while attempting to download a file"); console.log(error3); yield backOff(); continue; @@ -123960,7 +156093,7 @@ var require_download_http_client = __commonJS({ } } if (forceRetry || (0, utils_1.isRetryableStatusCode)(response.message.statusCode)) { - core31.info(`A ${response.message.statusCode} response code has been received while attempting to download an artifact`); + core29.info(`A ${response.message.statusCode} response code has been received while attempting to download an artifact`); resetDestinationStream(downloadPath); (0, utils_1.isThrottledStatusCode)(response.message.statusCode) ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers)) : yield backOff(); } else { @@ -123978,33 +156111,33 @@ var require_download_http_client = __commonJS({ */ pipeResponseToFile(response, destinationStream, isGzip) { return __awaiter2(this, void 0, void 0, function* () { - yield new Promise((resolve14, reject) => { + yield new Promise((resolve15, reject) => { if (isGzip) { const gunzip = zlib3.createGunzip(); response.message.on("error", (error3) => { - core31.info(`An error occurred while attempting to read the response stream`); + core29.info(`An error occurred while attempting to read the response stream`); gunzip.close(); destinationStream.close(); reject(error3); }).pipe(gunzip).on("error", (error3) => { - core31.info(`An error occurred while attempting to decompress the response stream`); + core29.info(`An error occurred while attempting to decompress the response stream`); destinationStream.close(); reject(error3); }).pipe(destinationStream).on("close", () => { - resolve14(); + resolve15(); }).on("error", (error3) => { - core31.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`); + core29.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`); reject(error3); }); } else { response.message.on("error", (error3) => { - core31.info(`An error occurred while attempting to read the response stream`); + core29.info(`An error occurred while attempting to read the response stream`); destinationStream.close(); reject(error3); }).pipe(destinationStream).on("close", () => { - resolve14(); + resolve15(); }).on("error", (error3) => { - core31.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`); + core29.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`); reject(error3); }); } @@ -124116,11 +156249,11 @@ var require_artifact_client = __commonJS({ }; var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { - return value instanceof P ? value : new P(function(resolve14) { - resolve14(value); + return value instanceof P ? value : new P(function(resolve15) { + resolve15(value); }); } - return new (P || (P = Promise))(function(resolve14, reject) { + return new (P || (P = Promise))(function(resolve15, reject) { function fulfilled(value) { try { step(generator.next(value)); @@ -124136,17 +156269,17 @@ var require_artifact_client = __commonJS({ } } function step(result) { - result.done ? resolve14(result.value) : adopt(result.value).then(fulfilled, rejected); + result.done ? resolve15(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DefaultArtifactClient = void 0; - var core31 = __importStar2(require_core3()); + var core29 = __importStar2(require_core3()); var upload_specification_1 = require_upload_specification(); var upload_http_client_1 = require_upload_http_client(); - var utils_1 = require_utils11(); + var utils_1 = require_utils12(); var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2(); var download_http_client_1 = require_download_http_client(); var download_specification_1 = require_download_specification(); @@ -124164,7 +156297,7 @@ var require_artifact_client = __commonJS({ */ uploadArtifact(name, files, rootDirectory, options) { return __awaiter2(this, void 0, void 0, function* () { - core31.info(`Starting artifact upload + core29.info(`Starting artifact upload For more detailed logs during the artifact upload process, enable step-debugging: https://docs.github.com/actions/monitoring-and-troubleshooting-workflows/enabling-debug-logging#enabling-step-debug-logging`); (0, path_and_artifact_name_validation_1.checkArtifactName)(name); const uploadSpecification = (0, upload_specification_1.getUploadSpecification)(name, rootDirectory, files); @@ -124176,24 +156309,24 @@ For more detailed logs during the artifact upload process, enable step-debugging }; const uploadHttpClient = new upload_http_client_1.UploadHttpClient(); if (uploadSpecification.length === 0) { - core31.warning(`No files found that can be uploaded`); + core29.warning(`No files found that can be uploaded`); } else { const response = yield uploadHttpClient.createArtifactInFileContainer(name, options); if (!response.fileContainerResourceUrl) { - core31.debug(response.toString()); + core29.debug(response.toString()); throw new Error("No URL provided by the Artifact Service to upload an artifact to"); } - core31.debug(`Upload Resource URL: ${response.fileContainerResourceUrl}`); - core31.info(`Container for artifact "${name}" successfully created. Starting upload of file(s)`); + core29.debug(`Upload Resource URL: ${response.fileContainerResourceUrl}`); + core29.info(`Container for artifact "${name}" successfully created. Starting upload of file(s)`); const uploadResult = yield uploadHttpClient.uploadArtifactToFileContainer(response.fileContainerResourceUrl, uploadSpecification, options); - core31.info(`File upload process has finished. Finalizing the artifact upload`); + core29.info(`File upload process has finished. Finalizing the artifact upload`); yield uploadHttpClient.patchArtifactSize(uploadResult.totalSize, name); if (uploadResult.failedItems.length > 0) { - core31.info(`Upload finished. There were ${uploadResult.failedItems.length} items that failed to upload`); + core29.info(`Upload finished. There were ${uploadResult.failedItems.length} items that failed to upload`); } else { - core31.info(`Artifact has been finalized. All files have been successfully uploaded!`); + core29.info(`Artifact has been finalized. All files have been successfully uploaded!`); } - core31.info(` + core29.info(` The raw size of all the files that were specified for upload is ${uploadResult.totalSize} bytes The size of all the files that were uploaded is ${uploadResult.uploadSize} bytes. This takes into account any gzip compression used to reduce the upload size, time and storage @@ -124227,10 +156360,10 @@ Note: The size of downloaded zips can differ significantly from the reported siz path30 = (0, path_1.resolve)(path30); const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(name, items.value, path30, (options === null || options === void 0 ? void 0 : options.createArtifactFolder) || false); if (downloadSpecification.filesToDownload.length === 0) { - core31.info(`No downloadable files were found for the artifact: ${artifactToDownload.name}`); + core29.info(`No downloadable files were found for the artifact: ${artifactToDownload.name}`); } else { yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure); - core31.info("Directory structure has been set up for the artifact"); + core29.info("Directory structure has been set up for the artifact"); yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate); yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload); } @@ -124246,7 +156379,7 @@ Note: The size of downloaded zips can differ significantly from the reported siz const response = []; const artifacts = yield downloadHttpClient.listArtifacts(); if (artifacts.count === 0) { - core31.info("Unable to find any artifacts for the associated workflow"); + core29.info("Unable to find any artifacts for the associated workflow"); return response; } if (!path30) { @@ -124258,11 +156391,11 @@ Note: The size of downloaded zips can differ significantly from the reported siz while (downloadedArtifacts < artifacts.count) { const currentArtifactToDownload = artifacts.value[downloadedArtifacts]; downloadedArtifacts += 1; - core31.info(`starting download of artifact ${currentArtifactToDownload.name} : ${downloadedArtifacts}/${artifacts.count}`); + core29.info(`starting download of artifact ${currentArtifactToDownload.name} : ${downloadedArtifacts}/${artifacts.count}`); const items = yield downloadHttpClient.getContainerItems(currentArtifactToDownload.name, currentArtifactToDownload.fileContainerResourceUrl); const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(currentArtifactToDownload.name, items.value, path30, true); if (downloadSpecification.filesToDownload.length === 0) { - core31.info(`No downloadable files were found for any artifact ${currentArtifactToDownload.name}`); + core29.info(`No downloadable files were found for any artifact ${currentArtifactToDownload.name}`); } else { yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure); yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate); @@ -124422,31 +156555,31 @@ var require_baseN = __commonJS({ }); // node_modules/node-forge/lib/util.js -var require_util16 = __commonJS({ +var require_util14 = __commonJS({ "node_modules/node-forge/lib/util.js"(exports2, module2) { var forge = require_forge(); var baseN = require_baseN(); - var util3 = module2.exports = forge.util = forge.util || {}; + var util4 = module2.exports = forge.util = forge.util || {}; (function() { if (typeof process !== "undefined" && process.nextTick && !process.browser) { - util3.nextTick = process.nextTick; + util4.nextTick = process.nextTick; if (typeof setImmediate === "function") { - util3.setImmediate = setImmediate; + util4.setImmediate = setImmediate; } else { - util3.setImmediate = util3.nextTick; + util4.setImmediate = util4.nextTick; } return; } if (typeof setImmediate === "function") { - util3.setImmediate = function() { + util4.setImmediate = function() { return setImmediate.apply(void 0, arguments); }; - util3.nextTick = function(callback) { + util4.nextTick = function(callback) { return setImmediate(callback); }; return; } - util3.setImmediate = function(callback) { + util4.setImmediate = function(callback) { setTimeout(callback, 0); }; if (typeof window !== "undefined" && typeof window.postMessage === "function") { @@ -124463,7 +156596,7 @@ var require_util16 = __commonJS({ var handler2 = handler3; var msg = "forge.setImmediate"; var callbacks = []; - util3.setImmediate = function(callback) { + util4.setImmediate = function(callback) { callbacks.push(callback); if (callbacks.length === 1) { window.postMessage(msg, "*"); @@ -124483,8 +156616,8 @@ var require_util16 = __commonJS({ callback(); }); }).observe(div, { attributes: true }); - var oldSetImmediate = util3.setImmediate; - util3.setImmediate = function(callback) { + var oldSetImmediate = util4.setImmediate; + util4.setImmediate = function(callback) { if (Date.now() - now > 15) { now = Date.now(); oldSetImmediate(callback); @@ -124496,36 +156629,36 @@ var require_util16 = __commonJS({ } }; } - util3.nextTick = util3.setImmediate; + util4.nextTick = util4.setImmediate; })(); - util3.isNodejs = typeof process !== "undefined" && process.versions && process.versions.node; - util3.globalScope = (function() { - if (util3.isNodejs) { + util4.isNodejs = typeof process !== "undefined" && process.versions && process.versions.node; + util4.globalScope = (function() { + if (util4.isNodejs) { return global; } return typeof self === "undefined" ? window : self; })(); - util3.isArray = Array.isArray || function(x) { + util4.isArray = Array.isArray || function(x) { return Object.prototype.toString.call(x) === "[object Array]"; }; - util3.isArrayBuffer = function(x) { + util4.isArrayBuffer = function(x) { return typeof ArrayBuffer !== "undefined" && x instanceof ArrayBuffer; }; - util3.isArrayBufferView = function(x) { - return x && util3.isArrayBuffer(x.buffer) && x.byteLength !== void 0; + util4.isArrayBufferView = function(x) { + return x && util4.isArrayBuffer(x.buffer) && x.byteLength !== void 0; }; function _checkBitsParam(n) { if (!(n === 8 || n === 16 || n === 24 || n === 32)) { throw new Error("Only 8, 16, 24, or 32 bits supported: " + n); } } - util3.ByteBuffer = ByteStringBuffer; + util4.ByteBuffer = ByteStringBuffer; function ByteStringBuffer(b) { this.data = ""; this.read = 0; if (typeof b === "string") { this.data = b; - } else if (util3.isArrayBuffer(b) || util3.isArrayBufferView(b)) { + } else if (util4.isArrayBuffer(b) || util4.isArrayBufferView(b)) { if (typeof Buffer !== "undefined" && b instanceof Buffer) { this.data = b.toString("binary"); } else { @@ -124544,25 +156677,25 @@ var require_util16 = __commonJS({ } this._constructedStringLength = 0; } - util3.ByteStringBuffer = ByteStringBuffer; + util4.ByteStringBuffer = ByteStringBuffer; var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; - util3.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { + util4.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { this._constructedStringLength += x; if (this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { this.data.substr(0, 1); this._constructedStringLength = 0; } }; - util3.ByteStringBuffer.prototype.length = function() { + util4.ByteStringBuffer.prototype.length = function() { return this.data.length - this.read; }; - util3.ByteStringBuffer.prototype.isEmpty = function() { + util4.ByteStringBuffer.prototype.isEmpty = function() { return this.length() <= 0; }; - util3.ByteStringBuffer.prototype.putByte = function(b) { + util4.ByteStringBuffer.prototype.putByte = function(b) { return this.putBytes(String.fromCharCode(b)); }; - util3.ByteStringBuffer.prototype.fillWithByte = function(b, n) { + util4.ByteStringBuffer.prototype.fillWithByte = function(b, n) { b = String.fromCharCode(b); var d = this.data; while (n > 0) { @@ -124578,45 +156711,45 @@ var require_util16 = __commonJS({ this._optimizeConstructedString(n); return this; }; - util3.ByteStringBuffer.prototype.putBytes = function(bytes) { + util4.ByteStringBuffer.prototype.putBytes = function(bytes) { this.data += bytes; this._optimizeConstructedString(bytes.length); return this; }; - util3.ByteStringBuffer.prototype.putString = function(str) { - return this.putBytes(util3.encodeUtf8(str)); + util4.ByteStringBuffer.prototype.putString = function(str) { + return this.putBytes(util4.encodeUtf8(str)); }; - util3.ByteStringBuffer.prototype.putInt16 = function(i) { + util4.ByteStringBuffer.prototype.putInt16 = function(i) { return this.putBytes( String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) ); }; - util3.ByteStringBuffer.prototype.putInt24 = function(i) { + util4.ByteStringBuffer.prototype.putInt24 = function(i) { return this.putBytes( String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) ); }; - util3.ByteStringBuffer.prototype.putInt32 = function(i) { + util4.ByteStringBuffer.prototype.putInt32 = function(i) { return this.putBytes( String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) ); }; - util3.ByteStringBuffer.prototype.putInt16Le = function(i) { + util4.ByteStringBuffer.prototype.putInt16Le = function(i) { return this.putBytes( String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) ); }; - util3.ByteStringBuffer.prototype.putInt24Le = function(i) { + util4.ByteStringBuffer.prototype.putInt24Le = function(i) { return this.putBytes( String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) ); }; - util3.ByteStringBuffer.prototype.putInt32Le = function(i) { + util4.ByteStringBuffer.prototype.putInt32Le = function(i) { return this.putBytes( String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 24 & 255) ); }; - util3.ByteStringBuffer.prototype.putInt = function(i, n) { + util4.ByteStringBuffer.prototype.putInt = function(i, n) { _checkBitsParam(n); var bytes = ""; do { @@ -124625,49 +156758,49 @@ var require_util16 = __commonJS({ } while (n > 0); return this.putBytes(bytes); }; - util3.ByteStringBuffer.prototype.putSignedInt = function(i, n) { + util4.ByteStringBuffer.prototype.putSignedInt = function(i, n) { if (i < 0) { i += 2 << n - 1; } return this.putInt(i, n); }; - util3.ByteStringBuffer.prototype.putBuffer = function(buffer) { + util4.ByteStringBuffer.prototype.putBuffer = function(buffer) { return this.putBytes(buffer.getBytes()); }; - util3.ByteStringBuffer.prototype.getByte = function() { + util4.ByteStringBuffer.prototype.getByte = function() { return this.data.charCodeAt(this.read++); }; - util3.ByteStringBuffer.prototype.getInt16 = function() { + util4.ByteStringBuffer.prototype.getInt16 = function() { var rval = this.data.charCodeAt(this.read) << 8 ^ this.data.charCodeAt(this.read + 1); this.read += 2; return rval; }; - util3.ByteStringBuffer.prototype.getInt24 = function() { + util4.ByteStringBuffer.prototype.getInt24 = function() { var rval = this.data.charCodeAt(this.read) << 16 ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2); this.read += 3; return rval; }; - util3.ByteStringBuffer.prototype.getInt32 = function() { + util4.ByteStringBuffer.prototype.getInt32 = function() { var rval = this.data.charCodeAt(this.read) << 24 ^ this.data.charCodeAt(this.read + 1) << 16 ^ this.data.charCodeAt(this.read + 2) << 8 ^ this.data.charCodeAt(this.read + 3); this.read += 4; return rval; }; - util3.ByteStringBuffer.prototype.getInt16Le = function() { + util4.ByteStringBuffer.prototype.getInt16Le = function() { var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8; this.read += 2; return rval; }; - util3.ByteStringBuffer.prototype.getInt24Le = function() { + util4.ByteStringBuffer.prototype.getInt24Le = function() { var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16; this.read += 3; return rval; }; - util3.ByteStringBuffer.prototype.getInt32Le = function() { + util4.ByteStringBuffer.prototype.getInt32Le = function() { var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16 ^ this.data.charCodeAt(this.read + 3) << 24; this.read += 4; return rval; }; - util3.ByteStringBuffer.prototype.getInt = function(n) { + util4.ByteStringBuffer.prototype.getInt = function(n) { _checkBitsParam(n); var rval = 0; do { @@ -124676,7 +156809,7 @@ var require_util16 = __commonJS({ } while (n > 0); return rval; }; - util3.ByteStringBuffer.prototype.getSignedInt = function(n) { + util4.ByteStringBuffer.prototype.getSignedInt = function(n) { var x = this.getInt(n); var max = 2 << n - 2; if (x >= max) { @@ -124684,7 +156817,7 @@ var require_util16 = __commonJS({ } return x; }; - util3.ByteStringBuffer.prototype.getBytes = function(count) { + util4.ByteStringBuffer.prototype.getBytes = function(count) { var rval; if (count) { count = Math.min(this.length(), count); @@ -124698,43 +156831,43 @@ var require_util16 = __commonJS({ } return rval; }; - util3.ByteStringBuffer.prototype.bytes = function(count) { + util4.ByteStringBuffer.prototype.bytes = function(count) { return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); }; - util3.ByteStringBuffer.prototype.at = function(i) { + util4.ByteStringBuffer.prototype.at = function(i) { return this.data.charCodeAt(this.read + i); }; - util3.ByteStringBuffer.prototype.setAt = function(i, b) { + util4.ByteStringBuffer.prototype.setAt = function(i, b) { this.data = this.data.substr(0, this.read + i) + String.fromCharCode(b) + this.data.substr(this.read + i + 1); return this; }; - util3.ByteStringBuffer.prototype.last = function() { + util4.ByteStringBuffer.prototype.last = function() { return this.data.charCodeAt(this.data.length - 1); }; - util3.ByteStringBuffer.prototype.copy = function() { - var c = util3.createBuffer(this.data); + util4.ByteStringBuffer.prototype.copy = function() { + var c = util4.createBuffer(this.data); c.read = this.read; return c; }; - util3.ByteStringBuffer.prototype.compact = function() { + util4.ByteStringBuffer.prototype.compact = function() { if (this.read > 0) { this.data = this.data.slice(this.read); this.read = 0; } return this; }; - util3.ByteStringBuffer.prototype.clear = function() { + util4.ByteStringBuffer.prototype.clear = function() { this.data = ""; this.read = 0; return this; }; - util3.ByteStringBuffer.prototype.truncate = function(count) { + util4.ByteStringBuffer.prototype.truncate = function(count) { var len = Math.max(0, this.length() - count); this.data = this.data.substr(this.read, len); this.read = 0; return this; }; - util3.ByteStringBuffer.prototype.toHex = function() { + util4.ByteStringBuffer.prototype.toHex = function() { var rval = ""; for (var i = this.read; i < this.data.length; ++i) { var b = this.data.charCodeAt(i); @@ -124745,15 +156878,15 @@ var require_util16 = __commonJS({ } return rval; }; - util3.ByteStringBuffer.prototype.toString = function() { - return util3.decodeUtf8(this.bytes()); + util4.ByteStringBuffer.prototype.toString = function() { + return util4.decodeUtf8(this.bytes()); }; function DataBuffer(b, options) { options = options || {}; this.read = options.readOffset || 0; this.growSize = options.growSize || 1024; - var isArrayBuffer = util3.isArrayBuffer(b); - var isArrayBufferView = util3.isArrayBufferView(b); + var isArrayBuffer = util4.isArrayBuffer(b); + var isArrayBufferView = util4.isArrayBufferView(b); if (isArrayBuffer || isArrayBufferView) { if (isArrayBuffer) { this.data = new DataView(b); @@ -124772,14 +156905,14 @@ var require_util16 = __commonJS({ this.write = options.writeOffset; } } - util3.DataBuffer = DataBuffer; - util3.DataBuffer.prototype.length = function() { + util4.DataBuffer = DataBuffer; + util4.DataBuffer.prototype.length = function() { return this.write - this.read; }; - util3.DataBuffer.prototype.isEmpty = function() { + util4.DataBuffer.prototype.isEmpty = function() { return this.length() <= 0; }; - util3.DataBuffer.prototype.accommodate = function(amount, growSize) { + util4.DataBuffer.prototype.accommodate = function(amount, growSize) { if (this.length() >= amount) { return this; } @@ -124794,20 +156927,20 @@ var require_util16 = __commonJS({ this.data = new DataView(dst.buffer); return this; }; - util3.DataBuffer.prototype.putByte = function(b) { + util4.DataBuffer.prototype.putByte = function(b) { this.accommodate(1); this.data.setUint8(this.write++, b); return this; }; - util3.DataBuffer.prototype.fillWithByte = function(b, n) { + util4.DataBuffer.prototype.fillWithByte = function(b, n) { this.accommodate(n); for (var i = 0; i < n; ++i) { this.data.setUint8(b); } return this; }; - util3.DataBuffer.prototype.putBytes = function(bytes, encoding) { - if (util3.isArrayBufferView(bytes)) { + util4.DataBuffer.prototype.putBytes = function(bytes, encoding) { + if (util4.isArrayBufferView(bytes)) { var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); var len = src.byteLength - src.byteOffset; this.accommodate(len); @@ -124816,7 +156949,7 @@ var require_util16 = __commonJS({ this.write += len; return this; } - if (util3.isArrayBuffer(bytes)) { + if (util4.isArrayBuffer(bytes)) { var src = new Uint8Array(bytes); this.accommodate(src.byteLength); var dst = new Uint8Array(this.data.buffer); @@ -124824,7 +156957,7 @@ var require_util16 = __commonJS({ this.write += src.byteLength; return this; } - if (bytes instanceof util3.DataBuffer || typeof bytes === "object" && typeof bytes.read === "number" && typeof bytes.write === "number" && util3.isArrayBufferView(bytes.data)) { + if (bytes instanceof util4.DataBuffer || typeof bytes === "object" && typeof bytes.read === "number" && typeof bytes.write === "number" && util4.isArrayBufferView(bytes.data)) { var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); this.accommodate(src.byteLength); var dst = new Uint8Array(bytes.data.byteLength, this.write); @@ -124832,7 +156965,7 @@ var require_util16 = __commonJS({ this.write += src.byteLength; return this; } - if (bytes instanceof util3.ByteStringBuffer) { + if (bytes instanceof util4.ByteStringBuffer) { bytes = bytes.data; encoding = "binary"; } @@ -124842,82 +156975,82 @@ var require_util16 = __commonJS({ if (encoding === "hex") { this.accommodate(Math.ceil(bytes.length / 2)); view = new Uint8Array(this.data.buffer, this.write); - this.write += util3.binary.hex.decode(bytes, view, this.write); + this.write += util4.binary.hex.decode(bytes, view, this.write); return this; } if (encoding === "base64") { this.accommodate(Math.ceil(bytes.length / 4) * 3); view = new Uint8Array(this.data.buffer, this.write); - this.write += util3.binary.base64.decode(bytes, view, this.write); + this.write += util4.binary.base64.decode(bytes, view, this.write); return this; } if (encoding === "utf8") { - bytes = util3.encodeUtf8(bytes); + bytes = util4.encodeUtf8(bytes); encoding = "binary"; } if (encoding === "binary" || encoding === "raw") { this.accommodate(bytes.length); view = new Uint8Array(this.data.buffer, this.write); - this.write += util3.binary.raw.decode(view); + this.write += util4.binary.raw.decode(view); return this; } if (encoding === "utf16") { this.accommodate(bytes.length * 2); view = new Uint16Array(this.data.buffer, this.write); - this.write += util3.text.utf16.encode(view); + this.write += util4.text.utf16.encode(view); return this; } throw new Error("Invalid encoding: " + encoding); } throw Error("Invalid parameter: " + bytes); }; - util3.DataBuffer.prototype.putBuffer = function(buffer) { + util4.DataBuffer.prototype.putBuffer = function(buffer) { this.putBytes(buffer); buffer.clear(); return this; }; - util3.DataBuffer.prototype.putString = function(str) { + util4.DataBuffer.prototype.putString = function(str) { return this.putBytes(str, "utf16"); }; - util3.DataBuffer.prototype.putInt16 = function(i) { + util4.DataBuffer.prototype.putInt16 = function(i) { this.accommodate(2); this.data.setInt16(this.write, i); this.write += 2; return this; }; - util3.DataBuffer.prototype.putInt24 = function(i) { + util4.DataBuffer.prototype.putInt24 = function(i) { this.accommodate(3); this.data.setInt16(this.write, i >> 8 & 65535); this.data.setInt8(this.write, i >> 16 & 255); this.write += 3; return this; }; - util3.DataBuffer.prototype.putInt32 = function(i) { + util4.DataBuffer.prototype.putInt32 = function(i) { this.accommodate(4); this.data.setInt32(this.write, i); this.write += 4; return this; }; - util3.DataBuffer.prototype.putInt16Le = function(i) { + util4.DataBuffer.prototype.putInt16Le = function(i) { this.accommodate(2); this.data.setInt16(this.write, i, true); this.write += 2; return this; }; - util3.DataBuffer.prototype.putInt24Le = function(i) { + util4.DataBuffer.prototype.putInt24Le = function(i) { this.accommodate(3); this.data.setInt8(this.write, i >> 16 & 255); this.data.setInt16(this.write, i >> 8 & 65535, true); this.write += 3; return this; }; - util3.DataBuffer.prototype.putInt32Le = function(i) { + util4.DataBuffer.prototype.putInt32Le = function(i) { this.accommodate(4); this.data.setInt32(this.write, i, true); this.write += 4; return this; }; - util3.DataBuffer.prototype.putInt = function(i, n) { + util4.DataBuffer.prototype.putInt = function(i, n) { _checkBitsParam(n); this.accommodate(n / 8); do { @@ -124926,7 +157059,7 @@ var require_util16 = __commonJS({ } while (n > 0); return this; }; - util3.DataBuffer.prototype.putSignedInt = function(i, n) { + util4.DataBuffer.prototype.putSignedInt = function(i, n) { _checkBitsParam(n); this.accommodate(n / 8); if (i < 0) { @@ -124934,40 +157067,40 @@ var require_util16 = __commonJS({ } return this.putInt(i, n); }; - util3.DataBuffer.prototype.getByte = function() { + util4.DataBuffer.prototype.getByte = function() { return this.data.getInt8(this.read++); }; - util3.DataBuffer.prototype.getInt16 = function() { + util4.DataBuffer.prototype.getInt16 = function() { var rval = this.data.getInt16(this.read); this.read += 2; return rval; }; - util3.DataBuffer.prototype.getInt24 = function() { + util4.DataBuffer.prototype.getInt24 = function() { var rval = this.data.getInt16(this.read) << 8 ^ this.data.getInt8(this.read + 2); this.read += 3; return rval; }; - util3.DataBuffer.prototype.getInt32 = function() { + util4.DataBuffer.prototype.getInt32 = function() { var rval = this.data.getInt32(this.read); this.read += 4; return rval; }; - util3.DataBuffer.prototype.getInt16Le = function() { + util4.DataBuffer.prototype.getInt16Le = function() { var rval = this.data.getInt16(this.read, true); this.read += 2; return rval; }; - util3.DataBuffer.prototype.getInt24Le = function() { + util4.DataBuffer.prototype.getInt24Le = function() { var rval = this.data.getInt8(this.read) ^ this.data.getInt16(this.read + 1, true) << 8; this.read += 3; return rval; }; - util3.DataBuffer.prototype.getInt32Le = function() { + util4.DataBuffer.prototype.getInt32Le = function() { var rval = this.data.getInt32(this.read, true); this.read += 4; return rval; }; - util3.DataBuffer.prototype.getInt = function(n) { + util4.DataBuffer.prototype.getInt = function(n) { _checkBitsParam(n); var rval = 0; do { @@ -124976,7 +157109,7 @@ var require_util16 = __commonJS({ } while (n > 0); return rval; }; - util3.DataBuffer.prototype.getSignedInt = function(n) { + util4.DataBuffer.prototype.getSignedInt = function(n) { var x = this.getInt(n); var max = 2 << n - 2; if (x >= max) { @@ -124984,7 +157117,7 @@ var require_util16 = __commonJS({ } return x; }; - util3.DataBuffer.prototype.getBytes = function(count) { + util4.DataBuffer.prototype.getBytes = function(count) { var rval; if (count) { count = Math.min(this.length(), count); @@ -124998,23 +157131,23 @@ var require_util16 = __commonJS({ } return rval; }; - util3.DataBuffer.prototype.bytes = function(count) { + util4.DataBuffer.prototype.bytes = function(count) { return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); }; - util3.DataBuffer.prototype.at = function(i) { + util4.DataBuffer.prototype.at = function(i) { return this.data.getUint8(this.read + i); }; - util3.DataBuffer.prototype.setAt = function(i, b) { + util4.DataBuffer.prototype.setAt = function(i, b) { this.data.setUint8(i, b); return this; }; - util3.DataBuffer.prototype.last = function() { + util4.DataBuffer.prototype.last = function() { return this.data.getUint8(this.write - 1); }; - util3.DataBuffer.prototype.copy = function() { - return new util3.DataBuffer(this); + util4.DataBuffer.prototype.copy = function() { + return new util4.DataBuffer(this); }; - util3.DataBuffer.prototype.compact = function() { + util4.DataBuffer.prototype.compact = function() { if (this.read > 0) { var src = new Uint8Array(this.data.buffer, this.read); var dst = new Uint8Array(src.byteLength); @@ -125025,17 +157158,17 @@ var require_util16 = __commonJS({ } return this; }; - util3.DataBuffer.prototype.clear = function() { + util4.DataBuffer.prototype.clear = function() { this.data = new DataView(new ArrayBuffer(0)); this.read = this.write = 0; return this; }; - util3.DataBuffer.prototype.truncate = function(count) { + util4.DataBuffer.prototype.truncate = function(count) { this.write = Math.max(0, this.length() - count); this.read = Math.min(this.read, this.write); return this; }; - util3.DataBuffer.prototype.toHex = function() { + util4.DataBuffer.prototype.toHex = function() { var rval = ""; for (var i = this.read; i < this.data.byteLength; ++i) { var b = this.data.getUint8(i); @@ -125046,34 +157179,34 @@ var require_util16 = __commonJS({ } return rval; }; - util3.DataBuffer.prototype.toString = function(encoding) { + util4.DataBuffer.prototype.toString = function(encoding) { var view = new Uint8Array(this.data, this.read, this.length()); encoding = encoding || "utf8"; if (encoding === "binary" || encoding === "raw") { - return util3.binary.raw.encode(view); + return util4.binary.raw.encode(view); } if (encoding === "hex") { - return util3.binary.hex.encode(view); + return util4.binary.hex.encode(view); } if (encoding === "base64") { - return util3.binary.base64.encode(view); + return util4.binary.base64.encode(view); } if (encoding === "utf8") { - return util3.text.utf8.decode(view); + return util4.text.utf8.decode(view); } if (encoding === "utf16") { - return util3.text.utf16.decode(view); + return util4.text.utf16.decode(view); } throw new Error("Invalid encoding: " + encoding); }; - util3.createBuffer = function(input, encoding) { + util4.createBuffer = function(input, encoding) { encoding = encoding || "raw"; if (input !== void 0 && encoding === "utf8") { - input = util3.encodeUtf8(input); + input = util4.encodeUtf8(input); } - return new util3.ByteBuffer(input); + return new util4.ByteBuffer(input); }; - util3.fillString = function(c, n) { + util4.fillString = function(c, n) { var s = ""; while (n > 0) { if (n & 1) { @@ -125086,7 +157219,7 @@ var require_util16 = __commonJS({ } return s; }; - util3.xorBytes = function(s1, s2, n) { + util4.xorBytes = function(s1, s2, n) { var s3 = ""; var b = ""; var t = ""; @@ -125105,7 +157238,7 @@ var require_util16 = __commonJS({ s3 += t; return s3; }; - util3.hexToBytes = function(hex) { + util4.hexToBytes = function(hex) { var rval = ""; var i = 0; if (hex.length & true) { @@ -125117,10 +157250,10 @@ var require_util16 = __commonJS({ } return rval; }; - util3.bytesToHex = function(bytes) { - return util3.createBuffer(bytes).toHex(); + util4.bytesToHex = function(bytes) { + return util4.createBuffer(bytes).toHex(); }; - util3.int32ToBytes = function(i) { + util4.int32ToBytes = function(i) { return String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255); }; var _base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; @@ -125219,7 +157352,7 @@ var require_util16 = __commonJS({ 51 ]; var _base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; - util3.encode64 = function(input, maxline) { + util4.encode64 = function(input, maxline) { var line = ""; var output = ""; var chr1, chr2, chr3; @@ -125244,7 +157377,7 @@ var require_util16 = __commonJS({ output += line; return output; }; - util3.decode64 = function(input) { + util4.decode64 = function(input) { input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); var output = ""; var enc1, enc2, enc3, enc4; @@ -125264,13 +157397,13 @@ var require_util16 = __commonJS({ } return output; }; - util3.encodeUtf8 = function(str) { + util4.encodeUtf8 = function(str) { return unescape(encodeURIComponent(str)); }; - util3.decodeUtf8 = function(str) { + util4.decodeUtf8 = function(str) { return decodeURIComponent(escape(str)); }; - util3.binary = { + util4.binary = { raw: {}, hex: {}, base64: {}, @@ -125280,10 +157413,10 @@ var require_util16 = __commonJS({ decode: baseN.decode } }; - util3.binary.raw.encode = function(bytes) { + util4.binary.raw.encode = function(bytes) { return String.fromCharCode.apply(null, bytes); }; - util3.binary.raw.decode = function(str, output, offset) { + util4.binary.raw.decode = function(str, output, offset) { var out = output; if (!out) { out = new Uint8Array(str.length); @@ -125295,8 +157428,8 @@ var require_util16 = __commonJS({ } return output ? j - offset : out; }; - util3.binary.hex.encode = util3.bytesToHex; - util3.binary.hex.decode = function(hex, output, offset) { + util4.binary.hex.encode = util4.bytesToHex; + util4.binary.hex.decode = function(hex, output, offset) { var out = output; if (!out) { out = new Uint8Array(Math.ceil(hex.length / 2)); @@ -125312,7 +157445,7 @@ var require_util16 = __commonJS({ } return output ? j - offset : out; }; - util3.binary.base64.encode = function(input, maxline) { + util4.binary.base64.encode = function(input, maxline) { var line = ""; var output = ""; var chr1, chr2, chr3; @@ -125337,7 +157470,7 @@ var require_util16 = __commonJS({ output += line; return output; }; - util3.binary.base64.decode = function(input, output, offset) { + util4.binary.base64.decode = function(input, output, offset) { var out = output; if (!out) { out = new Uint8Array(Math.ceil(input.length / 4) * 3); @@ -125361,18 +157494,18 @@ var require_util16 = __commonJS({ } return output ? j - offset : out.subarray(0, j); }; - util3.binary.base58.encode = function(input, maxline) { - return util3.binary.baseN.encode(input, _base58, maxline); + util4.binary.base58.encode = function(input, maxline) { + return util4.binary.baseN.encode(input, _base58, maxline); }; - util3.binary.base58.decode = function(input, maxline) { - return util3.binary.baseN.decode(input, _base58, maxline); + util4.binary.base58.decode = function(input, maxline) { + return util4.binary.baseN.decode(input, _base58, maxline); }; - util3.text = { + util4.text = { utf8: {}, utf16: {} }; - util3.text.utf8.encode = function(str, output, offset) { - str = util3.encodeUtf8(str); + util4.text.utf8.encode = function(str, output, offset) { + str = util4.encodeUtf8(str); var out = output; if (!out) { out = new Uint8Array(str.length); @@ -125384,10 +157517,10 @@ var require_util16 = __commonJS({ } return output ? j - offset : out; }; - util3.text.utf8.decode = function(bytes) { - return util3.decodeUtf8(String.fromCharCode.apply(null, bytes)); + util4.text.utf8.decode = function(bytes) { + return util4.decodeUtf8(String.fromCharCode.apply(null, bytes)); }; - util3.text.utf16.encode = function(str, output, offset) { + util4.text.utf16.encode = function(str, output, offset) { var out = output; if (!out) { out = new Uint8Array(str.length * 2); @@ -125402,11 +157535,11 @@ var require_util16 = __commonJS({ } return output ? j - offset : out; }; - util3.text.utf16.decode = function(bytes) { + util4.text.utf16.decode = function(bytes) { return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); }; - util3.deflate = function(api, bytes, raw) { - bytes = util3.decode64(api.deflate(util3.encode64(bytes)).rval); + util4.deflate = function(api, bytes, raw) { + bytes = util4.decode64(api.deflate(util4.encode64(bytes)).rval); if (raw) { var start = 2; var flg = bytes.charCodeAt(1); @@ -125417,9 +157550,9 @@ var require_util16 = __commonJS({ } return bytes; }; - util3.inflate = function(api, bytes, raw) { - var rval = api.inflate(util3.encode64(bytes)).rval; - return rval === null ? null : util3.decode64(rval); + util4.inflate = function(api, bytes, raw) { + var rval = api.inflate(util4.encode64(bytes)).rval; + return rval === null ? null : util4.decode64(rval); }; var _setStorageObject = function(api, id, obj) { if (!api) { @@ -125429,7 +157562,7 @@ var require_util16 = __commonJS({ if (obj === null) { rval = api.removeItem(id); } else { - obj = util3.encode64(JSON.stringify(obj)); + obj = util4.encode64(JSON.stringify(obj)); rval = api.setItem(id, obj); } if (typeof rval !== "undefined" && rval.rval !== true) { @@ -125458,7 +157591,7 @@ var require_util16 = __commonJS({ } } if (rval !== null) { - rval = JSON.parse(util3.decode64(rval)); + rval = JSON.parse(util4.decode64(rval)); } return rval; }; @@ -125530,19 +157663,19 @@ var require_util16 = __commonJS({ } return rval; }; - util3.setItem = function(api, id, key, data, location) { + util4.setItem = function(api, id, key, data, location) { _callStorageFunction(_setItem, arguments, location); }; - util3.getItem = function(api, id, key, location) { + util4.getItem = function(api, id, key, location) { return _callStorageFunction(_getItem, arguments, location); }; - util3.removeItem = function(api, id, key, location) { + util4.removeItem = function(api, id, key, location) { _callStorageFunction(_removeItem, arguments, location); }; - util3.clearItems = function(api, id, location) { + util4.clearItems = function(api, id, location) { _callStorageFunction(_clearItems, arguments, location); }; - util3.isEmpty = function(obj) { + util4.isEmpty = function(obj) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) { return false; @@ -125550,7 +157683,7 @@ var require_util16 = __commonJS({ } return true; }; - util3.format = function(format) { + util4.format = function(format) { var re = /%./g; var match2; var part; @@ -125586,7 +157719,7 @@ var require_util16 = __commonJS({ parts.push(format.substring(last)); return parts.join(""); }; - util3.formatNumber = function(number2, decimals, dec_point, thousands_sep) { + util4.formatNumber = function(number2, decimals, dec_point, thousands_sep) { var n = number2, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; var d = dec_point === void 0 ? "," : dec_point; var t = thousands_sep === void 0 ? "." : thousands_sep, s = n < 0 ? "-" : ""; @@ -125594,33 +157727,33 @@ var require_util16 = __commonJS({ var j = i.length > 3 ? i.length % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; - util3.formatSize = function(size) { + util4.formatSize = function(size) { if (size >= 1073741824) { - size = util3.formatNumber(size / 1073741824, 2, ".", "") + " GiB"; + size = util4.formatNumber(size / 1073741824, 2, ".", "") + " GiB"; } else if (size >= 1048576) { - size = util3.formatNumber(size / 1048576, 2, ".", "") + " MiB"; + size = util4.formatNumber(size / 1048576, 2, ".", "") + " MiB"; } else if (size >= 1024) { - size = util3.formatNumber(size / 1024, 0) + " KiB"; + size = util4.formatNumber(size / 1024, 0) + " KiB"; } else { - size = util3.formatNumber(size, 0) + " bytes"; + size = util4.formatNumber(size, 0) + " bytes"; } return size; }; - util3.bytesFromIP = function(ip) { + util4.bytesFromIP = function(ip) { if (ip.indexOf(".") !== -1) { - return util3.bytesFromIPv4(ip); + return util4.bytesFromIPv4(ip); } if (ip.indexOf(":") !== -1) { - return util3.bytesFromIPv6(ip); + return util4.bytesFromIPv6(ip); } return null; }; - util3.bytesFromIPv4 = function(ip) { + util4.bytesFromIPv4 = function(ip) { ip = ip.split("."); if (ip.length !== 4) { return null; } - var b = util3.createBuffer(); + var b = util4.createBuffer(); for (var i = 0; i < ip.length; ++i) { var num = parseInt(ip[i], 10); if (isNaN(num)) { @@ -125630,21 +157763,21 @@ var require_util16 = __commonJS({ } return b.getBytes(); }; - util3.bytesFromIPv6 = function(ip) { + util4.bytesFromIPv6 = function(ip) { var blanks = 0; ip = ip.split(":").filter(function(e) { if (e.length === 0) ++blanks; return true; }); var zeros = (8 - ip.length + blanks) * 2; - var b = util3.createBuffer(); + var b = util4.createBuffer(); for (var i = 0; i < 8; ++i) { if (!ip[i] || ip[i].length === 0) { b.fillWithByte(0, zeros); zeros = 0; continue; } - var bytes = util3.hexToBytes(ip[i]); + var bytes = util4.hexToBytes(ip[i]); if (bytes.length < 2) { b.putByte(0); } @@ -125652,16 +157785,16 @@ var require_util16 = __commonJS({ } return b.getBytes(); }; - util3.bytesToIP = function(bytes) { + util4.bytesToIP = function(bytes) { if (bytes.length === 4) { - return util3.bytesToIPv4(bytes); + return util4.bytesToIPv4(bytes); } if (bytes.length === 16) { - return util3.bytesToIPv6(bytes); + return util4.bytesToIPv6(bytes); } return null; }; - util3.bytesToIPv4 = function(bytes) { + util4.bytesToIPv4 = function(bytes) { if (bytes.length !== 4) { return null; } @@ -125671,7 +157804,7 @@ var require_util16 = __commonJS({ } return ip.join("."); }; - util3.bytesToIPv6 = function(bytes) { + util4.bytesToIPv6 = function(bytes) { if (bytes.length !== 16) { return null; } @@ -125679,7 +157812,7 @@ var require_util16 = __commonJS({ var zeroGroups = []; var zeroMaxGroup = 0; for (var i = 0; i < bytes.length; i += 2) { - var hex = util3.bytesToHex(bytes[i] + bytes[i + 1]); + var hex = util4.bytesToHex(bytes[i] + bytes[i + 1]); while (hex[0] === "0" && hex !== "0") { hex = hex.substr(1); } @@ -125711,26 +157844,26 @@ var require_util16 = __commonJS({ } return ip.join(":"); }; - util3.estimateCores = function(options, callback) { + util4.estimateCores = function(options, callback) { if (typeof options === "function") { callback = options; options = {}; } options = options || {}; - if ("cores" in util3 && !options.update) { - return callback(null, util3.cores); + if ("cores" in util4 && !options.update) { + return callback(null, util4.cores); } if (typeof navigator !== "undefined" && "hardwareConcurrency" in navigator && navigator.hardwareConcurrency > 0) { - util3.cores = navigator.hardwareConcurrency; - return callback(null, util3.cores); + util4.cores = navigator.hardwareConcurrency; + return callback(null, util4.cores); } if (typeof Worker === "undefined") { - util3.cores = 1; - return callback(null, util3.cores); + util4.cores = 1; + return callback(null, util4.cores); } if (typeof Blob === "undefined") { - util3.cores = 2; - return callback(null, util3.cores); + util4.cores = 2; + return callback(null, util4.cores); } var blobUrl = URL.createObjectURL(new Blob([ "(", @@ -125750,9 +157883,9 @@ var require_util16 = __commonJS({ var avg = Math.floor(max.reduce(function(avg2, x) { return avg2 + x; }, 0) / max.length); - util3.cores = Math.max(1, avg); + util4.cores = Math.max(1, avg); URL.revokeObjectURL(blobUrl); - return callback(null, util3.cores); + return callback(null, util4.cores); } map(numWorkers, function(err, results) { max.push(reduce(numWorkers, results)); @@ -125806,7 +157939,7 @@ var require_util16 = __commonJS({ var require_cipher = __commonJS({ "node_modules/node-forge/lib/cipher.js"(exports2, module2) { var forge = require_forge(); - require_util16(); + require_util14(); module2.exports = forge.cipher = forge.cipher || {}; forge.cipher.algorithms = forge.cipher.algorithms || {}; forge.cipher.createCipher = function(algorithm, key) { @@ -125923,7 +158056,7 @@ var require_cipher = __commonJS({ var require_cipherModes = __commonJS({ "node_modules/node-forge/lib/cipherModes.js"(exports2, module2) { var forge = require_forge(); - require_util16(); + require_util14(); forge.cipher = forge.cipher || {}; var modes = module2.exports = forge.cipher.modes = forge.cipher.modes || {}; modes.ecb = function(options) { @@ -125971,10 +158104,18 @@ var require_cipherModes = __commonJS({ return false; } var len = output.length(); + if (len === 0) { + return true; + } var count = output.at(len - 1); - if (count > this.blockSize << 2) { + if (count === 0 || count > this.blockSize || count > len) { return false; } + for (var i = 2; i <= count; ++i) { + if (output.at(len - i) !== count) { + return false; + } + } output.truncate(count); return true; }; @@ -126036,10 +158177,18 @@ var require_cipherModes = __commonJS({ return false; } var len = output.length(); + if (len === 0) { + return true; + } var count = output.at(len - 1); - if (count > this.blockSize << 2) { + if (count === 0 || count > this.blockSize || count > len) { return false; } + for (var i = 2; i <= count; ++i) { + if (output.at(len - i) !== count) { + return false; + } + } output.truncate(count); return true; }; @@ -126297,11 +158446,14 @@ var require_cipherModes = __commonJS({ } else { additionalData = forge.util.createBuffer(); } - if ("tagLength" in options) { - this._tagLength = options.tagLength; + if (options.tagLength !== void 0 && options.tagLength !== null) { + this._tagLength = Number(options.tagLength); } else { this._tagLength = 128; } + if ([128, 120, 112, 104, 96, 64, 32].indexOf(this._tagLength) === -1) { + throw new Error("Invalid tag length."); + } this._tag = null; if (options.decrypt) { this._tag = forge.util.createBuffer(options.tag).getBytes(); @@ -126495,11 +158647,11 @@ var require_cipherModes = __commonJS({ var size = 16 * multiplier; var m = new Array(size); for (var i = 0; i < size; ++i) { - var tmp = [0, 0, 0, 0]; + var tmp2 = [0, 0, 0, 0]; var idx = i / perInt | 0; var shft = (perInt - 1 - i % perInt) * bits; - tmp[idx] = 1 << bits - 1 << shft; - m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); + tmp2[idx] = 1 << bits - 1 << shft; + m[i] = this.generateSubHashTable(this.multiply(tmp2, h), bits); } return m; }; @@ -126539,10 +158691,10 @@ var require_cipherModes = __commonJS({ iv = forge.util.createBuffer(iv); } if (forge.util.isArray(iv) && iv.length > 4) { - var tmp = iv; + var tmp2 = iv; iv = forge.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - iv.putByte(tmp[i]); + for (var i = 0; i < tmp2.length; ++i) { + iv.putByte(tmp2[i]); } } if (iv.length() < blockSize) { @@ -126575,7 +158727,7 @@ var require_aes = __commonJS({ var forge = require_forge(); require_cipher(); require_cipherModes(); - require_util16(); + require_util14(); module2.exports = forge.aes = forge.aes || {}; forge.aes.startEncrypting = function(key, iv, output, mode) { var cipher = _createCipher({ @@ -126637,24 +158789,24 @@ var require_aes = __commonJS({ return; } var key = options.key; - var tmp; + var tmp2; if (typeof key === "string" && (key.length === 16 || key.length === 24 || key.length === 32)) { key = forge.util.createBuffer(key); } else if (forge.util.isArray(key) && (key.length === 16 || key.length === 24 || key.length === 32)) { - tmp = key; + tmp2 = key; key = forge.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); + for (var i = 0; i < tmp2.length; ++i) { + key.putByte(tmp2[i]); } } if (!forge.util.isArray(key)) { - tmp = key; + tmp2 = key; key = []; - var len = tmp.length(); + var len = tmp2.length(); if (len === 16 || len === 24 || len === 32) { len = len >>> 2; for (var i = 0; i < len; ++i) { - key.push(tmp.getInt32()); + key.push(tmp2.getInt32()); } } } @@ -126757,7 +158909,7 @@ var require_aes = __commonJS({ w[i] = w[i - Nk] ^ temp; } if (decrypt) { - var tmp; + var tmp2; var m0 = imix[0]; var m1 = imix[1]; var m2 = imix[2]; @@ -126772,8 +158924,8 @@ var require_aes = __commonJS({ wnew[i + 3] = w[wi + 1]; } else { for (var n = 0; n < Nb; ++n) { - tmp = w[wi + n]; - wnew[i + (3 & -n)] = m0[sbox[tmp >>> 24]] ^ m1[sbox[tmp >>> 16 & 255]] ^ m2[sbox[tmp >>> 8 & 255]] ^ m3[sbox[tmp & 255]]; + tmp2 = w[wi + n]; + wnew[i + (3 & -n)] = m0[sbox[tmp2 >>> 24]] ^ m1[sbox[tmp2 >>> 16 & 255]] ^ m2[sbox[tmp2 >>> 8 & 255]] ^ m3[sbox[tmp2 & 255]]; } } } @@ -126993,7 +159145,7 @@ var require_oids = __commonJS({ var require_asn1 = __commonJS({ "node_modules/node-forge/lib/asn1.js"(exports2, module2) { var forge = require_forge(); - require_util16(); + require_util14(); require_oids(); var asn1 = module2.exports = forge.asn1 = forge.asn1 || {}; asn1.Class = { @@ -127028,13 +159180,13 @@ var require_asn1 = __commonJS({ asn1.maxDepth = 256; asn1.create = function(tagClass, type, constructed, value, options) { if (forge.util.isArray(value)) { - var tmp = []; + var tmp2 = []; for (var i = 0; i < value.length; ++i) { if (value[i] !== void 0) { - tmp.push(value[i]); + tmp2.push(value[i]); } } - value = tmp; + value = tmp2; } var obj = { tagClass, @@ -127252,7 +159404,10 @@ var require_asn1 = __commonJS({ var subOptions = { // enforce strict mode to avoid parsing ASN.1 from plain data strict: true, - decodeBitStrings: true + // only decode one level of BIT STRINGs, nested decoding has + // quadratic cost due to copies for change detection + decodeBitStrings: false, + maxDepth: options.maxDepth }; var composed = _fromDer(bytes, remaining, depth + 1, subOptions); var used = start - bytes.length(); @@ -127356,12 +159511,16 @@ var require_asn1 = __commonJS({ asn1.oidToDer = function(oid) { var values = oid.split("."); var bytes = forge.util.createBuffer(); - bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); + var first = parseInt(values[0], 10); + var second = parseInt(values[1], 10); + if (!(first >= 0 && first <= 2 && second >= 0) || first < 2 && second > 39) { + throw new Error("Invalid OID; the first two arcs are out of range."); + } var last, valueBytes, value, b; - for (var i = 2; i < values.length; ++i) { + for (var i = 1; i < values.length; ++i) { last = true; valueBytes = []; - value = parseInt(values[i], 10); + value = i === 1 ? 40 * first + second : parseInt(values[i], 10); if (value > 4294967295) { throw new Error("OID value too large; max is 32-bits."); } @@ -127385,9 +159544,9 @@ var require_asn1 = __commonJS({ if (typeof bytes === "string") { bytes = forge.util.createBuffer(bytes); } - var b = bytes.getByte(); - oid = Math.floor(b / 40) + "." + b % 40; + var b; var value = 0; + var first = true; while (bytes.length() > 0) { if (value > 70368744177663) { throw new Error("OID value too large; max is 53-bits."); @@ -127397,7 +159556,13 @@ var require_asn1 = __commonJS({ if (b & 128) { value += b & 127; } else { - oid += "." + (value + b); + value += b; + if (first) { + oid = value < 80 ? Math.floor(value / 40) + "." + value % 40 : "2." + (value - 80); + first = false; + } else { + oid += "." + value; + } value = 0; } } @@ -127822,7 +159987,7 @@ var require_hmac = __commonJS({ "node_modules/node-forge/lib/hmac.js"(exports2, module2) { var forge = require_forge(); require_md(); - require_util16(); + require_util14(); var hmac = module2.exports = forge.hmac = forge.hmac || {}; hmac.create = function() { var _key = null; @@ -127849,10 +160014,10 @@ var require_hmac = __commonJS({ if (typeof key === "string") { key = forge.util.createBuffer(key); } else if (forge.util.isArray(key)) { - var tmp = key; + var tmp2 = key; key = forge.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); + for (var i = 0; i < tmp2.length; ++i) { + key.putByte(tmp2[i]); } } var keylen = key.length(); @@ -127865,13 +160030,13 @@ var require_hmac = __commonJS({ _opadding = forge.util.createBuffer(); keylen = key.length(); for (var i = 0; i < keylen; ++i) { - var tmp = key.at(i); - _ipadding.putByte(54 ^ tmp); - _opadding.putByte(92 ^ tmp); + var tmp2 = key.at(i); + _ipadding.putByte(54 ^ tmp2); + _opadding.putByte(92 ^ tmp2); } if (keylen < _md.blockLength) { - var tmp = _md.blockLength - keylen; - for (var i = 0; i < tmp; ++i) { + var tmp2 = _md.blockLength - keylen; + for (var i = 0; i < tmp2; ++i) { _ipadding.putByte(54); _opadding.putByte(92); } @@ -127904,7 +160069,7 @@ var require_md5 = __commonJS({ "node_modules/node-forge/lib/md5.js"(exports2, module2) { var forge = require_forge(); require_md(); - require_util16(); + require_util14(); var md5 = module2.exports = forge.md5 = forge.md5 || {}; forge.md.md5 = forge.md.algorithms.md5 = md5; md5.create = function() { @@ -127913,7 +160078,7 @@ var require_md5 = __commonJS({ } var _state = null; var _input = forge.util.createBuffer(); - var _w = new Array(16); + var _w2 = new Array(16); var md2 = { algorithm: "md5", blockLength: 64, @@ -127956,7 +160121,7 @@ var require_md5 = __commonJS({ len[0] = len[1] / 4294967296 >>> 0; } _input.putBytes(msg); - _update(_state, _w, _input); + _update(_state, _w2, _input); if (_input.read > 2048 || _input.length() === 0) { _input.compact(); } @@ -127980,7 +160145,7 @@ var require_md5 = __commonJS({ h2: _state.h2, h3: _state.h3 }; - _update(s2, _w, finalBlock); + _update(s2, _w2, finalBlock); var rval = forge.util.createBuffer(); rval.putInt32Le(s2.h0); rval.putInt32Le(s2.h1); @@ -127991,14 +160156,14 @@ var require_md5 = __commonJS({ return md2; }; var _padding = null; - var _g = null; - var _r = null; - var _k = null; + var _g2 = null; + var _r2 = null; + var _k2 = null; var _initialized = false; function _init() { _padding = String.fromCharCode(128); _padding += forge.util.fillString(String.fromCharCode(0), 64); - _g = [ + _g2 = [ 0, 1, 2, @@ -128064,7 +160229,7 @@ var require_md5 = __commonJS({ 2, 9 ]; - _r = [ + _r2 = [ 7, 12, 17, @@ -128130,9 +160295,9 @@ var require_md5 = __commonJS({ 15, 21 ]; - _k = new Array(64); + _k2 = new Array(64); for (var i = 0; i < 64; ++i) { - _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296); + _k2[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296); } _initialized = true; } @@ -128147,8 +160312,8 @@ var require_md5 = __commonJS({ for (i = 0; i < 16; ++i) { w[i] = bytes.getInt32Le(); f = d ^ b & (c ^ d); - t = a + f + _k[i] + w[i]; - r = _r[i]; + t = a + f + _k2[i] + w[i]; + r = _r2[i]; a = d; d = c; c = b; @@ -128156,8 +160321,8 @@ var require_md5 = __commonJS({ } for (; i < 32; ++i) { f = c ^ d & (b ^ c); - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; + t = a + f + _k2[i] + w[_g2[i]]; + r = _r2[i]; a = d; d = c; c = b; @@ -128165,8 +160330,8 @@ var require_md5 = __commonJS({ } for (; i < 48; ++i) { f = b ^ c ^ d; - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; + t = a + f + _k2[i] + w[_g2[i]]; + r = _r2[i]; a = d; d = c; c = b; @@ -128174,8 +160339,8 @@ var require_md5 = __commonJS({ } for (; i < 64; ++i) { f = c ^ (b | ~d); - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; + t = a + f + _k2[i] + w[_g2[i]]; + r = _r2[i]; a = d; d = c; c = b; @@ -128195,7 +160360,7 @@ var require_md5 = __commonJS({ var require_pem = __commonJS({ "node_modules/node-forge/lib/pem.js"(exports2, module2) { var forge = require_forge(); - require_util16(); + require_util14(); var pem = module2.exports = forge.pem = forge.pem || {}; pem.encode = function(msg, options) { options = options || {}; @@ -128233,12 +160398,12 @@ var require_pem = __commonJS({ }; pem.decode = function(str) { var rval = []; - var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; - var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; + var messages = _pemMessageScanner(str); + var rHeader = /(?:^|[^\x21-\x7e])([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; var rCRLF = /\r?\n/; var match2; while (true) { - match2 = rMessage.exec(str); + match2 = messages.next(); if (!match2) { break; } @@ -128261,7 +160426,7 @@ var require_pem = __commonJS({ var lines = match2[2].split(rCRLF); var li = 0; while (match2 && li < lines.length) { - var line = lines[li].replace(/\s+$/, ""); + var line = rtrim(lines[li]); for (var nl = li + 1; nl < lines.length; ++nl) { var next = lines[nl]; if (!/\s/.test(next[0])) { @@ -128339,6 +160504,140 @@ var require_pem = __commonJS({ function ltrim(str) { return str.replace(/^\s+/, ""); } + function rtrim(str) { + var end = str.length; + while (end > 0 && /\s/.test(str.charAt(end - 1))) { + --end; + } + return str.substring(0, end); + } + function _pemMessageScanner(str) { + var rBody = /[:A-Za-z0-9+\/=\s]/; + var rNotBody = /[^:A-Za-z0-9+\/=\s]/g; + var rNotHeader = /[^\x21-\x7e\s]/g; + var rLabel = /[A-Z0-9- ]/; + function indexOfRegex(regex, i) { + regex.lastIndex = i; + var match2 = regex.exec(str); + return match2 ? match2.index : str.length; + } + function labelAt(i) { + for (var j = i; j < str.length && rLabel.test(str.charAt(j)); ++j) { + if (j > i && str.substr(j, 5) === "-----") { + return str.substring(i, j); + } + } + return null; + } + function blankLineEnd(i) { + if (str.charAt(i) === "\r") { + ++i; + } + if (str.charAt(i) !== "\n") { + return -1; + } + if (str.charAt(++i) === "\r") { + ++i; + } + return str.charAt(i) === "\n" ? i + 1 : -1; + } + function firstBlankLine(start2, end2) { + for (var i = start2; i < end2; ++i) { + var v = blankLineEnd(i); + if (v !== -1 && v < end2) { + return i; + } + } + return -1; + } + var ends = {}; + for (var end = str.indexOf("-----END "); end !== -1; end = str.indexOf("-----END ", end + 1)) { + var endLabel = labelAt(end + 9); + var start = end; + while (start > 0 && rBody.test(str.charAt(start - 1))) { + --start; + } + var blank = firstBlankLine(start, end); + if (endLabel !== null && blank !== -1) { + var key = "$" + endLabel; + (ends[key] = ends[key] || []).push({ end, blank }); + } + } + var pos = 0; + var headerEnd = -1; + return { + next: function() { + var begin; + while ((begin = str.indexOf("-----BEGIN ", pos)) !== -1) { + pos = begin + 1; + var label = labelAt(begin + 11); + if (label === null) { + continue; + } + var q = begin + 16 + label.length; + var bodyEnd = indexOfRegex(rNotBody, q); + var bodyEndOk = str.substr(bodyEnd, 9) === "-----END " && labelAt(bodyEnd + 9) === label; + if (q > headerEnd) { + headerEnd = indexOfRegex(rNotHeader, q); + } + var later = null; + var list = ends["$" + label]; + if (list) { + var lo = 0; + var hi = list.length; + while (lo < hi) { + var mid = lo + hi >> 1; + if (list[mid].end > bodyEnd) { + hi = mid; + } else { + lo = mid + 1; + } + } + later = list[lo] || null; + } + var starts = []; + if (str.charAt(q) === "\r") { + if (str.charAt(q + 1) === "\n") { + starts.push(q + 2); + } + starts.push(q + 1); + } else if (str.charAt(q) === "\n") { + starts.push(q + 1); + } + starts.push(q); + for (var i = 0; i < starts.length; ++i) { + var t = starts[i]; + var blank2 = bodyEndOk ? firstBlankLine(t + 1, bodyEnd) : -1; + var end2 = bodyEnd; + if (blank2 === -1 && later) { + blank2 = later.blank; + end2 = later.end; + } + if (blank2 !== -1 && blank2 <= headerEnd) { + var v = blankLineEnd(blank2); + pos = end2 + 14 + label.length; + return [ + str.substring(begin, pos), + label, + str.substring(t, v), + str.substring(v, end2) + ]; + } + if (bodyEndOk && t < bodyEnd) { + pos = bodyEnd + 14 + label.length; + return [ + str.substring(begin, pos), + label, + void 0, + str.substring(t, bodyEnd) + ]; + } + } + } + return null; + } + }; + } } }); @@ -128348,7 +160647,7 @@ var require_des = __commonJS({ var forge = require_forge(); require_cipher(); require_cipherModes(); - require_util16(); + require_util14(); module2.exports = forge.des = forge.des || {}; forge.des.startEncrypting = function(key, iv, output, mode) { var cipher = _createCipher({ @@ -128444,34 +160743,34 @@ var require_des = __commonJS({ var iterations = key.length() > 8 ? 3 : 1; var keys = []; var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; - var n = 0, tmp; + var n = 0, tmp2; for (var j = 0; j < iterations; j++) { var left = key.getInt32(); var right = key.getInt32(); - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - tmp = (right >>> -16 ^ left) & 65535; - left ^= tmp; - right ^= tmp << -16; - tmp = (left >>> 2 ^ right) & 858993459; - right ^= tmp; - left ^= tmp << 2; - tmp = (right >>> -16 ^ left) & 65535; - left ^= tmp; - right ^= tmp << -16; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = left << 8 | right >>> 20 & 240; + tmp2 = (left >>> 4 ^ right) & 252645135; + right ^= tmp2; + left ^= tmp2 << 4; + tmp2 = (right >>> -16 ^ left) & 65535; + left ^= tmp2; + right ^= tmp2 << -16; + tmp2 = (left >>> 2 ^ right) & 858993459; + right ^= tmp2; + left ^= tmp2 << 2; + tmp2 = (right >>> -16 ^ left) & 65535; + left ^= tmp2; + right ^= tmp2 << -16; + tmp2 = (left >>> 1 ^ right) & 1431655765; + right ^= tmp2; + left ^= tmp2 << 1; + tmp2 = (right >>> 8 ^ left) & 16711935; + left ^= tmp2; + right ^= tmp2 << 8; + tmp2 = (left >>> 1 ^ right) & 1431655765; + right ^= tmp2; + left ^= tmp2 << 1; + tmp2 = left << 8 | right >>> 20 & 240; left = right << 24 | right << 8 & 16711680 | right >>> 8 & 65280 | right >>> 24 & 240; - right = tmp; + right = tmp2; for (var i = 0; i < shifts.length; ++i) { if (shifts[i]) { left = left << 2 | left >>> 26; @@ -128484,9 +160783,9 @@ var require_des = __commonJS({ right &= -15; var lefttmp = pc2bytes0[left >>> 28] | pc2bytes1[left >>> 24 & 15] | pc2bytes2[left >>> 20 & 15] | pc2bytes3[left >>> 16 & 15] | pc2bytes4[left >>> 12 & 15] | pc2bytes5[left >>> 8 & 15] | pc2bytes6[left >>> 4 & 15]; var righttmp = pc2bytes7[right >>> 28] | pc2bytes8[right >>> 24 & 15] | pc2bytes9[right >>> 20 & 15] | pc2bytes10[right >>> 16 & 15] | pc2bytes11[right >>> 12 & 15] | pc2bytes12[right >>> 8 & 15] | pc2bytes13[right >>> 4 & 15]; - tmp = (righttmp >>> 16 ^ lefttmp) & 65535; - keys[n++] = lefttmp ^ tmp; - keys[n++] = righttmp ^ tmp << 16; + tmp2 = (righttmp >>> 16 ^ lefttmp) & 65535; + keys[n++] = lefttmp ^ tmp2; + keys[n++] = righttmp ^ tmp2 << 16; } } return keys; @@ -128499,24 +160798,24 @@ var require_des = __commonJS({ } else { looping = decrypt ? [94, 62, -2, 32, 64, 2, 30, -2, -2] : [0, 32, 2, 62, 30, -2, 64, 96, 2]; } - var tmp; + var tmp2; var left = input[0]; var right = input[1]; - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - tmp = (left >>> 16 ^ right) & 65535; - right ^= tmp; - left ^= tmp << 16; - tmp = (right >>> 2 ^ left) & 858993459; - left ^= tmp; - right ^= tmp << 2; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; + tmp2 = (left >>> 4 ^ right) & 252645135; + right ^= tmp2; + left ^= tmp2 << 4; + tmp2 = (left >>> 16 ^ right) & 65535; + right ^= tmp2; + left ^= tmp2 << 16; + tmp2 = (right >>> 2 ^ left) & 858993459; + left ^= tmp2; + right ^= tmp2 << 2; + tmp2 = (right >>> 8 ^ left) & 16711935; + left ^= tmp2; + right ^= tmp2 << 8; + tmp2 = (left >>> 1 ^ right) & 1431655765; + right ^= tmp2; + left ^= tmp2 << 1; left = left << 1 | left >>> 31; right = right << 1 | right >>> 31; for (var j = 0; j < iterations; j += 3) { @@ -128525,31 +160824,31 @@ var require_des = __commonJS({ for (var i = looping[j]; i != endloop; i += loopinc) { var right1 = right ^ keys[i]; var right2 = (right >>> 4 | right << 28) ^ keys[i + 1]; - tmp = left; + tmp2 = left; left = right; - right = tmp ^ (spfunction2[right1 >>> 24 & 63] | spfunction4[right1 >>> 16 & 63] | spfunction6[right1 >>> 8 & 63] | spfunction8[right1 & 63] | spfunction1[right2 >>> 24 & 63] | spfunction3[right2 >>> 16 & 63] | spfunction5[right2 >>> 8 & 63] | spfunction7[right2 & 63]); + right = tmp2 ^ (spfunction2[right1 >>> 24 & 63] | spfunction4[right1 >>> 16 & 63] | spfunction6[right1 >>> 8 & 63] | spfunction8[right1 & 63] | spfunction1[right2 >>> 24 & 63] | spfunction3[right2 >>> 16 & 63] | spfunction5[right2 >>> 8 & 63] | spfunction7[right2 & 63]); } - tmp = left; + tmp2 = left; left = right; - right = tmp; + right = tmp2; } left = left >>> 1 | left << 31; right = right >>> 1 | right << 31; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (right >>> 2 ^ left) & 858993459; - left ^= tmp; - right ^= tmp << 2; - tmp = (left >>> 16 ^ right) & 65535; - right ^= tmp; - left ^= tmp << 16; - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; + tmp2 = (left >>> 1 ^ right) & 1431655765; + right ^= tmp2; + left ^= tmp2 << 1; + tmp2 = (right >>> 8 ^ left) & 16711935; + left ^= tmp2; + right ^= tmp2 << 8; + tmp2 = (right >>> 2 ^ left) & 858993459; + left ^= tmp2; + right ^= tmp2 << 2; + tmp2 = (left >>> 16 ^ right) & 65535; + right ^= tmp2; + left ^= tmp2 << 16; + tmp2 = (left >>> 4 ^ right) & 252645135; + right ^= tmp2; + left ^= tmp2 << 4; output[0] = left; output[1] = right; } @@ -128586,7 +160885,7 @@ var require_pbkdf2 = __commonJS({ var forge = require_forge(); require_hmac(); require_md(); - require_util16(); + require_util14(); var pkcs5 = forge.pkcs5 = forge.pkcs5 || {}; var crypto3; if (forge.util.isNodejs && !forge.options.usePureJavaScript) { @@ -128700,7 +160999,7 @@ var require_sha2562 = __commonJS({ "node_modules/node-forge/lib/sha256.js"(exports2, module2) { var forge = require_forge(); require_md(); - require_util16(); + require_util14(); var sha256 = module2.exports = forge.sha256 = forge.sha256 || {}; forge.md.sha256 = forge.md.algorithms.sha256 = sha256; sha256.create = function() { @@ -128709,7 +161008,7 @@ var require_sha2562 = __commonJS({ } var _state = null; var _input = forge.util.createBuffer(); - var _w = new Array(64); + var _w2 = new Array(64); var md2 = { algorithm: "sha256", blockLength: 64, @@ -128756,7 +161055,7 @@ var require_sha2562 = __commonJS({ len[0] = len[1] / 4294967296 >>> 0; } _input.putBytes(msg); - _update(_state, _w, _input); + _update(_state, _w2, _input); if (_input.read > 2048 || _input.length() === 0) { _input.compact(); } @@ -128788,7 +161087,7 @@ var require_sha2562 = __commonJS({ h6: _state.h6, h7: _state.h7 }; - _update(s2, _w, finalBlock); + _update(s2, _w2, finalBlock); var rval = forge.util.createBuffer(); rval.putInt32(s2.h0); rval.putInt32(s2.h1); @@ -128804,11 +161103,11 @@ var require_sha2562 = __commonJS({ }; var _padding = null; var _initialized = false; - var _k = null; + var _k2 = null; function _init() { _padding = String.fromCharCode(128); _padding += forge.util.fillString(String.fromCharCode(0), 64); - _k = [ + _k2 = [ 1116352408, 1899447441, 3049323471, @@ -128903,7 +161202,7 @@ var require_sha2562 = __commonJS({ ch = g ^ e & (f ^ g); s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); maj = a & b | c & (a ^ b); - t1 = h + s1 + ch + _k[i] + w[i]; + t1 = h + s1 + ch + _k2[i] + w[i]; t2 = s0 + maj; h = g; g = f; @@ -128932,7 +161231,7 @@ var require_sha2562 = __commonJS({ var require_prng = __commonJS({ "node_modules/node-forge/lib/prng.js"(exports2, module2) { var forge = require_forge(); - require_util16(); + require_util14(); var _crypto = null; if (forge.util.isNodejs && !forge.options.usePureJavaScript && !process.versions["node-webkit"]) { _crypto = require("crypto"); @@ -129175,7 +161474,7 @@ var require_random2 = __commonJS({ require_aes(); require_sha2562(); require_prng(); - require_util16(); + require_util14(); (function() { if (forge.random && forge.random.getBytes) { module2.exports = forge.random; @@ -129186,21 +161485,21 @@ var require_random2 = __commonJS({ var _prng_aes_output = new Array(4); var _prng_aes_buffer = forge.util.createBuffer(); prng_aes.formatKey = function(key2) { - var tmp = forge.util.createBuffer(key2); + var tmp2 = forge.util.createBuffer(key2); key2 = new Array(4); - key2[0] = tmp.getInt32(); - key2[1] = tmp.getInt32(); - key2[2] = tmp.getInt32(); - key2[3] = tmp.getInt32(); + key2[0] = tmp2.getInt32(); + key2[1] = tmp2.getInt32(); + key2[2] = tmp2.getInt32(); + key2[3] = tmp2.getInt32(); return forge.aes._expandKey(key2, false); }; prng_aes.formatSeed = function(seed) { - var tmp = forge.util.createBuffer(seed); + var tmp2 = forge.util.createBuffer(seed); seed = new Array(4); - seed[0] = tmp.getInt32(); - seed[1] = tmp.getInt32(); - seed[2] = tmp.getInt32(); - seed[3] = tmp.getInt32(); + seed[0] = tmp2.getInt32(); + seed[1] = tmp2.getInt32(); + seed[2] = tmp2.getInt32(); + seed[3] = tmp2.getInt32(); return seed; }; prng_aes.cipher = function(key2, seed) { @@ -129280,7 +161579,7 @@ var require_random2 = __commonJS({ var require_rc2 = __commonJS({ "node_modules/node-forge/lib/rc2.js"(exports2, module2) { var forge = require_forge(); - require_util16(); + require_util14(); var piTable = [ 217, 120, @@ -130776,7 +163075,7 @@ var require_jsbn = __commonJS({ return r; } function bnModInverse(m) { - if (this.signum() == 0) { + if (this.signum() <= 0 || m.signum() <= 0) { return BigInteger.ZERO; } var ac = m.isEven(); @@ -130930,7 +163229,7 @@ var require_sha1 = __commonJS({ "node_modules/node-forge/lib/sha1.js"(exports2, module2) { var forge = require_forge(); require_md(); - require_util16(); + require_util14(); var sha1 = module2.exports = forge.sha1 = forge.sha1 || {}; forge.md.sha1 = forge.md.algorithms.sha1 = sha1; sha1.create = function() { @@ -130939,7 +163238,7 @@ var require_sha1 = __commonJS({ } var _state = null; var _input = forge.util.createBuffer(); - var _w = new Array(80); + var _w2 = new Array(80); var md2 = { algorithm: "sha1", blockLength: 64, @@ -130983,7 +163282,7 @@ var require_sha1 = __commonJS({ len[0] = len[1] / 4294967296 >>> 0; } _input.putBytes(msg); - _update(_state, _w, _input); + _update(_state, _w2, _input); if (_input.read > 2048 || _input.length() === 0) { _input.compact(); } @@ -131012,7 +163311,7 @@ var require_sha1 = __commonJS({ h3: _state.h3, h4: _state.h4 }; - _update(s2, _w, finalBlock); + _update(s2, _w2, finalBlock); var rval = forge.util.createBuffer(); rval.putInt32(s2.h0); rval.putInt32(s2.h1); @@ -131125,7 +163424,7 @@ var require_sha1 = __commonJS({ var require_pkcs1 = __commonJS({ "node_modules/node-forge/lib/pkcs1.js"(exports2, module2) { var forge = require_forge(); - require_util16(); + require_util14(); require_random2(); require_sha1(); var pkcs1 = module2.exports = forge.pkcs1 = forge.pkcs1 || {}; @@ -131277,7 +163576,7 @@ var require_pkcs1 = __commonJS({ var require_prime = __commonJS({ "node_modules/node-forge/lib/prime.js"(exports2, module2) { var forge = require_forge(); - require_util16(); + require_util14(); require_jsbn(); require_random2(); (function() { @@ -131445,14 +163744,14 @@ var require_rsa = __commonJS({ require_pkcs1(); require_prime(); require_random2(); - require_util16(); + require_util14(); if (typeof BigInteger === "undefined") { BigInteger = forge.jsbn.BigInteger; } var BigInteger; var _crypto = forge.util.isNodejs ? require("crypto") : null; var asn1 = forge.asn1; - var util3 = forge.util; + var util4 = forge.util; forge.pki = forge.pki || {}; module2.exports = forge.pki.rsa = forge.rsa = forge.rsa || {}; var pki2 = forge.pki; @@ -131655,6 +163954,41 @@ var require_rsa = __commonJS({ capture: "digest" }] }; + var _encodeDigestInfo = function(oid, digest, withParameters) { + var digestAlgorithm = [asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(oid).getBytes() + )]; + if (withParameters) { + digestAlgorithm.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.NULL, + false, + "" + )); + } + return asn1.toDer(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + digestAlgorithm + ), + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + digest + ) + ] + )).getBytes(); + }; var emsaPkcs1v15encode = function(md2) { var oid; if (md2.algorithm in pki2.oids) { @@ -131992,13 +164326,13 @@ var require_rsa = __commonJS({ }); } if (_detectSubtleCrypto("generateKey") && _detectSubtleCrypto("exportKey")) { - return util3.globalScope.crypto.subtle.generateKey({ + return util4.globalScope.crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: bits, publicExponent: _intToUint8Array(e), hash: { name: "SHA-256" } }, true, ["sign", "verify"]).then(function(pair) { - return util3.globalScope.crypto.subtle.exportKey( + return util4.globalScope.crypto.subtle.exportKey( "pkcs8", pair.privateKey ); @@ -132017,7 +164351,7 @@ var require_rsa = __commonJS({ }); } if (_detectSubtleMsCrypto("generateKey") && _detectSubtleMsCrypto("exportKey")) { - var genOp = util3.globalScope.msCrypto.subtle.generateKey({ + var genOp = util4.globalScope.msCrypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: bits, publicExponent: _intToUint8Array(e), @@ -132025,7 +164359,7 @@ var require_rsa = __commonJS({ }, true, ["sign", "verify"]); genOp.oncomplete = function(e2) { var pair = e2.target.result; - var exportOp = util3.globalScope.msCrypto.subtle.exportKey( + var exportOp = util4.globalScope.msCrypto.subtle.exportKey( "pkcs8", pair.privateKey ); @@ -132158,6 +164492,13 @@ var require_rsa = __commonJS({ ); } } + var withParameters = _encodeDigestInfo(oid, capture.digest, true); + var withoutParameters = _encodeDigestInfo(oid, capture.digest, false); + if (d2.substring(0, withParameters.length) !== withParameters && d2.substring(0, withoutParameters.length) !== withoutParameters) { + throw new Error( + "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value." + ); + } return digest2 === capture.digest; } }; @@ -132544,9 +164885,9 @@ var require_rsa = __commonJS({ } state.q = num; if (state.p.compareTo(state.q) < 0) { - var tmp = state.p; + var tmp2 = state.p; state.p = state.q; - state.q = tmp; + state.q = tmp2; } if (state.p.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) !== 0) { state.p = null; @@ -132620,10 +164961,10 @@ var require_rsa = __commonJS({ return forge.util.isNodejs && typeof _crypto[fn] === "function"; } function _detectSubtleCrypto(fn) { - return typeof util3.globalScope !== "undefined" && typeof util3.globalScope.crypto === "object" && typeof util3.globalScope.crypto.subtle === "object" && typeof util3.globalScope.crypto.subtle[fn] === "function"; + return typeof util4.globalScope !== "undefined" && typeof util4.globalScope.crypto === "object" && typeof util4.globalScope.crypto.subtle === "object" && typeof util4.globalScope.crypto.subtle[fn] === "function"; } function _detectSubtleMsCrypto(fn) { - return typeof util3.globalScope !== "undefined" && typeof util3.globalScope.msCrypto === "object" && typeof util3.globalScope.msCrypto.subtle === "object" && typeof util3.globalScope.msCrypto.subtle[fn] === "function"; + return typeof util4.globalScope !== "undefined" && typeof util4.globalScope.msCrypto === "object" && typeof util4.globalScope.msCrypto.subtle === "object" && typeof util4.globalScope.msCrypto.subtle[fn] === "function"; } function _intToUint8Array(x) { var bytes = forge.util.hexToBytes(x.toString(16)); @@ -132650,7 +164991,7 @@ var require_pbe = __commonJS({ require_random2(); require_rc2(); require_rsa(); - require_util16(); + require_util14(); if (typeof BigInteger === "undefined") { BigInteger = forge.jsbn.BigInteger; } @@ -133118,6 +165459,9 @@ var require_pbe = __commonJS({ }; pki2.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md2) { var j, l; + if (!(iter >= 1)) { + throw new Error("PKCS#12 key derivation iteration count must be >= 1."); + } if (typeof md2 === "undefined" || md2 === null) { if (!("sha1" in forge.md)) { throw new Error('"sha1" hash algorithm unavailable.'); @@ -133418,7 +165762,7 @@ var require_pkcs7asn1 = __commonJS({ "node_modules/node-forge/lib/pkcs7asn1.js"(exports2, module2) { var forge = require_forge(); require_asn1(); - require_util16(); + require_util14(); var asn1 = forge.asn1; var p7v = module2.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {}; forge.pkcs7 = forge.pkcs7 || {}; @@ -133718,7 +166062,7 @@ var require_pkcs7asn1 = __commonJS({ var require_mgf1 = __commonJS({ "node_modules/node-forge/lib/mgf1.js"(exports2, module2) { var forge = require_forge(); - require_util16(); + require_util14(); forge.mgf = forge.mgf || {}; var mgf1 = module2.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {}; mgf1.create = function(md2) { @@ -133764,7 +166108,7 @@ var require_pss = __commonJS({ "node_modules/node-forge/lib/pss.js"(exports2, module2) { var forge = require_forge(); require_random2(); - require_util16(); + require_util14(); var pss = module2.exports = forge.pss = forge.pss || {}; pss.create = function(options) { if (arguments.length === 3) { @@ -133891,7 +166235,7 @@ var require_x509 = __commonJS({ require_pem(); require_pss(); require_rsa(); - require_util16(); + require_util14(); var asn1 = forge.asn1; var pki2 = module2.exports = forge.pki = forge.pki || {}; var oids = pki2.oids; @@ -134403,6 +166747,7 @@ var require_x509 = __commonJS({ }; var _verifySignature = function(options) { var cert = options.certificate; + var publicKey = options.publicKey || cert.publicKey; var scheme; switch (cert.signatureOid) { case oids.sha1WithRSAEncryption: @@ -134440,7 +166785,7 @@ var require_x509 = __commonJS({ ); break; } - return cert.publicKey.verify( + return publicKey.verify( options.md.digest().getBytes(), options.signature, scheme @@ -134660,7 +167005,8 @@ var require_x509 = __commonJS({ } if (md2 !== null) { rval = _verifySignature({ - certificate: cert, + certificate: child, + publicKey: cert.publicKey, md: md2, signature: child.signature }); @@ -135753,12 +168099,12 @@ var require_x509 = __commonJS({ ensureSubjectHasHash(cert2.subject); if (!caStore.hasCertificate(cert2)) { if (cert2.subject.hash in caStore.certs) { - var tmp = caStore.certs[cert2.subject.hash]; - if (!forge.util.isArray(tmp)) { - tmp = [tmp]; + var tmp2 = caStore.certs[cert2.subject.hash]; + if (!forge.util.isArray(tmp2)) { + tmp2 = [tmp2]; } - tmp.push(cert2); - caStore.certs[cert2.subject.hash] = tmp; + tmp2.push(cert2); + caStore.certs[cert2.subject.hash] = tmp2; } else { caStore.certs[cert2.subject.hash] = cert2; } @@ -135895,10 +168241,7 @@ var require_x509 = __commonJS({ } } if (parent) { - var parents = parent; - if (!forge.util.isArray(parents)) { - parents = [parents]; - } + var parents = forge.util.isArray(parent) ? parent.slice() : [parent]; var verified = false; while (!verified && parents.length > 0) { parent = parents.shift(); @@ -135943,7 +168286,7 @@ var require_x509 = __commonJS({ } } if (error3 === null && (!first || chain.length === 0 && (!parent || selfSigned))) { - var bcExt = cert.getExtension("basicConstraints"); + var bcExt = cert.getExtension({ id: "2.5.29.19" }); var keyUsageExt = cert.getExtension("keyUsage"); if (keyUsageExt !== null) { if (!keyUsageExt.keyCertSign || bcExt === null) { @@ -135965,7 +168308,7 @@ var require_x509 = __commonJS({ error: pki2.certificateError.bad_certificate }; } - if (error3 === null && keyUsageExt !== null && "pathLenConstraint" in bcExt) { + if (error3 === null && bcExt !== null && "pathLenConstraint" in bcExt) { var pathLen = depth - 1; if (pathLen > bcExt.pathLenConstraint) { error3 = { @@ -136020,7 +168363,7 @@ var require_pkcs12 = __commonJS({ require_random2(); require_rsa(); require_sha1(); - require_util16(); + require_util14(); require_x509(); var asn1 = forge.asn1; var pki2 = forge.pki; @@ -136349,6 +168692,9 @@ var require_pkcs12 = __commonJS({ } var macSalt = new forge.util.ByteBuffer(capture.macSalt); var macIterations = "macIterations" in capture ? parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1; + if (!(macIterations >= 1)) { + throw new Error("PKCS#12 MAC iteration count must be >= 1."); + } var macKey = p12.generateKey( password, macSalt, @@ -136476,7 +168822,7 @@ var require_pkcs12 = __commonJS({ attributes: _decodeBagAttributes(capture.bagAttributes) }; res.push(bag); - var validator, decoder; + var validator, decoder2; var bagAsn1 = capture.bagValue.value[0]; switch (bag.type) { case pki2.oids.pkcs8ShroudedKeyBag: @@ -136498,7 +168844,7 @@ var require_pkcs12 = __commonJS({ /* Nothing more to do. */ case pki2.oids.certBag: validator = certBagValidator; - decoder = function() { + decoder2 = function() { if (asn1.derToOid(capture.certId) !== pki2.oids.x509Certificate) { var error4 = new Error( "Unsupported certificate type, only X.509 supported." @@ -136525,7 +168871,7 @@ var require_pkcs12 = __commonJS({ error3.errors = errors; throw error3; } - decoder(); + decoder2(); } return res; } @@ -136883,7 +169229,7 @@ var require_pki = __commonJS({ require_pkcs12(); require_pss(); require_rsa(); - require_util16(); + require_util14(); require_x509(); var asn1 = forge.asn1; var pki2 = module2.exports = forge.pki = forge.pki || {}; @@ -136935,7 +169281,7 @@ var require_tls = __commonJS({ require_pki(); require_random2(); require_sha1(); - require_util16(); + require_util14(); var prf_TLS1 = function(secret, label, seed, length) { var rval = forge.util.createBuffer(); var idx = secret.length >> 1; @@ -137238,9 +169584,9 @@ var require_tls = __commonJS({ if (client) { c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite); } else { - var tmp = forge.util.createBuffer(msg.cipher_suites.bytes()); - while (tmp.length() > 0) { - c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2)); + var tmp2 = forge.util.createBuffer(msg.cipher_suites.bytes()); + while (tmp2.length() > 0) { + c.session.cipherSuite = tls.getCipherSuite(tmp2.getBytes(2)); if (c.session.cipherSuite !== null) { break; } @@ -137610,7 +169956,7 @@ var require_tls = __commonJS({ } }); } - if (c.serverCertificate === null) { + if (c.session.serverCertificate === null) { var error3 = { message: "No server certificate provided. Not enough security.", send: true, @@ -137634,8 +169980,8 @@ var require_tls = __commonJS({ error3.alert.description = ret; } } - return c.error(c, error3); } + return c.error(c, error3); } if (c.session.certificateRequest !== null) { record = tls.createRecord(c, { @@ -137891,7 +170237,7 @@ var require_tls = __commonJS({ var length = b.getInt16(); var payload = b.getBytes(length); if (type === tls.HeartbeatMessageType.heartbeat_request) { - if (c.handshaking || length > payload.length) { + if (c.handshakes === 0 || c.handshaking || length > payload.length) { return c.process(); } tls.queue(c, tls.createRecord(c, { @@ -138806,6 +171152,7 @@ var require_tls = __commonJS({ description: tls.Alert.Description.unexpected_message } }); + return rval; } } c2.record.ready = true; @@ -138870,24 +171217,48 @@ var require_tls = __commonJS({ tls.flush(c); } }; + var _processing = false; + var _processNext = false; + var _processRecord = function(c2) { + var rval = 0; + if (!c2.fail) { + if (c2.record !== null && c2.record.ready && c2.record.fragment.isEmpty()) { + c2.record = null; + } + if (c2.record === null) { + rval = _readRecordHeader(c2); + } + if (!c2.fail && c2.record !== null && !c2.record.ready) { + rval = _readRecord(c2); + } + if (!c2.fail && c2.record !== null && c2.record.ready) { + _update(c2, c2.record); + } + } + return rval; + }; c.process = function(data) { var rval = 0; if (data) { c.input.putBytes(data); } - if (!c.fail) { - if (c.record !== null && c.record.ready && c.record.fragment.isEmpty()) { - c.record = null; - } - if (c.record === null) { - rval = _readRecordHeader(c); - } - if (!c.fail && c.record !== null && !c.record.ready) { - rval = _readRecord(c); - } - if (!c.fail && c.record !== null && c.record.ready) { - _update(c, c.record); + if (_processing && typeof data === "undefined") { + _processNext = true; + return rval; + } + var processing = _processing; + var processNext = _processNext; + _processing = true; + _processNext = false; + try { + rval = _processRecord(c); + while (_processNext) { + _processNext = false; + _processRecord(c); } + } finally { + _processing = processing; + _processNext = processNext; } return rval; }; @@ -139106,7 +171477,7 @@ var require_sha512 = __commonJS({ "node_modules/node-forge/lib/sha512.js"(exports2, module2) { var forge = require_forge(); require_md(); - require_util16(); + require_util14(); var sha512 = module2.exports = forge.sha512 = forge.sha512 || {}; forge.md.sha512 = forge.md.algorithms.sha512 = sha512; var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {}; @@ -139137,11 +171508,11 @@ var require_sha512 = __commonJS({ throw new Error("Invalid SHA-512 algorithm: " + algorithm); } var _state = _states[algorithm]; - var _h = null; + var _h2 = null; var _input = forge.util.createBuffer(); - var _w = new Array(80); + var _w2 = new Array(80); for (var wi = 0; wi < 80; ++wi) { - _w[wi] = new Array(2); + _w2[wi] = new Array(2); } var digestLength = 64; switch (algorithm) { @@ -139175,9 +171546,9 @@ var require_sha512 = __commonJS({ md2.fullMessageLength.push(0); } _input = forge.util.createBuffer(); - _h = new Array(_state.length); + _h2 = new Array(_state.length); for (var i = 0; i < _state.length; ++i) { - _h[i] = _state[i].slice(0); + _h2[i] = _state[i].slice(0); } return md2; }; @@ -139196,7 +171567,7 @@ var require_sha512 = __commonJS({ len[0] = len[1] / 4294967296 >>> 0; } _input.putBytes(msg); - _update(_h, _w, _input); + _update(_h2, _w2, _input); if (_input.read > 2048 || _input.length() === 0) { _input.compact(); } @@ -139218,11 +171589,11 @@ var require_sha512 = __commonJS({ bits = next >>> 0; } finalBlock.putInt32(bits); - var h = new Array(_h.length); - for (var i = 0; i < _h.length; ++i) { - h[i] = _h[i].slice(0); + var h = new Array(_h2.length); + for (var i = 0; i < _h2.length; ++i) { + h[i] = _h2[i].slice(0); } - _update(h, _w, finalBlock); + _update(h, _w2, finalBlock); var rval = forge.util.createBuffer(); var hlen; if (algorithm === "SHA-512") { @@ -139244,12 +171615,12 @@ var require_sha512 = __commonJS({ }; var _padding = null; var _initialized = false; - var _k = null; + var _k2 = null; var _states = null; function _init() { _padding = String.fromCharCode(128); _padding += forge.util.fillString(String.fromCharCode(0), 128); - _k = [ + _k2 = [ [1116352408, 3609767458], [1899447441, 602891725], [3049323471, 3964484399], @@ -139454,8 +171825,8 @@ var require_sha512 = __commonJS({ (a_lo << 25 | a_hi >>> 7)) >>> 0; maj_hi = (a_hi & b_hi | c_hi & (a_hi ^ b_hi)) >>> 0; maj_lo = (a_lo & b_lo | c_lo & (a_lo ^ b_lo)) >>> 0; - lo = h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]; - t1_hi = h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + (lo / 4294967296 >>> 0) >>> 0; + lo = h_lo + s1_lo + ch_lo + _k2[i][1] + w[i][1]; + t1_hi = h_hi + s1_hi + ch_hi + _k2[i][0] + w[i][0] + (lo / 4294967296 >>> 0) >>> 0; t1_lo = lo >>> 0; lo = s0_lo + maj_lo; t2_hi = s0_hi + maj_hi + (lo / 4294967296 >>> 0) >>> 0; @@ -139608,7 +171979,7 @@ var require_ed25519 = __commonJS({ require_jsbn(); require_random2(); require_sha512(); - require_util16(); + require_util14(); var asn1Validator = require_asn1_validator(); var publicKeyValidator = asn1Validator.publicKeyValidator; var privateKeyValidator = asn1Validator.privateKeyValidator; @@ -139616,7 +171987,7 @@ var require_ed25519 = __commonJS({ BigInteger = forge.jsbn.BigInteger; } var BigInteger; - var ByteBuffer = forge.util.ByteBuffer; + var ByteBuffer8 = forge.util.ByteBuffer; var NativeBuffer = typeof Buffer === "undefined" ? Uint8Array : Buffer; forge.pki = forge.pki || {}; module2.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {}; @@ -139796,8 +172167,8 @@ var require_ed25519 = __commonJS({ if (typeof Buffer !== "undefined") { return Buffer.from(message, encoding); } - message = new ByteBuffer(message, encoding); - } else if (!(message instanceof ByteBuffer)) { + message = new ByteBuffer8(message, encoding); + } else if (!(message instanceof ByteBuffer8)) { throw new TypeError( '"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.' ); @@ -139936,7 +172307,7 @@ var require_ed25519 = __commonJS({ ]); function sha512(msg, msgLen) { var md2 = forge.md.sha512.create(); - var buffer = new ByteBuffer(msg); + var buffer = new ByteBuffer8(msg); md2.update(buffer.getBytes(msgLen), "binary"); var hash2 = md2.digest().getBytes(); if (typeof Buffer !== "undefined") { @@ -140718,7 +173089,7 @@ var require_ed25519 = __commonJS({ var require_kem = __commonJS({ "node_modules/node-forge/lib/kem.js"(exports2, module2) { var forge = require_forge(); - require_util16(); + require_util14(); require_random2(); require_jsbn(); module2.exports = forge.kem = forge.kem || {}; @@ -140781,7 +173152,7 @@ var require_kem = __commonJS({ var require_log7 = __commonJS({ "node_modules/node-forge/lib/log.js"(exports2, module2) { var forge = require_forge(); - require_util16(); + require_util14(); module2.exports = forge.log = forge.log || {}; forge.log.levels = [ "none", @@ -140810,13 +173181,13 @@ var require_log7 = __commonJS({ forge.log.logMessage = function(message) { var messageLevelIndex = sLevelInfo[message.level].index; for (var i2 = 0; i2 < sLoggers.length; ++i2) { - var logger2 = sLoggers[i2]; - if (logger2.flags & forge.log.NO_LEVEL_CHECK) { - logger2.f(message); + var logger3 = sLoggers[i2]; + if (logger3.flags & forge.log.NO_LEVEL_CHECK) { + logger3.f(message); } else { - var loggerLevelIndex = sLevelInfo[logger2.level].index; + var loggerLevelIndex = sLevelInfo[logger3.level].index; if (messageLevelIndex <= loggerLevelIndex) { - logger2.f(logger2, message); + logger3.f(logger3, message); } } } @@ -140864,20 +173235,20 @@ var require_log7 = __commonJS({ var levels; var i; forge.log.makeLogger = function(logFunction) { - var logger2 = { + var logger3 = { flags: 0, f: logFunction }; - forge.log.setLevel(logger2, "none"); - return logger2; + forge.log.setLevel(logger3, "none"); + return logger3; }; - forge.log.setLevel = function(logger2, level2) { + forge.log.setLevel = function(logger3, level2) { var rval = false; - if (logger2 && !(logger2.flags & forge.log.LEVEL_LOCKED)) { + if (logger3 && !(logger3.flags & forge.log.LEVEL_LOCKED)) { for (var i2 = 0; i2 < forge.log.levels.length; ++i2) { var aValidLevel = forge.log.levels[i2]; if (level2 == aValidLevel) { - logger2.level = level2; + logger3.level = level2; rval = true; break; } @@ -140885,15 +173256,15 @@ var require_log7 = __commonJS({ } return rval; }; - forge.log.lock = function(logger2, lock2) { + forge.log.lock = function(logger3, lock2) { if (typeof lock2 === "undefined" || lock2) { - logger2.flags |= forge.log.LEVEL_LOCKED; + logger3.flags |= forge.log.LEVEL_LOCKED; } else { - logger2.flags &= ~forge.log.LEVEL_LOCKED; + logger3.flags &= ~forge.log.LEVEL_LOCKED; } }; - forge.log.addLogger = function(logger2) { - sLoggers.push(logger2); + forge.log.addLogger = function(logger3) { + sLoggers.push(logger3); }; if (typeof console !== "undefined" && "log" in console) { if (console.error && console.warn && console.info && console.debug) { @@ -140904,31 +173275,31 @@ var require_log7 = __commonJS({ debug: console.debug, verbose: console.debug }; - f = function(logger2, message) { + f = function(logger3, message) { forge.log.prepareStandard(message); var handler2 = levelHandlers[message.level]; var args = [message.standard]; args = args.concat(message["arguments"].slice()); handler2.apply(console, args); }; - logger = forge.log.makeLogger(f); + logger2 = forge.log.makeLogger(f); } else { - f = function(logger2, message) { + f = function(logger3, message) { forge.log.prepareStandardFull(message); console.log(message.standardFull); }; - logger = forge.log.makeLogger(f); + logger2 = forge.log.makeLogger(f); } - forge.log.setLevel(logger, "debug"); - forge.log.addLogger(logger); - sConsoleLogger = logger; + forge.log.setLevel(logger2, "debug"); + forge.log.addLogger(logger2); + sConsoleLogger = logger2; } else { console = { log: function() { } }; } - var logger; + var logger2; var levelHandlers; var f; if (sConsoleLogger !== null && typeof window !== "undefined" && window.location) { @@ -140974,7 +173345,7 @@ var require_pkcs7 = __commonJS({ require_pem(); require_pkcs7asn1(); require_random2(); - require_util16(); + require_util14(); require_x509(); var asn1 = forge.asn1; var p7 = module2.exports = forge.pkcs7 = forge.pkcs7 || {}; @@ -141960,7 +174331,7 @@ var require_ssh = __commonJS({ require_hmac(); require_md5(); require_sha1(); - require_util16(); + require_util14(); var ssh = module2.exports = forge.ssh = forge.ssh || {}; ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { comment = comment || ""; @@ -142116,7 +174487,7 @@ var require_lib6 = __commonJS({ require_rc2(); require_ssh(); require_tls(); - require_util16(); + require_util14(); } }); @@ -142139,23 +174510,30 @@ __export(entry_points_exports, { module.exports = __toCommonJS(entry_points_exports); // src/analyze-action.ts -var fs23 = __toESM(require("fs")); +var fs25 = __toESM(require("fs")); var import_path5 = __toESM(require("path")); -var import_perf_hooks4 = require("perf_hooks"); -var core16 = __toESM(require_core()); +var import_perf_hooks6 = require("perf_hooks"); +var core14 = __toESM(require_core()); // src/action-common.ts -var core8 = __toESM(require_core()); +var os4 = __toESM(require("os")); +var core9 = __toESM(require_core()); // src/actions-util.ts var fs2 = __toESM(require("fs")); var path2 = __toESM(require("path")); -var core3 = __toESM(require_core()); +var core4 = __toESM(require_core()); var toolrunner = __toESM(require_toolrunner()); var github = __toESM(require_github()); var io2 = __toESM(require_io()); +// src/config/action-config.ts +function hasConfigKey(config, key) { + return config[key] !== void 0; +} + // src/environment.ts +var core = __toESM(require_core()); function getRequiredEnvVar(env, paramName) { const value = env[paramName]; if (value === void 0 || value.length === 0) { @@ -142189,6 +174567,17 @@ var ReadOnlyEnv = class { get() { return { ...this.vars }; } + /** Gets a copy of the underlying environment, where the values are not `undefined`. */ + getDefined() { + const result = {}; + for (const [key, val] of Object.entries(this.vars)) { + if (val === void 0) { + continue; + } + result[key] = val; + } + return result; + } /** Tries to get the value for `name` and throws if there isn't one. */ getRequired(name) { return getRequiredEnvVar(this.vars, name); @@ -142201,6 +174590,24 @@ var ReadOnlyEnv = class { entries() { return Object.entries(this.vars); } + /** + * Gets a value indicating whether we should skip uploads of + * all kinds (SARIF results, status reports, DBs, ...). + * + * This is not guaranteed to be set in all test environments. + */ + isSkippingUploadsInTests() { + return this.getOptional("CODEQL_ACTION_TEST_MODE" /* TEST_MODE */) === "true"; + } + /** + * Gets a value indicative of whether we are in a testing environment + * by testing whether the value of the `NODE_ENV` variable is "test". + * This is expected to be the case if e.g. `ava` is running the tests + * or if this instance was constructed by `getTestEnv`. + */ + isTestingEnv() { + return false; + } }; var Env = class extends ReadOnlyEnv { changed = false; @@ -142209,6 +174616,37 @@ var Env = class extends ReadOnlyEnv { this.vars[name] = value; this.changed = true; } + /** Sets all environment variables given by `vars`. */ + setAll(vars) { + for (const [key, val] of Object.entries(vars)) { + this.set(key, val); + } + } + /** + * Wrapper around `core.exportVariable` which does not call `core.exportVariable` + * when running unit tests. This is important, because otherwise `core.exportVariable` + * sets environment variables for other steps in a workflow when we run unit tests in CI. + * + * @param name The name of the environment variable to set and export. + * @param val The value to set and export for the environment variable. + */ + export(name, val) { + this.set(name, val); + if (!this.isTestingEnv()) { + core.exportVariable(name, val); + } + } + /** + * Set some initial environment variables that we can set even without + * knowing what version of CodeQL we're running. + */ + initialise(version) { + this.export("CODEQL_ACTION_FEATURE_MULTI_LANGUAGE" /* FEATURE_MULTI_LANGUAGE */, "false"); + this.export("CODEQL_ACTION_FEATURE_SANDWICH" /* FEATURE_SANDWICH */, "false"); + this.export("CODEQL_ACTION_FEATURE_SARIF_COMBINE" /* FEATURE_SARIF_COMBINE */, "true"); + this.export("CODEQL_ACTION_FEATURE_WILL_UPLOAD" /* FEATURE_WILL_UPLOAD */, "true"); + this.export("CODEQL_ACTION_VERSION" /* VERSION */, version); + } /** Gets a value indicating whether `set` was called at least once. */ hasChanged() { return this.changed; @@ -142217,38 +174655,50 @@ var Env = class extends ReadOnlyEnv { function getEnv(env = process.env) { return new Env(env); } +function isInTestMode() { + return getEnv().isSkippingUploadsInTests(); +} +function exportEnvVar(name, val) { + const env = getEnv(); + if (typeof val === "string") { + env.export(name, val); + } else { + env.export(name, JSON.stringify(val)); + } +} // src/util.ts var fs = __toESM(require("fs")); var fsPromises = __toESM(require("fs/promises")); var os = __toESM(require("os")); var path = __toESM(require("path")); -var core2 = __toESM(require_core()); +var import_perf_hooks = require("perf_hooks"); +var core3 = __toESM(require_core()); var io = __toESM(require_io()); // node_modules/get-folder-size/index.js var import_node_path = require("node:path"); async function getFolderSize(itemPath, options) { - return await core(itemPath, options, { errors: true }); + return await core2(itemPath, options, { errors: true }); } -getFolderSize.loose = async (itemPath, options) => await core(itemPath, options); -getFolderSize.strict = async (itemPath, options) => await core(itemPath, options, { strict: true }); -async function core(rootItemPath, options = {}, returnType = {}) { - const fs32 = options.fs || await import("node:fs/promises"); +getFolderSize.loose = async (itemPath, options) => await core2(itemPath, options); +getFolderSize.strict = async (itemPath, options) => await core2(itemPath, options, { strict: true }); +async function core2(rootItemPath, options = {}, returnType = {}) { + const fs34 = options.fs || await import("node:fs/promises"); let folderSize = 0n; const foundInos = /* @__PURE__ */ new Set(); const errors = []; await processItem(rootItemPath); async function processItem(itemPath) { if (options.ignore?.test(itemPath)) return; - const stats = returnType.strict ? await fs32.lstat(itemPath, { bigint: true }) : await fs32.lstat(itemPath, { bigint: true }).catch((error3) => errors.push(error3)); + const stats = returnType.strict ? await fs34.lstat(itemPath, { bigint: true }) : await fs34.lstat(itemPath, { bigint: true }).catch((error3) => errors.push(error3)); if (typeof stats !== "object") return; if (!foundInos.has(stats.ino)) { foundInos.add(stats.ino); folderSize += stats.size; } if (stats.isDirectory()) { - const directoryItems = returnType.strict ? await fs32.readdir(itemPath) : await fs32.readdir(itemPath).catch((error3) => errors.push(error3)); + const directoryItems = returnType.strict ? await fs34.readdir(itemPath) : await fs34.readdir(itemPath).catch((error3) => errors.push(error3)); if (typeof directoryItems !== "object") return; await Promise.all( directoryItems.map( @@ -142283,7 +174733,6 @@ async function core(rootItemPath, options = {}, returnType = {}) { // node_modules/js-yaml/dist/js-yaml.mjs var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED"); -var MERGE_KEY = /* @__PURE__ */ Symbol("MERGE_KEY"); function defineScalarTag(tagName, options) { return { tagName, @@ -142292,9 +174741,9 @@ function defineScalarTag(tagName, options) { matchByTagPrefix: options.matchByTagPrefix ?? false, implicitFirstChars: options.implicitFirstChars ?? null, resolve: options.resolve, - identify: options.identify ?? null, + identify: options.identify, represent: options.represent ?? ((data) => String(data)), - representTagName: options.representTagName ?? null + representTagName: options.representTagName ?? (() => tagName) }; } function defineSequenceTag(tagName, options) { @@ -142308,9 +174757,9 @@ function defineSequenceTag(tagName, options) { addItem: options.addItem, finalize: options.finalize ?? ((carrier) => carrier), carrierIsResult, - identify: options.identify ?? null, + identify: options.identify, represent: options.represent ?? ((data) => data), - representTagName: options.representTagName ?? null + representTagName: options.representTagName ?? (() => tagName) }; } function defineMappingTag(tagName, options) { @@ -142327,9 +174776,9 @@ function defineMappingTag(tagName, options) { get: options.get, finalize: options.finalize ?? ((carrier) => carrier), carrierIsResult, - identify: options.identify ?? null, + identify: options.identify, represent: options.represent ?? ((data) => data), - representTagName: options.representTagName ?? null + representTagName: options.representTagName ?? (() => tagName) }; } var strTag = defineScalarTag("tag:yaml.org,2002:str", { @@ -142678,9 +175127,10 @@ var mergeTag = defineScalarTag("tag:yaml.org,2002:merge", { implicit: true, implicitFirstChars: ["<"], resolve: (source, isExplicit) => { - if (source === "<<" || isExplicit && source === "") return MERGE_KEY; + if (source === "<<" || isExplicit && source === "") return "<<"; return NOT_RESOLVED; - } + }, + identify: () => false }); var BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/; function resolveYamlBinary(source) { @@ -142785,7 +175235,8 @@ var omapTag = defineSequenceTag("tag:yaml.org,2002:omap", { carrier.list.push(item); return ""; }, - finalize: (carrier) => carrier.list + finalize: (carrier) => carrier.list, + identify: () => false }); var pairsTag = defineSequenceTag("tag:yaml.org,2002:pairs", { create: () => [], @@ -142801,7 +175252,8 @@ var pairsTag = defineSequenceTag("tag:yaml.org,2002:pairs", { if (keys.length !== 1) return "cannot resolve a pairs item"; container.push([keys[0], object2[keys[0]]]); return ""; - } + }, + identify: () => false }); var mapTag = defineMappingTag("tag:yaml.org,2002:map", { create: () => ({}), @@ -142882,11 +175334,35 @@ function compileTags(tags) { } var Schema = class Schema2 { tags; + /** @internal */ implicitScalarTags; + /** + * Dispatch implicit scalar resolvers by `source.charAt(0)`. Each bucket holds + * the resolvers that may match that key, in schema order; a key absent from + * the map uses + * {@link Schema.implicitScalarAnyFirstChar} + * (resolvers that declared no first-char constraint, so they apply to any + * first character). + */ implicitScalarByFirstChar; implicitScalarAnyFirstChar; + /** + * The default scalar tag (`!!str`), resolved once so the composer's fallback + * for unresolved plain scalars avoids a keyed lookup per scalar. + * + * @internal + */ defaultScalarTag; + /** + * The default container tags (`!!seq` / `!!map`), used by the dumper: when a + * value is identified by its default tag, the tag is implicit and not + * printed. Undefined if the schema does not define them (then such values + * can't be dumped). + * + * @internal + */ defaultSequenceTag; + /** @internal */ defaultMappingTag; exact; prefix; @@ -142912,7 +175388,6 @@ var Schema = class Schema2 { case "mapping": if (tag.matchByTagPrefix) prefix.mapping.push(tag); else exact.mapping[tag.tagName] = tag; - break; } } const implicitScalarAnyFirstChar = implicitScalarTags.filter((tag) => tag.implicitFirstChars === null); @@ -142932,6 +175407,52 @@ var Schema = class Schema2 { this.exact = exact; this.prefix = prefix; } + /** @internal */ + lookupScalarTag(tagName) { + const exactTag = this.exact.scalar[tagName]; + if (exactTag) return exactTag; + for (const tag of this.prefix.scalar) if (tagName.startsWith(tag.tagName)) return tag; + } + /** @internal */ + lookupSequenceTag(tagName) { + const exactTag = this.exact.sequence[tagName]; + if (exactTag) return exactTag; + for (const tag of this.prefix.sequence) if (tagName.startsWith(tag.tagName)) return tag; + } + /** @internal */ + lookupMappingTag(tagName) { + const exactTag = this.exact.mapping[tagName]; + if (exactTag) return exactTag; + for (const tag of this.prefix.mapping) if (tagName.startsWith(tag.tagName)) return tag; + } + /** @internal */ + resolveImplicitScalarTag(source) { + const candidates = this.implicitScalarByFirstChar.get(source.charAt(0)) ?? this.implicitScalarAnyFirstChar; + for (const tag2 of candidates) { + const value = tag2.resolve(source, false, tag2.tagName); + if (value !== NOT_RESOLVED) return { + value, + tag: tag2 + }; + } + const tag = this.defaultScalarTag; + return { + value: tag.resolve(source, false, tag.tagName), + tag + }; + } + /** + * Creates a new schema with the specified tags added. If a tag already + * exists, it is replaced by the specified tag. + * + * @example + * + * ```javascript + * import { CORE_SCHEMA, mergeTag, realMapTag } from 'js-yaml' + * + * const schema = CORE_SCHEMA.withTags(mergeTag, realMapTag) + * ``` + */ withTags(...tags) { let flatTags = []; for (const tag of tags) flatTags = flatTags.concat(tag); @@ -142970,6 +175491,19 @@ var YAML11_SCHEMA = new Schema([ pairsTag, setTag ]); +var DUMP_SCHEMA = YAML11_SCHEMA.withTags({ + ...intYaml11Tag, + resolve: (source, isExplicit, tagName) => { + const result = intYaml11Tag.resolve(source, isExplicit, tagName); + return result === NOT_RESOLVED ? intCoreTag.resolve(source, isExplicit, tagName) : result; + } +}, { + ...floatYaml11Tag, + resolve: (source, isExplicit, tagName) => { + const result = floatYaml11Tag.resolve(source, isExplicit, tagName); + return result === NOT_RESOLVED ? floatCoreTag.resolve(source, isExplicit, tagName) : result; + } +}); var realMapTag = defineMappingTag("tag:yaml.org,2002:map", { create: () => /* @__PURE__ */ new Map(), addPair: (container, key, value) => { @@ -143106,9 +175640,13 @@ function formatError(exception, compact) { ${exception.mark.snippet}`; return `${exception.reason} ${where}`; } -var YAMLException = class extends Error { +var YAMLException = class YAMLException2 extends Error { reason; mark; + /** + * Optional `mark` contains source snippet data. Usually, use + * {@link YAMLException.throwAt} instead of passing it directly. + */ constructor(reason, mark) { super(); this.name = "YAMLException"; @@ -143117,34 +175655,65 @@ var YAMLException = class extends Error { this.message = formatError(this, false); if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor); } + /** + * Returns the formatted error, omitting the source snippet in compact mode. + */ toString(compact) { return `${this.name}: ${formatError(this, compact)}`; } -}; -function throwErrorAt(source, position, message, filename = "") { - let line = 0; - let lineStart = 0; - for (let index2 = 0; index2 < position; index2++) { - const ch = source.charCodeAt(index2); - if (ch === 10) { - line++; - lineStart = index2 + 1; - } else if (ch === 13) { - line++; - if (source.charCodeAt(index2 + 1) === 10) index2++; - lineStart = index2 + 1; - } + /** + * Builds a YAMLException with a source snippet and throws it. `source` is + * the raw input text; `position` is an offset into it. + */ + static throwAt(source, position, message, filename = "") { + let line = 0; + let lineStart = 0; + for (let index2 = 0; index2 < position; index2++) { + const ch = source.charCodeAt(index2); + if (ch === 10) { + line++; + lineStart = index2 + 1; + } else if (ch === 13) { + line++; + if (source.charCodeAt(index2 + 1) === 10) index2++; + lineStart = index2 + 1; + } + } + const mark = { + name: filename, + buffer: source, + position, + line, + column: position - lineStart + }; + mark.snippet = makeSnippet(mark); + throw new YAMLException2(message, mark); } - const mark = { - name: filename, - buffer: source, - position, - line, - column: position - lineStart - }; - mark.snippet = makeSnippet(mark); - throw new YAMLException(message, mark); -} +}; +var EVENT_ID = { + DOCUMENT: 1, + SEQUENCE: 2, + MAPPING: 3, + SCALAR: 4, + ALIAS: 5, + POP: 6 +}; +var SCALAR_STYLE = { + PLAIN: 1, + SINGLE_QUOTED: 2, + DOUBLE_QUOTED: 3, + LITERAL_BLOCK: 4, + FOLDED_BLOCK: 5 +}; +var COLLECTION_STYLE = { + BLOCK: 1, + FLOW: 2 +}; +var CHOMPING_MODE = { + CLIP: 1, + STRIP: 2, + KEEP: 3 +}; var NO_RANGE$3 = -1; function simpleEscapeSequence(c) { switch (c) { @@ -143328,22 +175897,23 @@ function getBlockValue(input, start, end, indent, chomping, folded) { } const content = line.slice(textIndent); const first = content.charCodeAt(0); - if (folded) if (first === 32 || first === 9) { - atMoreIndented = true; - result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines); - } else if (atMoreIndented) { - atMoreIndented = false; - result += "\n".repeat(emptyLines + 1); - } else if (emptyLines === 0) { - if (didReadContent) result += " "; - } else result += "\n".repeat(emptyLines); - else result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines); + if (folded) { + if (first === 32 || first === 9) { + atMoreIndented = true; + result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines); + } else if (atMoreIndented) { + atMoreIndented = false; + result += "\n".repeat(emptyLines + 1); + } else if (emptyLines === 0) { + if (didReadContent) result += " "; + } else result += "\n".repeat(emptyLines); + } else result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines); result += content; didReadContent = true; emptyLines = 0; } - if (chomping === 3) result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines); - else if (chomping !== 2) { + if (chomping === CHOMPING_MODE.KEEP) result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines); + else if (chomping !== CHOMPING_MODE.STRIP) { if (didReadContent) result += "\n"; } return result; @@ -143353,13 +175923,13 @@ function getScalarValue(input, scalar) { const { valueStart, valueEnd } = scalar; if (scalar.fast) return input.slice(valueStart, valueEnd); switch (scalar.style) { - case 2: + case SCALAR_STYLE.SINGLE_QUOTED: return getSingleQuotedValue(input, valueStart, valueEnd); - case 3: + case SCALAR_STYLE.DOUBLE_QUOTED: return getDoubleQuotedValue(input, valueStart, valueEnd); - case 4: + case SCALAR_STYLE.LITERAL_BLOCK: return getBlockValue(input, valueStart, valueEnd, scalar.indent, scalar.chomping, false); - case 5: + case SCALAR_STYLE.FOLDED_BLOCK: return getBlockValue(input, valueStart, valueEnd, scalar.indent, scalar.chomping, true); default: return getPlainValue(input, valueStart, valueEnd); @@ -143369,26 +175939,72 @@ var DEFAULT_TAG_HANDLERS = Object.assign(/* @__PURE__ */ Object.create(null), { "!": "!", "!!": "tag:yaml.org,2002:" }); -function tagPercentEncode(source) { - return encodeURI(source).replace(/!/g, "%21"); +var TAG_SUFFIX_CHARS = "-#;/?:@&=+$_.~*'()"; +var TAG_URI_CHARS = TAG_SUFFIX_CHARS + "!,[]"; +var HEX = "0123456789ABCDEF"; +function percentByte(byte) { + return "%" + HEX[byte >> 4] + HEX[byte & 15]; +} +function tagPercentEncode(source, isSuffix) { + const allowed = isSuffix ? TAG_SUFFIX_CHARS : TAG_URI_CHARS; + let result = ""; + for (let index2 = 0; index2 < source.length; index2++) { + let ch = source.charCodeAt(index2); + if (ch >= 48 && ch <= 57 || ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || allowed.includes(source[index2])) { + result += source[index2]; + continue; + } + if (ch >= 55296 && ch <= 56319) ch = 65536 + ((ch & 1023) << 10) + (source.charCodeAt(++index2) & 1023); + if (ch < 128) result += percentByte(ch); + else if (ch < 2048) result += percentByte(192 | ch >> 6) + percentByte(128 | ch & 63); + else if (ch < 65536) result += percentByte(224 | ch >> 12) + percentByte(128 | ch >> 6 & 63) + percentByte(128 | ch & 63); + else result += percentByte(240 | ch >> 18) + percentByte(128 | ch >> 12 & 63) + percentByte(128 | ch >> 6 & 63) + percentByte(128 | ch & 63); + } + return result; +} +function tagPercentDecode(source) { + let result = ""; + let index2 = 0; + while (index2 < source.length) { + if (source.charCodeAt(index2) !== 37) { + result += source[index2++]; + continue; + } + let ch = parseInt(source.slice(index2 + 1, index2 + 3), 16); + index2 += 3; + if (ch >= 192) { + let remaining = ch < 224 ? 1 : ch < 240 ? 2 : 3; + ch &= (1 << 6 - remaining) - 1; + while (remaining-- > 0) { + ch = ch << 6 | parseInt(source.slice(index2 + 1, index2 + 3), 16) & 63; + index2 += 3; + } + } + if (ch < 65536) result += String.fromCharCode(ch); + else { + ch -= 65536; + result += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023); + } + } + return result; } function tagNameFull(rawTag, tagHandlers) { - if (rawTag.startsWith("!<") && rawTag.endsWith(">")) return decodeURIComponent(rawTag.slice(2, -1)); + if (rawTag.startsWith("!<") && rawTag.endsWith(">")) return tagPercentDecode(rawTag.slice(2, -1)); const handleEnd = rawTag.indexOf("!", 1); const handle = handleEnd === -1 ? "!" : rawTag.slice(0, handleEnd + 1); - const prefix = tagHandlers?.[handle] ?? DEFAULT_TAG_HANDLERS[handle] ?? handle; - return decodeURIComponent(prefix) + decodeURIComponent(rawTag.slice(handle.length)); + return tagPercentDecode(tagHandlers?.[handle] ?? DEFAULT_TAG_HANDLERS[handle] ?? handle) + tagPercentDecode(rawTag.slice(handle.length)); } function tagNameShort(fullTag) { let tag = fullTag; if (tag.charCodeAt(0) === 33) { tag = tag.slice(1); - return `!${tagPercentEncode(tag)}`; + return `!${tagPercentEncode(tag, true)}`; } - if (tag.slice(0, 18) === "tag:yaml.org,2002:") return `!!${tagPercentEncode(tag.slice(18))}`; - return `!<${tagPercentEncode(tag)}>`; + if (tag.slice(0, 18) === "tag:yaml.org,2002:") return `!!${tagPercentEncode(tag.slice(18), true)}`; + return `!<${tagPercentEncode(tag, false)}>`; } var NO_RANGE$2 = -1; +var MERGE_TAG_NAME = "tag:yaml.org,2002:merge"; var DEFAULT_CONSTRUCTOR_OPTIONS = { filename: "", schema: CORE_SCHEMA, @@ -143404,26 +176020,16 @@ function eventPosition$1(event) { return 0; } function throwError$1(state, message) { - throwErrorAt(state.source, state.position, message, state.filename); + YAMLException.throwAt(state.source, state.position, message, state.filename); } function finalizeCollection(state, position, tag, carrier) { try { return tag.finalize(carrier); } catch (error3) { if (error3 instanceof YAMLException) throw error3; - throwErrorAt(state.source, position, error3 instanceof Error ? error3.message : String(error3), state.filename); + YAMLException.throwAt(state.source, position, error3 instanceof Error ? error3.message : String(error3), state.filename); } } -function lookupTag(exact, prefix, tagName) { - const exactTag = exact[tagName]; - if (exactTag) return exactTag; - for (const tag of prefix) if (tagName.startsWith(tag.tagName)) return tag; -} -function findExplicitTag(state, exact, prefix, tagName, nodeKind) { - const tag = lookupTag(exact, prefix, tagName); - if (tag) return tag; - throwError$1(state, `unknown ${nodeKind} tag !<${tagName}>`); -} function constructScalar(state, event) { const source = getScalarValue(state.source, event); const rawTag = event.tagStart === NO_RANGE$2 ? "" : state.source.slice(event.tagStart, event.tagEnd); @@ -143434,7 +176040,7 @@ function constructScalar(state, event) { tag: strTag2 }; const tagName = tagNameFull(rawTag, state.tagHandlers); - const scalarTag = lookupTag(state.schema.exact.scalar, state.schema.prefix.scalar, tagName); + const scalarTag = state.schema.lookupScalarTag(tagName); if (scalarTag) { const result = scalarTag.resolve(source, true, tagName); if (result === NOT_RESOLVED) throwError$1(state, `cannot resolve a node with !<${tagName}> explicit tag`); @@ -143443,7 +176049,7 @@ function constructScalar(state, event) { tag: scalarTag }; } - const collectionTagDef = lookupTag(state.schema.exact.mapping, state.schema.prefix.mapping, tagName) ?? lookupTag(state.schema.exact.sequence, state.schema.prefix.sequence, tagName); + const collectionTagDef = state.schema.lookupMappingTag(tagName) ?? state.schema.lookupSequenceTag(tagName); if (collectionTagDef) { if (source !== "") throwError$1(state, `cannot resolve a node with !<${tagName}> explicit tag`); const carrier = collectionTagDef.create(tagName); @@ -143454,50 +176060,49 @@ function constructScalar(state, event) { } throwError$1(state, `unknown scalar tag !<${tagName}>`); } - if (event.style === 1) { - const candidates = state.schema.implicitScalarByFirstChar.get(source.charAt(0)) ?? state.schema.implicitScalarAnyFirstChar; - for (const tag of candidates) { - const result = tag.resolve(source, false, tag.tagName); - if (result !== NOT_RESOLVED) return { - value: result, - tag - }; - } - } + if (event.style === SCALAR_STYLE.PLAIN) return state.schema.resolveImplicitScalarTag(source); return { value: strTag2.resolve(source, false, strTag2.tagName), tag: strTag2 }; } -function collectionTag(state, event, exact, prefix, defaultTagName, nodeKind) { +function collectionTagName(state, event, defaultTagName) { const rawTag = event.tagStart === NO_RANGE$2 ? "" : state.source.slice(event.tagStart, event.tagEnd); - const tagName = rawTag === "" || rawTag === "!" ? defaultTagName : tagNameFull(rawTag, state.tagHandlers); - return { - tagName, - tag: findExplicitTag(state, exact, prefix, tagName, nodeKind) - }; + return rawTag === "" || rawTag === "!" ? defaultTagName : tagNameFull(rawTag, state.tagHandlers); } function isMappingTag(tag) { return tag.nodeKind === "mapping"; } +function chargeMergeWork(state) { + state.totalMergeKeys++; + if (state.maxTotalMergeKeys !== -1 && state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`); +} function mergeKeys(state, frame, source, sourceTag) { + chargeMergeWork(state); for (const sourceKey of sourceTag.keys(source)) { - if (state.maxTotalMergeKeys !== -1 && ++state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`); + chargeMergeWork(state); if (frame.tag.has(frame.value, sourceKey)) continue; const err = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey)); if (err) throwError$1(state, err); - (frame.overridable ??= /* @__PURE__ */ new Set()).add(sourceKey); + frame.overridable ??= /* @__PURE__ */ new Set(); + frame.overridable.add(sourceKey); } } function mergeSource(state, frame, source, sourceTag) { state.position = frame.keyPosition; if (isMappingTag(sourceTag)) mergeKeys(state, frame, source, sourceTag); - else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) for (const element of source) mergeKeys(state, frame, element, frame.tag); - else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable"); + else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) { + if (source.length > 100) throwError$1(state, "abnormal merge sequence size"); + for (const element of source) { + const elementTag = state.nodeTags.get(element); + if (!elementTag) throwError$1(state, "cannot merge mappings; the provided source object is unacceptable"); + mergeKeys(state, frame, element, elementTag); + } + } else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable"); } function addMappingValue(state, frame, key, value, tag) { state.position = frame.keyPosition; - if (key === MERGE_KEY) { + if (frame.keyIsMerge) { mergeSource(state, frame, value, tag); return; } @@ -143512,9 +176117,7 @@ function addValue(state, value, tag) { frame.value = value; frame.hasValue = true; } else if (frame.kind === "sequence") { - if (frame.merge) { - if (!isMappingTag(tag)) throwError$1(state, "cannot merge mappings; the provided source object is unacceptable"); - } + if (isMappingTag(tag)) state.nodeTags.set(value, tag); const err = frame.tag.addItem(frame.value, value, frame.index++); if (err) throwError$1(state, err); } else if (frame.hasKey) { @@ -143526,6 +176129,7 @@ function addValue(state, value, tag) { frame.key = value; frame.keyPosition = state.position; frame.hasKey = true; + frame.keyIsMerge = tag.tagName === MERGE_TAG_NAME; } } function storeAnchor(state, event, value, tag, isValueFinal) { @@ -143550,6 +176154,7 @@ function constructFromEvents(events, options) { position: 0, frames: [], anchors: /* @__PURE__ */ new Map(), + nodeTags: /* @__PURE__ */ new Map(), tagHandlers: /* @__PURE__ */ Object.create(null), totalMergeKeys: 0, aliasCount: 0 @@ -143558,8 +176163,9 @@ function constructFromEvents(events, options) { const event = state.events[state.eventIndex++]; state.position = eventPosition$1(event); switch (event.type) { - case 1: + case EVENT_ID.DOCUMENT: state.anchors = /* @__PURE__ */ new Map(); + state.nodeTags = /* @__PURE__ */ new Map(); state.aliasCount = 0; state.tagHandlers = /* @__PURE__ */ Object.create(null); for (const directive of event.directives) if (directive.kind === "tag") state.tagHandlers[directive.handle] = directive.prefix; @@ -143570,47 +176176,49 @@ function constructFromEvents(events, options) { hasValue: false }); break; - case 4: { + case EVENT_ID.SCALAR: { const { value, tag } = constructScalar(state, event); storeAnchor(state, event, value, tag, true); addValue(state, value, tag); break; } - case 2: { - const definition = collectionTag(state, event, state.schema.exact.sequence, state.schema.prefix.sequence, "tag:yaml.org,2002:seq", "sequence"); - const value = definition.tag.create(definition.tagName); - const anchor = storeAnchor(state, event, value, definition.tag, definition.tag.carrierIsResult); - const parent = state.frames[state.frames.length - 1]; - const merge2 = parent !== void 0 && parent.kind === "mapping" && parent.hasKey && parent.key === MERGE_KEY; + case EVENT_ID.SEQUENCE: { + const tagName = collectionTagName(state, event, "tag:yaml.org,2002:seq"); + const tag = state.schema.lookupSequenceTag(tagName); + if (!tag) throwError$1(state, `unknown sequence tag !<${tagName}>`); + const value = tag.create(tagName); + const anchor = storeAnchor(state, event, value, tag, tag.carrierIsResult); state.frames.push({ kind: "sequence", position: state.position, value, - tag: definition.tag, + tag, anchor, - index: 0, - merge: merge2 + index: 0 }); break; } - case 3: { - const definition = collectionTag(state, event, state.schema.exact.mapping, state.schema.prefix.mapping, "tag:yaml.org,2002:map", "mapping"); - const value = definition.tag.create(definition.tagName); - const anchor = storeAnchor(state, event, value, definition.tag, definition.tag.carrierIsResult); + case EVENT_ID.MAPPING: { + const tagName = collectionTagName(state, event, "tag:yaml.org,2002:map"); + const tag = state.schema.lookupMappingTag(tagName); + if (!tag) throwError$1(state, `unknown mapping tag !<${tagName}>`); + const value = tag.create(tagName); + const anchor = storeAnchor(state, event, value, tag, tag.carrierIsResult); state.frames.push({ kind: "mapping", position: state.position, value, - tag: definition.tag, + tag, anchor, key: void 0, keyPosition: state.position, hasKey: false, + keyIsMerge: false, overridable: null }); break; } - case 5: { + case EVENT_ID.ALIAS: { if (state.maxAliases !== -1 && ++state.aliasCount > state.maxAliases) throwError$1(state, `aliases exceeded maxAliases (${state.maxAliases})`); const name = state.source.slice(event.anchorStart, event.anchorEnd); const anchor = state.anchors.get(name); @@ -143619,7 +176227,7 @@ function constructFromEvents(events, options) { addValue(state, anchor.value, anchor.tag); break; } - case 6: { + case EVENT_ID.POP: { const frame = state.frames.pop(); if (frame.kind === "mapping" && frame.hasKey) { state.position = frame.keyPosition; @@ -143660,7 +176268,7 @@ var DEFAULT_PARSER_OPTIONS = { }; function addDocumentEvent(state, explicitStart, explicitEnd) { state.events.push({ - type: 1, + type: EVENT_ID.DOCUMENT, explicitStart, explicitEnd, directives: state.directives @@ -143668,7 +176276,7 @@ function addDocumentEvent(state, explicitStart, explicitEnd) { } function addSequenceEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) { state.events.push({ - type: 2, + type: EVENT_ID.SEQUENCE, start, anchorStart, anchorEnd, @@ -143679,7 +176287,7 @@ function addSequenceEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd } function addMappingEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) { state.events.push({ - type: 3, + type: EVENT_ID.MAPPING, start, anchorStart, anchorEnd, @@ -143690,18 +176298,18 @@ function addMappingEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, } function insertFlowPairMappingEvent(state, snapshot) { state.events.splice(snapshot.eventsLength, 0, { - type: 3, + type: EVENT_ID.MAPPING, start: snapshot.position, anchorStart: NO_RANGE$1, anchorEnd: NO_RANGE$1, tagStart: NO_RANGE$1, tagEnd: NO_RANGE$1, - style: 2 + style: COLLECTION_STYLE.FLOW }); } -function addScalarEvent(state, valueStart, valueEnd, anchorStart, anchorEnd, tagStart, tagEnd, style, chomping = 1, indent = -1, fast = false) { +function addScalarEvent(state, valueStart, valueEnd, anchorStart, anchorEnd, tagStart, tagEnd, style, chomping = CHOMPING_MODE.CLIP, indent = -1, fast = false) { state.events.push({ - type: 4, + type: EVENT_ID.SCALAR, valueStart, valueEnd, anchorStart, @@ -143716,16 +176324,16 @@ function addScalarEvent(state, valueStart, valueEnd, anchorStart, anchorEnd, tag } function addAliasEvent(state, anchorStart, anchorEnd) { state.events.push({ - type: 5, + type: EVENT_ID.ALIAS, anchorStart, anchorEnd }); } function addPopEvent(state) { - state.events.push({ type: 6 }); + state.events.push({ type: EVENT_ID.POP }); } function addEmptyScalarEvent(state) { - addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, 1); + addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, SCALAR_STYLE.PLAIN); } function emptyProperties() { return { @@ -143754,7 +176362,7 @@ function restoreState(state, snapshot) { state.events.length = snapshot.eventsLength; } function throwError(state, message) { - throwErrorAt(state.input.slice(0, state.length), state.position, message, state.filename); + YAMLException.throwAt(state.input.slice(0, state.length), state.position, message, state.filename); } function isEol(c) { return c === 10 || c === 13; @@ -143833,12 +176441,34 @@ function testDocumentSeparator(state, position = state.position) { } return false; } +function skipByteOrderMark(state) { + if (state.position === state.lineStart && state.input.charCodeAt(state.position) === 65279) { + state.position++; + state.lineStart = state.position; + } +} +function testDocumentBoundary(state) { + if (state.position !== state.lineStart) return false; + if (testDocumentSeparator(state)) return true; + if (state.input.charCodeAt(state.position) !== 65279) return false; + const snapshot = snapshotState(state); + skipByteOrderMark(state); + skipSeparationSpace(state, true); + const ch = state.input.charCodeAt(state.position); + const result = state.position === state.lineStart && (ch === 37 || ch === 45 && testDocumentSeparator(state)); + restoreState(state, snapshot); + return result; +} function skipUntilLineEnd(state) { let ch = state.input.charCodeAt(state.position); while (ch !== 0 && !isEol(ch)) ch = state.input.charCodeAt(++state.position); } function checkPrintable(state, start, end) { - if (PATTERN_NON_PRINTABLE.test(state.input.slice(start, end))) throwError(state, "the stream contains non-printable characters"); + const match2 = PATTERN_NON_PRINTABLE.exec(state.input.slice(start, end)); + if (match2 !== null) { + state.position = start + match2.index + match2[0].length - 1; + throwError(state, "the stream contains non-printable characters"); + } } function readTagProperty(state, props, inFlow) { if (state.input.charCodeAt(state.position) !== 33) return false; @@ -143865,12 +176495,14 @@ function readTagProperty(state, props, inFlow) { state.position++; } else { while (ch !== 0 && !isWsOrEol(ch) && !(inFlow && isFlowIndicator(ch))) { - if (ch === 33) if (!isNamed) { - tagHandle = state.input.slice(suffixStart - 1, state.position + 1); - if (!PATTERN_TAG_HANDLE.test(tagHandle)) throwError(state, "named tag handle cannot contain such characters"); - isNamed = true; - suffixStart = state.position + 1; - } else throwError(state, "tag suffix cannot contain exclamation marks"); + if (ch === 33) { + if (!isNamed) { + tagHandle = state.input.slice(suffixStart - 1, state.position + 1); + if (!PATTERN_TAG_HANDLE.test(tagHandle)) throwError(state, "named tag handle cannot contain such characters"); + isNamed = true; + suffixStart = state.position + 1; + } else throwError(state, "tag suffix cannot contain exclamation marks"); + } ch = state.input.charCodeAt(++state.position); } tagName = state.input.slice(suffixStart, state.position); @@ -143922,7 +176554,7 @@ function readSingleQuotedScalar(state, nodeIndent, props) { } const end = state.position; state.position++; - addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 2, 1, -1, simple); + addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.SINGLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple); return true; } if (isEol(ch)) { @@ -143944,7 +176576,7 @@ function readDoubleQuotedScalar(state, nodeIndent, props) { if (ch === 34) { const end = state.position; state.position++; - addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 3, 1, -1, simple); + addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.DOUBLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple); return true; } if (ch === 92) { @@ -143972,18 +176604,18 @@ function readDoubleQuotedScalar(state, nodeIndent, props) { } function readBlockScalar(state, parentIndent, props) { const ch = state.input.charCodeAt(state.position); - let chomping = 1; + let chomping = CHOMPING_MODE.CLIP; let indent = -1; let detectedIndent = false; if (ch !== 124 && ch !== 62) return false; - const style = ch === 124 ? 4 : 5; + const style = ch === 124 ? SCALAR_STYLE.LITERAL_BLOCK : SCALAR_STYLE.FOLDED_BLOCK; state.position++; while (state.input.charCodeAt(state.position) !== 0) { const current = state.input.charCodeAt(state.position); const digit = fromDecimalCode(current); if (current === 43 || current === 45) { - if (chomping !== 1) throwError(state, "repeat of a chomping mode identifier"); - chomping = current === 43 ? 3 : 2; + if (chomping !== CHOMPING_MODE.CLIP) throwError(state, "repeat of a chomping mode identifier"); + chomping = current === 43 ? CHOMPING_MODE.KEEP : CHOMPING_MODE.STRIP; state.position++; } else if (digit >= 0) { if (digit === 0) throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one"); @@ -144016,14 +176648,14 @@ function readBlockScalar(state, parentIndent, props) { } else if (column > 0) valueEnd = linePosition + column; break; } - if (linePosition === state.lineStart && testDocumentSeparator(state, linePosition)) break; + if (testDocumentBoundary(state)) break; if (!detectedIndent && contentIndent === -1 && isEol(first)) maxLeadingIndent = Math.max(maxLeadingIndent, column); if (!detectedIndent && contentIndent === -1 && !isEol(first)) { if (first === 9 && column < parentIndent) { state.position = linePosition + column; throwError(state, "tab characters must not be used in indentation"); } - if (column < maxLeadingIndent) { + if (column >= parentIndent && column < maxLeadingIndent) { state.position = linePosition + column; throwError(state, "bad indentation of a mapping entry"); } @@ -144054,7 +176686,7 @@ function readBlockScalar(state, parentIndent, props) { function canStartPlainScalar(state, nodeContext) { const ch = state.input.charCodeAt(state.position); const inFlow = nodeContext === CONTEXT_FLOW_IN; - if (ch === 0 || isWsOrEol(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96 || inFlow && isFlowIndicator(ch)) return false; + if (ch === 0 || isWsOrEol(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96 || isFlowIndicator(ch)) return false; if (ch === 63 || ch === 45) { const following = state.input.charCodeAt(state.position + 1); if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) return false; @@ -144069,7 +176701,7 @@ function readPlainScalar(state, nodeIndent, nodeContext, props) { const inFlow = nodeContext === CONTEXT_FLOW_IN; let multiline = false; while (ch !== 0) { - if (state.position === state.lineStart && testDocumentSeparator(state)) break; + if (testDocumentBoundary(state)) break; if (ch === 58) { const following = state.input.charCodeAt(state.position + 1); if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) break; @@ -144098,7 +176730,7 @@ function readPlainScalar(state, nodeIndent, nodeContext, props) { } if (end === start) return false; checkPrintable(state, start, end); - addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1, 1, -1, !multiline); + addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.PLAIN, CHOMPING_MODE.CLIP, -1, !multiline); return true; } function skipFlowSeparationSpace(state, nodeIndent) { @@ -144113,8 +176745,8 @@ function readFlowCollection(state, nodeIndent, props) { let readNext = true; if (ch !== 91 && ch !== 123) return false; const terminator = isMapping ? 125 : 93; - if (isMapping) addMappingEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 2); - else addSequenceEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 2); + if (isMapping) addMappingEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW); + else addSequenceEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW); state.position++; while (state.input.charCodeAt(state.position) !== 0) { skipFlowSeparationSpace(state, nodeIndent); @@ -144168,7 +176800,7 @@ function readFlowCollection(state, nodeIndent, props) { } function readBlockSequence(state, nodeIndent, props) { if (state.firstTabInLine !== -1 || state.input.charCodeAt(state.position) !== 45 || !isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) return false; - addSequenceEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1); + addSequenceEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK); while (state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) { if (state.firstTabInLine !== -1) { state.position = state.firstTabInLine; @@ -144204,7 +176836,7 @@ function readBlockMapping(state, nodeIndent, flowIndent, props) { const entryLine = state.line; if ((ch === 63 || ch === 58) && isWsOrEolOrEnd(following)) { if (!mappingOpened) { - addMappingEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1); + addMappingEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK); mappingOpened = true; } if (ch === 63) { @@ -144233,13 +176865,16 @@ function readBlockMapping(state, nodeIndent, flowIndent, props) { ch = state.input.charCodeAt(++state.position); if (!isWsOrEolOrEnd(ch)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping"); if (!mappingOpened) { - restoreState(state, beforeKey); - addMappingEvent(state, beforeKey.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1); + state.events.splice(beforeKey.eventsLength, 0, { + type: EVENT_ID.MAPPING, + start: beforeKey.position, + anchorStart: props.anchorStart, + anchorEnd: props.anchorEnd, + tagStart: props.tagStart, + tagEnd: props.tagEnd, + style: COLLECTION_STYLE.BLOCK + }); mappingOpened = true; - parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true); - ch = state.input.charCodeAt(state.position); - while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position); - state.position++; } detected = true; atExplicitKey = false; @@ -144302,7 +176937,7 @@ function parseNode(state, parentIndent, nodeContext, allowToSeek, allowCompact, if (atNewLine && allowBlockStyles && (props.tagStart !== NO_RANGE$1 || props.anchorStart !== NO_RANGE$1) && (ch === 33 || ch === 38)) { const fallbackState = snapshotState(state); const flowIndent = parentIndent + 1; - if (readBlockMapping(state, state.position - state.lineStart, flowIndent, props) && state.events[fallbackState.eventsLength]?.type === 3) { + if (readBlockMapping(state, state.position - state.lineStart, flowIndent, props) && state.events[fallbackState.eventsLength]?.type === EVENT_ID.MAPPING) { state.depth--; return true; } @@ -144323,23 +176958,24 @@ function parseNode(state, parentIndent, nodeContext, allowToSeek, allowCompact, if (indentStatus === 1 || nodeContext === CONTEXT_BLOCK_OUT) { const flowIndent = nodeContext === CONTEXT_FLOW_IN || nodeContext === CONTEXT_FLOW_OUT ? parentIndent : parentIndent + 1; const blockIndent = state.position - state.lineStart; - if (indentStatus === 1) if (allowBlockCollections && (readBlockSequence(state, blockIndent, props) || readBlockMapping(state, blockIndent, flowIndent, props)) || readFlowCollection(state, flowIndent, props)) hasContent = true; - else { - const ch = state.input.charCodeAt(state.position); - if (propertyStart !== null && allowPropertyMapping && allowBlockStyles && !allowBlockCollections && ch !== 124 && ch !== 62) { - const fallbackState = snapshotState(state); - const propertyIndent = propertyStart.position - propertyStart.lineStart; - restoreState(state, propertyStart); - if (readBlockMapping(state, propertyIndent, flowIndent, emptyProperties()) && state.events[fallbackState.eventsLength]?.type === 3) hasContent = true; - else restoreState(state, fallbackState); + if (indentStatus === 1) { + if (allowBlockCollections && (readBlockSequence(state, blockIndent, props) || readBlockMapping(state, blockIndent, flowIndent, props)) || readFlowCollection(state, flowIndent, props)) hasContent = true; + else { + const ch = state.input.charCodeAt(state.position); + if (propertyStart !== null && allowPropertyMapping && allowBlockStyles && !allowBlockCollections && ch !== 124 && ch !== 62) { + const fallbackState = snapshotState(state); + const propertyIndent = propertyStart.position - propertyStart.lineStart; + restoreState(state, propertyStart); + if (readBlockMapping(state, propertyIndent, flowIndent, emptyProperties()) && state.events[fallbackState.eventsLength]?.type === EVENT_ID.MAPPING) hasContent = true; + else restoreState(state, fallbackState); + } + if (!hasContent && (allowBlockScalars && readBlockScalar(state, flowIndent, props) || readSingleQuotedScalar(state, flowIndent, props) || readDoubleQuotedScalar(state, flowIndent, props) || readAlias(state, props) || readPlainScalar(state, flowIndent, nodeContext, props))) hasContent = true; } - if (!hasContent && (allowBlockScalars && readBlockScalar(state, flowIndent, props) || readSingleQuotedScalar(state, flowIndent, props) || readDoubleQuotedScalar(state, flowIndent, props) || readAlias(state, props) || readPlainScalar(state, flowIndent, nodeContext, props))) hasContent = true; - } - else if (indentStatus === 0) hasContent = allowBlockCollections && readBlockSequence(state, blockIndent, props); + } else if (indentStatus === 0) hasContent = allowBlockCollections && readBlockSequence(state, blockIndent, props); } allowBlockScalars = allowBlockScalars && !hasContent; if (!hasContent && (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1 || allowBlockScalars)) { - addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1); + addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.PLAIN); hasContent = true; } state.depth--; @@ -144424,9 +177060,9 @@ function readDocument(state) { } } const documentEvent = state.events[documentEventIndex]; - if (documentEvent?.type === 1) documentEvent.explicitEnd = explicitEnd; + if (documentEvent?.type === EVENT_ID.DOCUMENT) documentEvent.explicitEnd = explicitEnd; addPopEvent(state); - if (!explicitEnd && state.position < state.length && !(state.position === state.lineStart && testDocumentSeparator(state))) throwError(state, "end of the stream or a document separator is expected"); + if (!explicitEnd && state.position < state.length && !testDocumentBoundary(state)) throwError(state, "end of the stream or a document separator is expected"); } function parseEvents(input, options) { const length = input.length; @@ -144446,9 +177082,9 @@ function parseEvents(input, options) { events: [] }; const nullpos = input.indexOf("\0"); - if (nullpos !== -1) throwErrorAt(input, nullpos, "null byte is not allowed in input", state.filename); - if (state.input.charCodeAt(state.position) === 65279) state.position++; + if (nullpos !== -1) YAMLException.throwAt(input, nullpos, "null byte is not allowed in input", state.filename); while (state.position < state.length) { + skipByteOrderMark(state); skipSeparationSpace(state, true); if (state.position >= state.length) break; const documentStart = state.position; @@ -144481,14 +177117,6 @@ function load(input, options) { if (documents.length === 1) return documents[0]; throw new YAMLException("expected a single document in the stream, but found more"); } -var Style = class { - tagged = false; - flow = false; - singleQuoted = false; - doubleQuoted = false; - literal = false; - folded = false; -}; var INVALID = /* @__PURE__ */ Symbol("INVALID"); function buildRepresentTypes(schema) { const defaultTags = new Set([ @@ -144517,9 +177145,9 @@ function buildRepresentTypes(schema) { function matchTag(state, object2) { for (let index2 = 0, length = state.representTypes.length; index2 < length; index2 += 1) { const { tag, implicitTag } = state.representTypes[index2]; - if (tag.identify && tag.identify(object2)) { + if (tag.identify(object2)) { let tagName; - if (tag.matchByTagPrefix && tag.representTagName) tagName = tag.representTagName(object2); + if (tag.matchByTagPrefix) tagName = tag.representTagName(object2); else tagName = tag.tagName; return { tag, @@ -144537,8 +177165,6 @@ function build(state, object2) { if (existing.anchor === void 0) existing.anchor = `ref_${state.refCounter++}`; return { kind: "alias", - tag: "", - style: new Style(), anchor: existing.anchor }; } @@ -144551,24 +177177,20 @@ function build(state, object2) { } const { tag, tagName, implicitTag } = matched; const nodeTagName = implicitTag ? tagName : tagNameShort(tagName); - if (tag.nodeKind === "scalar") { - const style2 = new Style(); - style2.tagged = !implicitTag; - return { - kind: "scalar", - tag: nodeTagName, - style: style2, - value: tag.represent(object2) - }; - } + if (tag.nodeKind === "scalar") return { + kind: "scalar", + tag: nodeTagName, + tagged: !implicitTag, + style: SCALAR_STYLE.PLAIN, + value: tag.represent(object2) + }; if (tag.nodeKind === "sequence") { const container = tag.represent(object2); - const style2 = new Style(); - style2.tagged = !implicitTag; const node2 = { kind: "sequence", tag: nodeTagName, - style: style2, + tagged: !implicitTag, + style: COLLECTION_STYLE.BLOCK, items: [] }; if (!state.noRefs) state.refs.set(object2, node2); @@ -144581,12 +177203,11 @@ function build(state, object2) { return node2; } const map = tag.represent(object2); - const style = new Style(); - style.tagged = !implicitTag; const node = { kind: "mapping", tag: nodeTagName, - style, + tagged: !implicitTag, + style: COLLECTION_STYLE.BLOCK, items: [] }; if (!state.noRefs) state.refs.set(object2, node); @@ -144643,7 +177264,6 @@ function visitNode(node, visitor, ctx) { isKey: false })) return true; } - break; } return false; } @@ -144654,83 +177274,204 @@ function visit(documents, visitor) { isKey: false })) return; } -var CHAR_BOM = 65279; -var CHAR_TAB = 9; -var CHAR_LINE_FEED = 10; -var CHAR_CARRIAGE_RETURN = 13; -var CHAR_SPACE = 32; -var CHAR_EXCLAMATION = 33; -var CHAR_DOUBLE_QUOTE = 34; -var CHAR_SHARP = 35; -var CHAR_PERCENT = 37; -var CHAR_AMPERSAND = 38; -var CHAR_SINGLE_QUOTE = 39; -var CHAR_ASTERISK = 42; -var CHAR_COMMA = 44; -var CHAR_MINUS = 45; -var CHAR_COLON = 58; -var CHAR_EQUALS = 61; -var CHAR_GREATER_THAN = 62; -var CHAR_QUESTION = 63; -var CHAR_COMMERCIAL_AT = 64; -var CHAR_LEFT_SQUARE_BRACKET = 91; -var CHAR_RIGHT_SQUARE_BRACKET = 93; -var CHAR_GRAVE_ACCENT = 96; -var CHAR_LEFT_CURLY_BRACKET = 123; -var CHAR_VERTICAL_LINE = 124; -var CHAR_RIGHT_CURLY_BRACKET = 125; -var ESCAPE_SEQUENCES = {}; -ESCAPE_SEQUENCES[0] = "\\0"; -ESCAPE_SEQUENCES[7] = "\\a"; -ESCAPE_SEQUENCES[8] = "\\b"; -ESCAPE_SEQUENCES[9] = "\\t"; -ESCAPE_SEQUENCES[10] = "\\n"; -ESCAPE_SEQUENCES[11] = "\\v"; -ESCAPE_SEQUENCES[12] = "\\f"; -ESCAPE_SEQUENCES[13] = "\\r"; -ESCAPE_SEQUENCES[27] = "\\e"; -ESCAPE_SEQUENCES[34] = '\\"'; -ESCAPE_SEQUENCES[92] = "\\\\"; -ESCAPE_SEQUENCES[133] = "\\N"; -ESCAPE_SEQUENCES[160] = "\\_"; -ESCAPE_SEQUENCES[8232] = "\\L"; -ESCAPE_SEQUENCES[8233] = "\\P"; -var DEFAULT_PRESENTER_OPTIONS = { - indent: 2, - seqNoIndent: false, - seqInlineFirst: true, - sortKeys: false, - lineWidth: 80, - flowBracketPadding: false, - flowSkipCommaSpace: false, - flowSkipColonSpace: false, - quoteFlowKeys: false, - quoteStyle: "single", - forceQuotes: false, - tagBeforeAnchor: false +function hasBit(mask, bit) { + return (mask & 1 << bit) !== 0; +} +var DEFAULT_SCALAR_STYLE_RULES = { + applyQuoteFlowKeysOption, + doubleQuoteForInvisibles, + doubleQuoteWhitespaceOnly, + applyForceQuotesOption, + tryLongOrMultilineAsBlock, + quoteInvalidPlain, + fallbackToDoubleQuoted }; -function nodeTagShort(node) { - return node.style.tagged ? node.tag : tagNameShort(node.tag); +function _preferredQuotedStyle(layout) { + if (layout.presenterOptions.quoteStyle === "single" && hasBit(layout.allowedStylesMask, SCALAR_STYLE.SINGLE_QUOTED)) return SCALAR_STYLE.SINGLE_QUOTED; + return SCALAR_STYLE.DOUBLE_QUOTED; +} +function applyQuoteFlowKeysOption(layout) { + if (!layout.presenterOptions.quoteFlowKeys) return; + if (!layout.isKey || !layout.flowOnly || layout.style !== SCALAR_STYLE.PLAIN) return; + layout.style = SCALAR_STYLE.DOUBLE_QUOTED; +} +function doubleQuoteForInvisibles(layout) { + if (layout.style === SCALAR_STYLE.PLAIN && /[\t\x7F-\xA0\u2028\u2029\uFEFF\uFFFE\uFFFF]/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED; +} +function doubleQuoteWhitespaceOnly(layout) { + if (layout.style === SCALAR_STYLE.PLAIN && /^\s+$/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED; +} +function applyForceQuotesOption(layout) { + if (!layout.presenterOptions.forceQuotes) return; + if (layout.isKey || layout.style !== SCALAR_STYLE.PLAIN) return; + if (layout.node.tag !== layout.presenterOptions.schema.defaultScalarTag.tagName) return; + layout.style = layout.node.value.includes("\n") ? SCALAR_STYLE.DOUBLE_QUOTED : _preferredQuotedStyle(layout); +} +function tryLongOrMultilineAsBlock(layout) { + if (layout.style !== SCALAR_STYLE.PLAIN || layout.isKey) return; + const value = layout.node.value; + const multiline = value.indexOf("\n") !== -1; + if (!hasBit(layout.allowedStylesMask, SCALAR_STYLE.LITERAL_BLOCK)) { + if (multiline) layout.style = SCALAR_STYLE.DOUBLE_QUOTED; + return; + } + const w = layout.presenterOptions.lineWidth; + if (w === -1) { + if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK; + return; + } + const availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent); + let position = 0; + let shouldFold = false; + while (position <= value.length) { + let lineEnd = value.length; + const nextLineBreak = value.indexOf("\n", position); + if (nextLineBreak !== -1) lineEnd = nextLineBreak; + const line = value.slice(position, lineEnd); + if (line.length > availableWidth && line[0] !== " " && / [^ \t]/.test(line)) shouldFold = true; + if (nextLineBreak === -1) break; + position = nextLineBreak + 1; + } + if (shouldFold) layout.style = SCALAR_STYLE.FOLDED_BLOCK; + else if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK; +} +function quoteInvalidPlain(layout) { + if (layout.style === SCALAR_STYLE.PLAIN && !hasBit(layout.allowedStylesMask, SCALAR_STYLE.PLAIN)) layout.style = _preferredQuotedStyle(layout); +} +function fallbackToDoubleQuoted(layout) { + if (!hasBit(layout.allowedStylesMask, layout.style)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED; +} +function setBit(mask, bit) { + return mask | 1 << bit; +} +var SRC_C_PRINTABLE = "[\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\uD7FF\\uE000-\\uFFFD\\u{10000}-\\u{10FFFF}]"; +var SRC_B_CHAR = "[\\n\\r]"; +var SRC_C_BYTE_ORDER_MARK = "\\uFEFF"; +var SRC_S_WHITE = "[ \\t]"; +var SRC_NB_CHAR = `(?:(?!(?:${SRC_B_CHAR}|${SRC_C_BYTE_ORDER_MARK}))${SRC_C_PRINTABLE})`; +var SRC_NS_CHAR = `(?:(?!${SRC_S_WHITE})${SRC_NB_CHAR})`; +var SRC_NB_JSON = "[\\x09\\x20-\\uD7FF\\uE000-\\uFFFF\\u{10000}-\\u{10FFFF}]"; +var SRC_C_INDICATOR = "[-?:,\\[\\]{}#&*!|>'\"%@`]"; +var SRC_C_FLOW_INDICATOR = "[,\\[\\]{}]"; +var SRC_NS_PLAIN_SAFE_FLOW_OUT = SRC_NS_CHAR; +var SRC_NS_PLAIN_SAFE_FLOW_IN = `(?:(?!${SRC_C_FLOW_INDICATOR})${SRC_NS_CHAR})`; +var SRC_NS_PLAIN_FIRST_FLOW_OUT = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))`; +var SRC_NS_PLAIN_FIRST_FLOW_IN = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))`; +var SRC_NS_PLAIN_CHAR_FLOW_OUT = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_OUT})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))#*`; +var SRC_NS_PLAIN_CHAR_FLOW_IN = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_IN})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))#*`; +var SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_OUT})*`; +var SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_IN})*`; +var SRC_NS_PLAIN_ONE_LINE_FLOW_OUT = `${SRC_NS_PLAIN_FIRST_FLOW_OUT}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`; +var SRC_NS_PLAIN_ONE_LINE_FLOW_IN = `${SRC_NS_PLAIN_FIRST_FLOW_IN}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`; +var SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_OUT; +var SRC_NS_PLAIN_ONE_LINE_FLOW_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_IN; +var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_OUT}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`; +var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_IN}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`; +var SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT = `${SRC_NS_PLAIN_ONE_LINE_FLOW_OUT}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT})*`; +var SRC_NS_PLAIN_MULTI_LINE_FLOW_IN = `${SRC_NS_PLAIN_ONE_LINE_FLOW_IN}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN})*`; +var NS_PLAIN_FLOW_OUT = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT})$`, "u"); +var NS_PLAIN_FLOW_IN = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_IN})$`, "u"); +var NS_PLAIN_BLOCK_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY})$`, "u"); +var NS_PLAIN_FLOW_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_FLOW_KEY})$`, "u"); +var NB_SINGLE_ONE_LINE = new RegExp(`^(?:${SRC_NB_JSON})*$`, "u"); +var NB_SINGLE_MULTI_LINE = new RegExp(`^(?:${SRC_NB_JSON}|\\n)*$`, "u"); +var BLOCK_SCALAR_CONTENT = new RegExp(`^(?:${SRC_NB_CHAR}|\\n)*$`, "u"); +var C_FORBIDDEN_FIRST_LINE = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/; +var C_FORBIDDEN_CONTENT = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/m; +function canUsePlain(layout) { + const str = layout.node.value; + if (str !== "") { + if (!(layout.isKey ? layout.flowOnly ? NS_PLAIN_FLOW_KEY : NS_PLAIN_BLOCK_KEY : layout.flowOnly ? NS_PLAIN_FLOW_IN : NS_PLAIN_FLOW_OUT).test(str)) return false; + if (layout.shiftOfFirstLine === 0 && C_FORBIDDEN_FIRST_LINE.test(str)) return false; + if (layout.shiftOfContent === 0) { + const firstLineBreak = str.indexOf("\n"); + if (firstLineBreak !== -1) { + const content = str.slice(firstLineBreak + 1); + if (C_FORBIDDEN_CONTENT.test(content)) return false; + } + } + } + const resolvedTag = layout.presenterOptions.schema.resolveImplicitScalarTag(str).tag.tagName; + if (!layout.node.tagged && resolvedTag !== layout.node.tag) return false; + if (!layout.node.tagged && str === "=" && resolvedTag === layout.presenterOptions.schema.defaultScalarTag.tagName) return false; + return true; } -function createPresenterState(options) { - const opts = { - ...DEFAULT_PRESENTER_OPTIONS, - ...options - }; - return { - ...opts, - defaultScalarTagName: opts.schema.defaultScalarTag.tagName, - implicitResolvers: opts.schema.implicitScalarTags - }; +function canUseSingleQuoted(layout) { + const str = layout.node.value; + if (!(layout.isKey ? NB_SINGLE_ONE_LINE : NB_SINGLE_MULTI_LINE).test(str)) return false; + if (/[ \t]\n|\n[ \t]/.test(str)) return false; + if (!layout.isKey && layout.shiftOfContent === 0) { + const firstLineBreak = str.indexOf("\n"); + if (firstLineBreak !== -1 && C_FORBIDDEN_CONTENT.test(str.slice(firstLineBreak + 1))) return false; + } + return true; } -function encodeNonPrintable(character) { - const string2 = character.toString(16).toUpperCase(); - const handle = character <= 255 ? "x" : "u"; - const length = character <= 255 ? 2 : 4; - return `\\${handle}${"0".repeat(length - string2.length)}${string2}`; +function canUseBlock(layout) { + if (layout.flowOnly || !BLOCK_SCALAR_CONTENT.test(layout.node.value)) return false; + const contentIndent = layout.shiftOfContent - layout.shiftOfParent; + if (contentIndent < 1) return false; + if (contentIndent > 9 && /^\n* /.test(layout.node.value)) return false; + if (layout.shiftOfContent === 0 && C_FORBIDDEN_CONTENT.test(layout.node.value)) return false; + return true; +} +function detectAllowedStyles(layout) { + let mask = setBit(0, SCALAR_STYLE.DOUBLE_QUOTED); + if (canUsePlain(layout)) mask = setBit(mask, SCALAR_STYLE.PLAIN); + if (canUseSingleQuoted(layout)) mask = setBit(mask, SCALAR_STYLE.SINGLE_QUOTED); + if (canUseBlock(layout)) mask = setBit(setBit(mask, SCALAR_STYLE.LITERAL_BLOCK), SCALAR_STYLE.FOLDED_BLOCK); + layout.allowedStylesMask = mask; +} +function renderScalar(layout) { + switch (layout.style) { + case SCALAR_STYLE.PLAIN: + return renderPlain(layout); + case SCALAR_STYLE.SINGLE_QUOTED: + return renderSingleQuoted(layout); + case SCALAR_STYLE.LITERAL_BLOCK: + return renderLiteralBlock(layout); + case SCALAR_STYLE.FOLDED_BLOCK: + return renderFoldedBlock(layout); + case SCALAR_STYLE.DOUBLE_QUOTED: + return renderDoubleQuoted(layout); + } +} +function renderPlain(layout) { + return encodeFlowBreaks(layout.node.value, layout.shiftOfContent); +} +function renderSingleQuoted(layout) { + return `'${encodeFlowBreaks(layout.node.value, layout.shiftOfContent).replace(/'/g, "''")}'`; +} +function renderLiteralBlock(layout) { + const value = layout.node.value; + return "|" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(value, layout.shiftOfContent)); +} +function renderFoldedBlock(layout) { + const value = layout.node.value; + const w = layout.presenterOptions.lineWidth; + let availableWidth = Infinity; + if (w !== -1) availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent); + return ">" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(foldBlockScalar(value, availableWidth), layout.shiftOfContent)); +} +function renderDoubleQuoted(layout) { + return `"${escapeString(layout.node.value)}"`; +} +function encodeFlowBreaks(string2, shiftOfContent) { + let nextLF = string2.indexOf("\n"); + if (nextLF === -1) return string2; + const pad = " ".repeat(shiftOfContent); + let result = string2.slice(0, nextLF); + const lineRe = /(\n+)([^\n]*)/g; + lineRe.lastIndex = nextLF; + let match2; + while (match2 = lineRe.exec(string2)) { + const breaks = match2[1].length; + const line = match2[2]; + result += "\n".repeat(breaks + 1) + pad + line; + } + return result; } function indentString(string2, spaces) { - const ind = " ".repeat(spaces); + const indent = " ".repeat(spaces); let position = 0; let result = ""; const length = string2.length; @@ -144744,198 +177485,26 @@ function indentString(string2, spaces) { line = string2.slice(position, next + 1); position = next + 1; } - if (line.length && line !== "\n") result += ind; + if (line.length && line !== "\n") result += indent; result += line; } return result; } -function generateNextLine(state, level) { - return ` -${" ".repeat(state.indent * level)}`; -} -function scalarLayout(state, level) { - const indent = state.indent * Math.max(1, level); - return { - indent, - blockIndent: level === 0 ? state.indent + 1 : state.indent, - lineWidth: state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent) - }; -} -function resolveImplicitTag(state, str) { - for (let index2 = 0, length = state.implicitResolvers.length; index2 < length; index2 += 1) { - const tagDefinition = state.implicitResolvers[index2]; - if (tagDefinition.resolve(str, false, tagDefinition.tagName) !== NOT_RESOLVED) return tagDefinition.tagName; - } - return state.defaultScalarTagName; -} -function isWhitespace(c) { - return c === CHAR_SPACE || c === CHAR_TAB; -} -function startsWithDocumentSeparator(string2) { - const marker = string2.charCodeAt(0); - if (marker !== CHAR_MINUS && marker !== 46 || string2.charCodeAt(1) !== marker || string2.charCodeAt(2) !== marker) return false; - if (string2.length === 3) return true; - const following = string2.charCodeAt(3); - return isWhitespace(following) || following === CHAR_CARRIAGE_RETURN || following === CHAR_LINE_FEED; -} -function isPrintable(c) { - return c >= 32 && c <= 126 || c >= 161 && c <= 55295 && c !== 8232 && c !== 8233 || c >= 57344 && c <= 65533 && c !== CHAR_BOM || c >= 65536 && c <= 1114111; -} -function isNsCharOrWhitespace(c) { - return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED; -} -function isPlainSafe(c, prev, inblock) { - const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); - const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); - return (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar && (inblock || c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET); -} -function isPlainSafeFirst(c) { - return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT; -} -function isPlainSafeAtStart(string2, inblock) { - const first = codePointAt(string2, 0); - if (isPlainSafeFirst(first)) return true; - if (string2.length > 1 && (first === CHAR_MINUS || first === CHAR_QUESTION || first === CHAR_COLON)) { - const second = codePointAt(string2, 1); - return !isWhitespace(second) && isPlainSafe(second, first, inblock); - } - return false; -} -function isPlainSafeLast(c) { - return !isWhitespace(c) && c !== CHAR_COLON; -} -function codePointAt(string2, pos) { - const first = string2.charCodeAt(pos); - let second; - if (first >= 55296 && first <= 56319 && pos + 1 < string2.length) { - second = string2.charCodeAt(pos + 1); - if (second >= 56320 && second <= 57343) return (first - 55296) * 1024 + second - 56320 + 65536; - } - return first; -} function needIndentIndicator(string2) { return /^\n* /.test(string2); } -var STYLE_PLAIN = 1; -var STYLE_SINGLE = 2; -var STYLE_LITERAL = 3; -var STYLE_FOLDED = 4; -var STYLE_DOUBLE = 5; -function chooseScalarStyle(state, string2, layout, singleLineOnly, forceQuote, inblock) { - const { blockIndent, lineWidth } = layout; - let i; - let char = 0; - let prevChar = -1; - let hasLineBreak = false; - let hasFoldableLine = false; - const shouldTrackWidth = lineWidth !== -1; - let previousLineBreak = -1; - let plain = !startsWithDocumentSeparator(string2) && isPlainSafeAtStart(string2, inblock) && isPlainSafeLast(codePointAt(string2, string2.length - 1)); - if (singleLineOnly || forceQuote) for (i = 0; i < string2.length; char >= 65536 ? i += 2 : i++) { - char = codePointAt(string2, i); - if (!isPrintable(char)) return STYLE_DOUBLE; - plain = plain && isPlainSafe(char, prevChar, inblock); - prevChar = char; - } - else { - for (i = 0; i < string2.length; char >= 65536 ? i += 2 : i++) { - char = codePointAt(string2, i); - if (char === CHAR_LINE_FEED) { - hasLineBreak = true; - if (shouldTrackWidth) { - hasFoldableLine = hasFoldableLine || i - previousLineBreak - 1 > lineWidth && !isMoreIndented(string2[previousLineBreak + 1]); - previousLineBreak = i; - } - } else if (!isPrintable(char)) return STYLE_DOUBLE; - plain = plain && isPlainSafe(char, prevChar, inblock); - prevChar = char; - } - hasFoldableLine = hasFoldableLine || shouldTrackWidth && i - previousLineBreak - 1 > lineWidth && !isMoreIndented(string2[previousLineBreak + 1]); - } - if (!hasLineBreak && !hasFoldableLine) { - if (plain && !forceQuote) return STYLE_PLAIN; - return state.quoteStyle === "double" ? STYLE_DOUBLE : STYLE_SINGLE; - } - if (blockIndent > 9 && needIndentIndicator(string2)) return STYLE_DOUBLE; - return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; -} -function renderScalarStyle(string2, style, layout) { - const { indent, blockIndent, lineWidth } = layout; - switch (style) { - case STYLE_PLAIN: - return encodeFlowBreaks(string2, indent); - case STYLE_SINGLE: - return `'${encodeFlowBreaks(string2, indent).replace(/'/g, "''")}'`; - case STYLE_LITERAL: - return "|" + blockHeader(string2, blockIndent) + dropEndingNewline(indentString(string2, indent)); - case STYLE_FOLDED: - return ">" + blockHeader(string2, blockIndent) + dropEndingNewline(indentString(foldBlockScalar(string2, lineWidth), indent)); - case STYLE_DOUBLE: - return `"${escapeString(string2)}"`; - } -} -function resolveScalarStyle(state, node, layout, iskey, inblock) { - const singleLineOnly = iskey || !inblock; - if (node.style.singleQuoted) return STYLE_SINGLE; - if (node.style.doubleQuoted) return STYLE_DOUBLE; - if (!singleLineOnly) { - if (node.style.literal) return STYLE_LITERAL; - if (node.style.folded) return STYLE_FOLDED; - } - const string2 = node.value; - if (string2.length === 0) { - if (node.style.tagged || resolveImplicitTag(state, string2) === node.tag) return STYLE_PLAIN; - return state.quoteStyle === "double" ? STYLE_DOUBLE : STYLE_SINGLE; - } - const style = chooseScalarStyle(state, string2, layout, singleLineOnly, state.forceQuotes && !iskey, inblock); - if (style === STYLE_PLAIN && !node.style.tagged && resolveImplicitTag(state, string2) !== node.tag) return state.quoteStyle === "double" ? STYLE_DOUBLE : STYLE_SINGLE; - return style; -} -function blockHeader(string2, indentPerLevel) { - const indentIndicator = needIndentIndicator(string2) ? String(indentPerLevel) : ""; +function blockHeader(string2, shiftOfParent, shiftOfContent) { + const indentIndicator = needIndentIndicator(string2) ? String(shiftOfContent - shiftOfParent) : ""; const clip = string2[string2.length - 1] === "\n"; return `${indentIndicator}${clip && (string2[string2.length - 2] === "\n" || string2 === "\n") ? "+" : clip ? "" : "-"} `; } -function encodeFlowBreaks(string2, indent) { - let nextLF = string2.indexOf("\n"); - if (nextLF === -1) return string2; - const pad = " ".repeat(indent); - let result = string2.slice(0, nextLF); - const lineRe = /(\n+)([^\n]*)/g; - lineRe.lastIndex = nextLF; - let match2; - while (match2 = lineRe.exec(string2)) { - const breaks = match2[1].length; - const line = match2[2]; - result += "\n".repeat(breaks + 1) + pad + line; - } - return result; -} function dropEndingNewline(string2) { return string2[string2.length - 1] === "\n" ? string2.slice(0, -1) : string2; } function isMoreIndented(char) { return char === " " || char === " "; } -function foldBlockScalar(string2, width) { - const lineRe = /(\n+)([^\n]*)/g; - let nextLF = string2.indexOf("\n"); - if (nextLF === -1) nextLF = string2.length; - lineRe.lastIndex = nextLF; - let result = foldLine(string2.slice(0, nextLF), width); - let prevMoreIndented = string2[0] === "\n" || isMoreIndented(string2[0]); - let moreIndented; - let match2; - while (match2 = lineRe.exec(string2)) { - const prefix = match2[1]; - const line = match2[2]; - moreIndented = line !== "" && isMoreIndented(line[0]); - result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width); - prevMoreIndented = moreIndented; - } - return result; -} function foldLine(line, width) { if (line === "" || isMoreIndented(line[0])) return line; const breakRe = / [^ \t]/g; @@ -144961,43 +177530,133 @@ ${line.slice(curr + 1)}`; else result += line.slice(start); return result.slice(1); } -function escapeString(string2) { - let result = ""; - let char = 0; - for (let i = 0; i < string2.length; char >= 65536 ? i += 2 : i++) { - char = codePointAt(string2, i); - const escapeSeq = ESCAPE_SEQUENCES[char]; - if (escapeSeq) { - result += escapeSeq; - continue; - } - if (isPrintable(char)) { - result += string2[i]; - if (char >= 65536) result += string2[i + 1]; - continue; - } - result += encodeNonPrintable(char); +function foldBlockScalar(string2, width) { + const lineRe = /(\n+)([^\n]*)/g; + let nextLF = string2.indexOf("\n"); + if (nextLF === -1) nextLF = string2.length; + lineRe.lastIndex = nextLF; + let result = foldLine(string2.slice(0, nextLF), width); + let prevMoreIndented = string2[0] === "\n" || isMoreIndented(string2[0]); + let moreIndented; + let match2; + while (match2 = lineRe.exec(string2)) { + const prefix = match2[1]; + const line = match2[2]; + moreIndented = line !== "" && isMoreIndented(line[0]); + result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width); + prevMoreIndented = moreIndented; } return result; } +var CHARACTERS_TO_ESCAPE = /["\\\x00-\x1F\x7F-\xA0\u2028\u2029\uD800-\uDFFF\uFEFF\uFFFE\uFFFF]/gu; +function escapeCharacter(character) { + switch (character) { + case "\0": + return "\\0"; + case "\x07": + return "\\a"; + case "\b": + return "\\b"; + case " ": + return "\\t"; + case "\n": + return "\\n"; + case "\v": + return "\\v"; + case "\f": + return "\\f"; + case "\r": + return "\\r"; + case "\x1B": + return "\\e"; + case '"': + return '\\"'; + case "\\": + return "\\\\"; + case "\x85": + return "\\N"; + case "\xA0": + return "\\_"; + case "\u2028": + return "\\L"; + case "\u2029": + return "\\P"; + } + const code = character.charCodeAt(0); + const hex = code.toString(16).toUpperCase(); + if (code <= 255) return `\\x${"0".repeat(2 - hex.length)}${hex}`; + return `\\u${"0".repeat(4 - hex.length)}${hex}`; +} +function escapeString(string2) { + return string2.replace(CHARACTERS_TO_ESCAPE, escapeCharacter); +} +var CHAR_LINE_FEED = 10; +var DEFAULT_PRESENTER_OPTIONS = { + indent: 2, + seqNoIndent: false, + seqInlineFirst: true, + lineWidth: 80, + flowBracketPadding: false, + flowSkipCommaSpace: false, + flowSkipColonSpace: false, + quoteFlowKeys: false, + quoteStyle: "single", + forceQuotes: false, + scalarStyleRules: Object.keys(DEFAULT_SCALAR_STYLE_RULES).map((name) => Reflect.get(DEFAULT_SCALAR_STYLE_RULES, name)), + tagBeforeAnchor: false +}; +function nodeTagShort(node) { + return node.tagged ? node.tag : tagNameShort(node.tag); +} +function createPresenterState(options) { + const opts = { + ...DEFAULT_PRESENTER_OPTIONS, + ...options + }; + if (opts.flowSkipColonSpace) opts.quoteFlowKeys = true; + return { + ...opts, + defaultScalarTagName: opts.schema.defaultScalarTag.tagName, + openEnded: false + }; +} +function generateNextLine(state, level) { + return ` +${" ".repeat(state.indent * level)}`; +} +function scalarLayout(state, node, parent, level, isKey, flowOnly) { + return { + node, + parent, + level, + isKey, + flowOnly, + shiftOfParent: level === 0 ? -1 : state.indent * (level - 1), + shiftOfContent: state.indent * Math.max(1, level), + shiftOfFirstLine: level === 0 ? 0 : state.indent * level, + presenterOptions: state, + allowedStylesMask: 0, + style: node.style + }; +} function writeFlowSequence(state, level, node) { let result = ""; for (let index2 = 0, length = node.items.length; index2 < length; index2 += 1) { - const item = writeNode(state, level, node.items[index2], {}); - if (result !== "") result += `,${!state.flowSkipCommaSpace ? " " : ""}`; + const item = writeNode(state, level, node.items[index2], node, {}).text; + if (index2 > 0) result += `,${!state.flowSkipCommaSpace ? " " : ""}`; result += item; } - const pad = state.flowBracketPadding && result !== "" ? " " : ""; + const pad = state.flowBracketPadding && node.items.length > 0 ? " " : ""; return `[${pad}${result}${pad}]`; } function writeBlockSequence(state, level, node, compact) { let result = ""; for (let index2 = 0, length = node.items.length; index2 < length; index2 += 1) { - const item = writeNode(state, level + 1, node.items[index2], { + const item = writeNode(state, level + 1, node.items[index2], node, { block: true, compact: state.seqInlineFirst, isblockseq: true - }); + }).text; if (!compact || result !== "") result += generateNextLine(state, level); if (item === "" || CHAR_LINE_FEED === item.charCodeAt(0)) result += "-"; else result += "- "; @@ -145007,70 +177666,53 @@ function writeBlockSequence(state, level, node, compact) { } function writeFlowMapping(state, level, node) { let result = ""; - const items = sortMappingItems(state, node.items); - for (const { key, value } of items) { + for (const { key, value } of node.items) { let pairBuffer = ""; if (result !== "") pairBuffer += `,${!state.flowSkipCommaSpace ? " " : ""}`; - const keyText = writeNode(state, level, key, { iskey: true }); - const explicitPair = keyText.length > 1024; - if (explicitPair) pairBuffer += "? "; - else if (state.quoteFlowKeys) pairBuffer += '"'; - const valueText = writeNode(state, level, value, {}); + const keyRender = writeNode(state, level, key, node, { iskey: true }); + const keyText = keyRender.text; + const valueText = writeNode(state, level, value, node, {}).text; const sep7 = state.flowSkipColonSpace || valueText === "" ? "" : " "; - pairBuffer += `${keyText}${state.quoteFlowKeys && !explicitPair ? '"' : ""}:${sep7}${valueText}`; + const keyIsBareProps = key.kind === "scalar" && keyRender.noBody && (key.tagged || key.anchor !== void 0); + const keyColonSep = key.kind === "alias" || keyIsBareProps ? " " : ""; + pairBuffer += `${keyText}${keyColonSep}:${sep7}${valueText}`; result += pairBuffer; } const pad = state.flowBracketPadding && result !== "" ? " " : ""; return `{${pad}${result}${pad}}`; } -function sortKeyValue(key) { - return key.kind === "scalar" ? key.value : key; -} -function sortMappingItems(state, items) { - if (!state.sortKeys) return items; - const copy = items.slice(); - if (state.sortKeys === true) copy.sort((a, b) => { - const x = sortKeyValue(a.key); - const y = sortKeyValue(b.key); - if (x < y) return -1; - if (x > y) return 1; - return 0; - }); - else { - const fn = state.sortKeys; - copy.sort((a, b) => fn(sortKeyValue(a.key), sortKeyValue(b.key))); - } - return copy; -} function writeBlockMapping(state, level, node, compact) { let result = ""; - const items = sortMappingItems(state, node.items); - for (let index2 = 0, length = items.length; index2 < length; index2 += 1) { + for (let index2 = 0, length = node.items.length; index2 < length; index2 += 1) { let pairBuffer = ""; if (!compact || result !== "") pairBuffer += generateNextLine(state, level); - const { key, value } = items[index2]; - const keyIsBlock = (key.kind === "mapping" || key.kind === "sequence") && !key.style.flow && key.items.length !== 0 || key.kind === "scalar" && (key.style.literal || key.style.folded); - const keyText = keyIsBlock ? writeNode(state, level + 1, key, { + const { key, value } = node.items[index2]; + const keyIsBlock = (key.kind === "mapping" || key.kind === "sequence") && key.style === COLLECTION_STYLE.BLOCK && key.items.length !== 0 || key.kind === "scalar" && (key.style === SCALAR_STYLE.LITERAL_BLOCK || key.style === SCALAR_STYLE.FOLDED_BLOCK); + const keyRender = keyIsBlock ? writeNode(state, level + 1, key, node, { block: true, compact: true, isblockseq: !cannotBeCompact(state, key, level + 1) - }) : writeNode(state, level + 1, key, { + }) : writeNode(state, level + 1, key, node, { block: true, compact: true, iskey: true }); + const keyText = keyRender.text; const keyHasLineBreak = key.kind === "scalar" && key.value.indexOf("\n") !== -1; - const explicitPair = keyIsBlock || keyHasLineBreak || keyText.length > 1024; - if (explicitPair) if (keyText && CHAR_LINE_FEED === keyText.charCodeAt(0)) pairBuffer += "?"; - else pairBuffer += "? "; + const keyIsTooLong = keyText.length > 1024 && /^[\s\S]{1025}/u.test(keyText); + const explicitPair = keyIsBlock || keyHasLineBreak || keyIsTooLong; + if (explicitPair) { + if (keyText && CHAR_LINE_FEED === keyText.charCodeAt(0)) pairBuffer += "?"; + else pairBuffer += "? "; + } pairBuffer += keyText; if (explicitPair) pairBuffer += generateNextLine(state, level); - const valueText = writeNode(state, level + 1, value, { + const valueText = writeNode(state, level + 1, value, node, { block: true, compact: explicitPair, isblockseq: explicitPair && !cannotBeCompact(state, value, level + 1) - }); - const keyIsBareProps = key.kind === "scalar" && key.value === "" && keyText !== "" && keyText.charCodeAt(keyText.length - 1) !== CHAR_SINGLE_QUOTE && keyText.charCodeAt(keyText.length - 1) !== CHAR_DOUBLE_QUOTE; + }).text; + const keyIsBareProps = key.kind === "scalar" && keyRender.noBody && (key.tagged || key.anchor !== void 0); const keyColonSep = !explicitPair && (key.kind === "alias" || keyIsBareProps) ? " " : ""; if (valueText === "" || CHAR_LINE_FEED === valueText.charCodeAt(0)) pairBuffer += `${keyColonSep}:`; else pairBuffer += `${keyColonSep}: `; @@ -145080,29 +177722,44 @@ function writeBlockMapping(state, level, node, compact) { return result; } function cannotBeCompact(state, node, level) { - return node.style.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0; + if (node.kind === "alias") return true; + return node.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0; } -function writeNode(state, level, node, ctx) { - if (node.kind === "alias") return `*${node.anchor}`; +function writeNode(state, level, node, parent, ctx) { + if (node.kind === "alias") { + state.openEnded = false; + return { + text: `*${node.anchor}`, + noBody: false + }; + } const { block = false, iskey = false, isblockseq = false } = ctx; let compact = ctx.compact ?? false; const hasAnchor = node.anchor !== void 0; if (cannotBeCompact(state, node, level)) compact = false; let body; - let shouldPrintTag = node.style.tagged; - const useBlockCollection = block && (node.kind === "mapping" || node.kind === "sequence") && !node.style.flow && node.items.length !== 0; - if (node.kind === "mapping") if (useBlockCollection) body = writeBlockMapping(state, level, node, compact); - else body = writeFlowMapping(state, level, node); - else if (node.kind === "sequence") if (useBlockCollection) if (state.seqNoIndent && !isblockseq && level > 0) body = writeBlockSequence(state, level - 1, node, compact); - else body = writeBlockSequence(state, level, node, compact); - else body = writeFlowSequence(state, level, node); - else { - const layout = scalarLayout(state, level); - const style = resolveScalarStyle(state, node, layout, iskey, block); - body = renderScalarStyle(node.value, style, layout); - shouldPrintTag = node.style.tagged || style !== STYLE_PLAIN && node.tag !== state.defaultScalarTagName; - } + let shouldPrintTag = node.tagged; + const useBlockCollection = block && (node.kind === "mapping" || node.kind === "sequence") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0; + if (node.kind === "mapping") { + if (useBlockCollection) body = writeBlockMapping(state, level, node, compact); + else body = writeFlowMapping(state, level, node); + } else if (node.kind === "sequence") { + if (useBlockCollection) { + if (state.seqNoIndent && !isblockseq && level > 0) body = writeBlockSequence(state, level - 1, node, compact); + else body = writeBlockSequence(state, level, node, compact); + } else body = writeFlowSequence(state, level, node); + } else { + const layout = scalarLayout(state, node, parent, level, iskey, !block); + detectAllowedStyles(layout); + for (const rule of state.scalarStyleRules) rule(layout); + body = renderScalar(layout); + state.openEnded = (layout.style === SCALAR_STYLE.LITERAL_BLOCK || layout.style === SCALAR_STYLE.FOLDED_BLOCK) && (node.value === "\n" || node.value.endsWith("\n\n")); + shouldPrintTag = node.tagged || body === "" && layout.flowOnly && parent?.kind === "sequence" && !hasAnchor || layout.style !== SCALAR_STYLE.PLAIN && node.tag !== state.defaultScalarTagName; + } + if ((node.kind === "mapping" || node.kind === "sequence") && !useBlockCollection) state.openEnded = false; if (useBlockCollection && compact && level > 0 && state.indent > 2) body = `${" ".repeat(state.indent - 2)}${body}`; + const noBody = body === ""; + let text = body; if (shouldPrintTag || hasAnchor) { const props = []; const tag = shouldPrintTag ? nodeTagShort(node) : null; @@ -145115,19 +177772,15 @@ function writeNode(state, level, node, ctx) { if (tag !== null) props.push(tag); } const sep7 = body === "" || body.charCodeAt(0) === CHAR_LINE_FEED ? "" : " "; - body = `${props.join(" ")}${sep7}${body}`; + text = `${props.join(" ")}${sep7}${body}`; } - return body; + return { + text, + noBody + }; } function rootStartsOwnLine(node) { - return (node.kind === "sequence" || node.kind === "mapping") && !node.style.flow && node.items.length !== 0 && !node.style.tagged && node.anchor === void 0; -} -function isOpenEnded(node) { - let leaf = node; - while ((leaf.kind === "sequence" || leaf.kind === "mapping") && !leaf.style.flow && leaf.items.length !== 0) leaf = leaf.kind === "sequence" ? leaf.items[leaf.items.length - 1] : leaf.items[leaf.items.length - 1].value; - if (leaf.kind !== "scalar" || !(leaf.style.literal || leaf.style.folded)) return false; - const { value } = leaf; - return value.endsWith("\n\n") || value === "\n"; + return (node.kind === "sequence" || node.kind === "mapping") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0 && !node.tagged && node.anchor === void 0; } function writeDocumentDirectives(doc) { let result = ""; @@ -145149,6 +177802,7 @@ function present(documents, options) { let previousEnded = false; for (let index2 = 0; index2 < documents.length; index2 += 1) { const doc = documents[index2]; + state.openEnded = false; const directives = writeDocumentDirectives(doc); const hasDirectives = directives !== ""; const marker = doc.explicitStart || hasDirectives || index2 > 0 && !previousEnded; @@ -145156,44 +177810,39 @@ function present(documents, options) { if (doc.contents === null) { if (marker) result += "---\n"; } else if (marker) { - const body = writeNode(state, 0, doc.contents, { + const body = writeNode(state, 0, doc.contents, null, { block: true, compact: true - }); + }).text; const sep7 = body === "" ? "" : hasDirectives || rootStartsOwnLine(doc.contents) ? "\n" : " "; result += `---${sep7}${body} `; - } else result += writeNode(state, 0, doc.contents, { + } else result += writeNode(state, 0, doc.contents, null, { block: true, compact: true - }) + "\n"; - previousEnded = doc.explicitEnd || doc.contents !== null && isOpenEnded(doc.contents); + }).text + "\n"; + previousEnded = doc.explicitEnd || state.openEnded; if (previousEnded) result += "...\n"; } return result; } -var DEFAULT_DUMP_SCHEMA = YAML11_SCHEMA.withTags({ - ...intYaml11Tag, - resolve: (source, isExplicit, tagName) => { - const result = intYaml11Tag.resolve(source, isExplicit, tagName); - return result === NOT_RESOLVED ? intCoreTag.resolve(source, isExplicit, tagName) : result; - } -}, { - ...floatYaml11Tag, - resolve: (source, isExplicit, tagName) => { - const result = floatYaml11Tag.resolve(source, isExplicit, tagName); - return result === NOT_RESOLVED ? floatCoreTag.resolve(source, isExplicit, tagName) : result; - } -}); var DEFAULT_DUMP_OPTIONS = { ...DEFAULT_PRESENTER_OPTIONS, - schema: DEFAULT_DUMP_SCHEMA, + schema: DUMP_SCHEMA, skipInvalid: false, noRefs: false, flowLevel: -1, + sortKeys: false, transform: () => { } }; +function defaultCompareFn(a, b) { + const x = String(a); + const y = String(b); + if (x < y) return -1; + if (x > y) return 1; + return 0; +} function dump(input, options = {}) { const opts = { ...DEFAULT_DUMP_OPTIONS, @@ -145205,28 +177854,51 @@ function dump(input, options = {}) { }); if (opts.flowLevel >= 0) visit(documents, (node, ctx) => { if (ctx.depth < opts.flowLevel) return; - node.style.flow = true; + if (node.kind === "sequence" || node.kind === "mapping") node.style = COLLECTION_STYLE.FLOW; return VISIT_SKIP; }); + if (opts.sortKeys) { + const compareFn = opts.sortKeys === true ? defaultCompareFn : opts.sortKeys; + visit(documents, (node) => { + if (node.kind !== "mapping") return; + node.items.sort((a, b) => compareFn(a.key.kind === "scalar" ? a.key.value : "", b.key.kind === "scalar" ? b.key.value : "")); + }); + } opts.transform(documents); return present(documents, { ...pick(opts, Object.keys(DEFAULT_PRESENTER_OPTIONS)), schema: opts.schema }); } +var EVENT_DOCUMENT = EVENT_ID.DOCUMENT; +var EVENT_SEQUENCE = EVENT_ID.SEQUENCE; +var EVENT_MAPPING = EVENT_ID.MAPPING; +var EVENT_SCALAR = EVENT_ID.SCALAR; +var EVENT_ALIAS = EVENT_ID.ALIAS; +var EVENT_POP = EVENT_ID.POP; +var SCALAR_STYLE_PLAIN = SCALAR_STYLE.PLAIN; +var SCALAR_STYLE_SINGLE_QUOTED = SCALAR_STYLE.SINGLE_QUOTED; +var SCALAR_STYLE_DOUBLE_QUOTED = SCALAR_STYLE.DOUBLE_QUOTED; +var SCALAR_STYLE_LITERAL_BLOCK = SCALAR_STYLE.LITERAL_BLOCK; +var SCALAR_STYLE_FOLDED_BLOCK = SCALAR_STYLE.FOLDED_BLOCK; +var COLLECTION_STYLE_BLOCK = COLLECTION_STYLE.BLOCK; +var COLLECTION_STYLE_FLOW = COLLECTION_STYLE.FLOW; +var CHOMPING_CLIP = CHOMPING_MODE.CLIP; +var CHOMPING_STRIP = CHOMPING_MODE.STRIP; +var CHOMPING_KEEP = CHOMPING_MODE.KEEP; // src/util.ts var semver = __toESM(require_semver2()); // src/api-compatibility.json var maximumVersion = "3.23"; -var minimumVersion = "3.17"; +var minimumVersion = "3.19"; // src/json/index.ts function parseString(data) { return JSON.parse(data); } -function isObject(value) { +function isObject2(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } function isArray(value) { @@ -145295,10 +177967,10 @@ function array(validator) { function object(schema) { return { validate: (val) => { - return isObject(val) && validateSchema(schema, val); + return isObject2(val) && validateSchema(schema, val); }, check: (val, opts, path30) => { - if (!isObject(val)) { + if (!isObject2(val)) { return invalidCheckSchema(); } return checkSchema(schema, val, opts, path30); @@ -145404,10 +178076,88 @@ function checkSchema(schema, obj, options = {}, path30 = "") { return result; } +// src/errors/index.ts +function wrapError(error3) { + return error3 instanceof Error ? error3 : new Error(String(error3)); +} +function getErrorMessage(error3) { + return error3 instanceof Error ? error3.message : String(error3); +} +function isErrnoException(error3) { + return typeof error3 === "object" && error3 !== null && "code" in error3 && typeof error3.code === "string"; +} +function isDiskConfigurationError(e) { + if (!(e instanceof Error)) { + return false; + } + return ( + // out of disk space + e.message.includes("ENOSPC") || // access denied + e.message.includes("EACCES") + ); +} +var ConfigurationError = class extends Error { +}; +var HTTPError = class extends Error { + status; + constructor(message, status) { + super(message); + this.status = status; + } +}; +function asHTTPError(arg) { + if (!isObject2(arg) || !isString(arg.message)) { + return void 0; + } + if (Number.isInteger(arg.status)) { + return new HTTPError(arg.message, arg.status); + } + if (Number.isInteger(arg.httpStatusCode)) { + return new HTTPError(arg.message, arg.httpStatusCode); + } + return void 0; +} + +// src/github.ts +var GITHUB_DOTCOM_URL = "https://github.com"; +function parseGitHubUrl(inputUrl) { + const originalUrl = inputUrl; + if (inputUrl.indexOf("://") === -1) { + inputUrl = `https://${inputUrl}`; + } + if (!inputUrl.startsWith("http://") && !inputUrl.startsWith("https://")) { + throw new ConfigurationError(`"${originalUrl}" is not a http or https URL`); + } + let url2; + try { + url2 = new URL(inputUrl); + } catch { + throw new ConfigurationError(`"${originalUrl}" is not a valid URL`); + } + if (url2.hostname === "github.com" || url2.hostname === "api.github.com") { + return GITHUB_DOTCOM_URL; + } + if (url2.pathname.indexOf("/api/v3") !== -1) { + url2.pathname = url2.pathname.substring(0, url2.pathname.indexOf("/api/v3")); + } + if (url2.hostname.startsWith("api.")) { + url2.hostname = url2.hostname.substring(4); + } + if (!url2.pathname.endsWith("/")) { + url2.pathname = `${url2.pathname}/`; + } + return url2.toString(); +} +function getCurrentInstance(env) { + return { + url: env.getRequired("GITHUB_SERVER_URL" /* GITHUB_SERVER_URL */), + apiURL: env.getRequired("GITHUB_API_URL" /* GITHUB_API_URL */) + }; +} + // src/util.ts var BASE_DATABASE_OIDS_FILE_NAME = "base-database-oids.json"; var BROKEN_VERSIONS = ["0.0.0-20211207"]; -var GITHUB_DOTCOM_URL = "https://github.com"; var DEFAULT_DEBUG_ARTIFACT_NAME = "debug-artifacts"; var DEFAULT_DEBUG_DATABASE_NAME = "db"; var DEFAULT_RESERVED_RAM_SCALING_FACTOR = 0.05; @@ -145461,74 +178211,74 @@ function getMemoryFlagValueForPlatform(userInput, totalMemoryBytes, platform2) { } return Math.floor(memoryToUseMegaBytes); } -function getTotalMemoryBytes(logger) { +function getTotalMemoryBytes(logger2) { const limits = [os.totalmem()]; if (os.platform() === "linux") { limits.push( ...[ "/sys/fs/cgroup/memory/memory.limit_in_bytes", "/sys/fs/cgroup/memory.max" - ].map((file) => getCgroupMemoryLimitBytes(file, logger)).filter((limit2) => limit2 !== void 0).map((limit2) => limit2) + ].map((file) => getCgroupMemoryLimitBytes(file, logger2)).filter((limit2) => limit2 !== void 0).map((limit2) => limit2) ); } const limit = Math.min(...limits); - logger.debug( + logger2.debug( `While resolving RAM, determined that the total memory available to the Action is ${limit / (1024 * 1024)} MiB.` ); return limit; } -function getCgroupMemoryLimitBytes(limitFile, logger) { +function getCgroupMemoryLimitBytes(limitFile, logger2) { if (!fs.existsSync(limitFile)) { - logger.debug( + logger2.debug( `While resolving RAM, did not find a cgroup memory limit at ${limitFile}.` ); return void 0; } const limit = Number(fs.readFileSync(limitFile, "utf8")); if (!Number.isInteger(limit)) { - logger.debug( + logger2.debug( `While resolving RAM, ignored the file ${limitFile} that may contain a cgroup memory limit as this file did not contain an integer.` ); return void 0; } const displayLimit = `${Math.floor(limit / (1024 * 1024))} MiB`; if (limit > os.totalmem()) { - logger.debug( + logger2.debug( `While resolving RAM, ignored the file ${limitFile} that may contain a cgroup memory limit as its contents ${displayLimit} were greater than the total amount of system memory.` ); return void 0; } if (limit < MINIMUM_CGROUP_MEMORY_LIMIT_BYTES) { - logger.info( + logger2.info( `While resolving RAM, ignored a cgroup limit of ${displayLimit} in ${limitFile} as it was below ${MINIMUM_CGROUP_MEMORY_LIMIT_BYTES / (1024 * 1024)} MiB.` ); return void 0; } - logger.info( + logger2.info( `While resolving RAM, found a cgroup limit of ${displayLimit} in ${limitFile}.` ); return limit; } -function getCodeQLMemoryLimit(userInput, logger) { +function getCodeQLMemoryLimit(userInput, logger2) { return getMemoryFlagValueForPlatform( userInput, - getTotalMemoryBytes(logger), + getTotalMemoryBytes(logger2), process.platform ); } -function getMemoryFlag(userInput, logger) { - const megabytes = getCodeQLMemoryLimit(userInput, logger); +function getMemoryFlag(userInput, logger2) { + const megabytes = getCodeQLMemoryLimit(userInput, logger2); return `--ram=${megabytes}`; } -function getThreadsFlagValue(userInput, logger) { +function getThreadsFlagValue(userInput, logger2) { let numThreads; const maxThreadsCandidates = [os.cpus().length]; if (os.platform() === "linux") { maxThreadsCandidates.push( - ...["/sys/fs/cgroup/cpuset.cpus.effective", "/sys/fs/cgroup/cpuset.cpus"].map((file) => getCgroupCpuCountFromCpus(file, logger)).filter((count) => count !== void 0 && count > 0).map((count) => count) + ...["/sys/fs/cgroup/cpuset.cpus.effective", "/sys/fs/cgroup/cpuset.cpus"].map((file) => getCgroupCpuCountFromCpus(file, logger2)).filter((count) => count !== void 0 && count > 0).map((count) => count) ); maxThreadsCandidates.push( - ...["/sys/fs/cgroup/cpu.max"].map((file) => getCgroupCpuCountFromCpuMax(file, logger)).filter((count) => count !== void 0 && count > 0).map((count) => count) + ...["/sys/fs/cgroup/cpu.max"].map((file) => getCgroupCpuCountFromCpuMax(file, logger2)).filter((count) => count !== void 0 && count > 0).map((count) => count) ); } const maxThreads = Math.min(...maxThreadsCandidates); @@ -145540,14 +178290,14 @@ function getThreadsFlagValue(userInput, logger) { ); } if (numThreads > maxThreads) { - logger.info( + logger2.info( `Clamping desired number of threads (${numThreads}) to max available (${maxThreads}).` ); numThreads = maxThreads; } const minThreads = -maxThreads; if (numThreads < minThreads) { - logger.info( + logger2.info( `Clamping desired number of free threads (${numThreads}) to max available (${minThreads}).` ); numThreads = minThreads; @@ -145557,9 +178307,9 @@ function getThreadsFlagValue(userInput, logger) { } return numThreads; } -function getCgroupCpuCountFromCpuMax(cpuMaxFile, logger) { +function getCgroupCpuCountFromCpuMax(cpuMaxFile, logger2) { if (!fs.existsSync(cpuMaxFile)) { - logger.debug( + logger2.debug( `While resolving threads, did not find a cgroup CPU file at ${cpuMaxFile}.` ); return void 0; @@ -145567,7 +178317,7 @@ function getCgroupCpuCountFromCpuMax(cpuMaxFile, logger) { const cpuMaxString = fs.readFileSync(cpuMaxFile, "utf-8"); const cpuMaxStringSplit = cpuMaxString.split(" "); if (cpuMaxStringSplit.length !== 2) { - logger.debug( + logger2.debug( `While resolving threads, did not use cgroup CPU file at ${cpuMaxFile} because it contained ${cpuMaxStringSplit.length} value(s) rather than the two expected.` ); return void 0; @@ -145578,14 +178328,14 @@ function getCgroupCpuCountFromCpuMax(cpuMaxFile, logger) { } const duration = cpuMaxStringSplit[1]; const cpuCount = Math.floor(parseInt(cpuLimit) / parseInt(duration)); - logger.info( + logger2.info( `While resolving threads, found a cgroup CPU file with ${cpuCount} CPUs in ${cpuMaxFile}.` ); return cpuCount; } -function getCgroupCpuCountFromCpus(cpusFile, logger) { +function getCgroupCpuCountFromCpus(cpusFile, logger2) { if (!fs.existsSync(cpusFile)) { - logger.debug( + logger2.debug( `While resolving threads, did not find a cgroup CPUs file at ${cpusFile}.` ); return void 0; @@ -145604,13 +178354,13 @@ function getCgroupCpuCountFromCpus(cpusFile, logger) { cpuCount += cpuEndIndex - cpuStartIndex + 1; } } - logger.info( + logger2.info( `While resolving threads, found a cgroup CPUs file with ${cpuCount} CPUs in ${cpusFile}.` ); return cpuCount; } -function getThreadsFlag(userInput, logger) { - return `--threads=${getThreadsFlagValue(userInput, logger)}`; +function getThreadsFlag(userInput, logger2) { + return `--threads=${getThreadsFlagValue(userInput, logger2)}`; } function getCodeQLDatabasePath(config, language) { return path.resolve(config.dbLocation, language); @@ -145623,37 +178373,9 @@ function getGeneratedSuitePath(config, language) { "config-queries.qls" ); } -function parseGitHubUrl(inputUrl) { - const originalUrl = inputUrl; - if (inputUrl.indexOf("://") === -1) { - inputUrl = `https://${inputUrl}`; - } - if (!inputUrl.startsWith("http://") && !inputUrl.startsWith("https://")) { - throw new ConfigurationError(`"${originalUrl}" is not a http or https URL`); - } - let url2; - try { - url2 = new URL(inputUrl); - } catch { - throw new ConfigurationError(`"${originalUrl}" is not a valid URL`); - } - if (url2.hostname === "github.com" || url2.hostname === "api.github.com") { - return GITHUB_DOTCOM_URL; - } - if (url2.pathname.indexOf("/api/v3") !== -1) { - url2.pathname = url2.pathname.substring(0, url2.pathname.indexOf("/api/v3")); - } - if (url2.hostname.startsWith("api.")) { - url2.hostname = url2.hostname.substring(4); - } - if (!url2.pathname.endsWith("/")) { - url2.pathname = `${url2.pathname}/`; - } - return url2.toString(); -} var CODEQL_ACTION_WARNED_ABOUT_VERSION_ENV_VAR = "CODEQL_ACTION_WARNED_ABOUT_VERSION"; var hasBeenWarnedAboutVersion = false; -function checkGitHubVersionInRange(version, logger) { +function checkGitHubVersionInRange(version, logger2) { if (hasBeenWarnedAboutVersion || version.type !== "GitHub Enterprise Server" /* GHES */) { return; } @@ -145663,17 +178385,17 @@ function checkGitHubVersionInRange(version, logger) { maximumVersion ); if (disallowedAPIVersionReason === 0 /* ACTION_TOO_OLD */) { - logger.warning( + logger2.warning( `The CodeQL Action version you are using is too old to be compatible with GitHub Enterprise ${version.version}. If you experience issues, please upgrade to a more recent version of the CodeQL Action.` ); } if (disallowedAPIVersionReason === 1 /* ACTION_TOO_NEW */) { - logger.warning( + logger2.warning( `GitHub Enterprise ${version.version} is too old to be compatible with this version of the CodeQL Action. If you experience issues, please upgrade to a more recent version of GitHub Enterprise or use an older version of the CodeQL Action.` ); } hasBeenWarnedAboutVersion = true; - core2.exportVariable(CODEQL_ACTION_WARNED_ABOUT_VERSION_ENV_VAR, true); + exportEnvVar(CODEQL_ACTION_WARNED_ABOUT_VERSION_ENV_VAR, true); } function apiVersionInRange(version, minimumVersion2, maximumVersion2) { if (!semver.satisfies(version, `>=${minimumVersion2}`)) { @@ -145694,37 +178416,6 @@ var ExhaustivityCheckingError = class extends Error { function assertNever(value) { throw new ExhaustivityCheckingError(value); } -function initializeEnvironment(version) { - core2.exportVariable("CODEQL_ACTION_FEATURE_MULTI_LANGUAGE" /* FEATURE_MULTI_LANGUAGE */, "false"); - core2.exportVariable("CODEQL_ACTION_FEATURE_SANDWICH" /* FEATURE_SANDWICH */, "false"); - core2.exportVariable("CODEQL_ACTION_FEATURE_SARIF_COMBINE" /* FEATURE_SARIF_COMBINE */, "true"); - core2.exportVariable("CODEQL_ACTION_FEATURE_WILL_UPLOAD" /* FEATURE_WILL_UPLOAD */, "true"); - core2.exportVariable("CODEQL_ACTION_VERSION" /* VERSION */, version); -} -var HTTPError = class extends Error { - status; - constructor(message, status) { - super(message); - this.status = status; - } -}; -var ConfigurationError = class extends Error { -}; -function asHTTPError(arg) { - if (!isObject(arg) || !isString(arg.message)) { - return void 0; - } - if (Number.isInteger(arg.status)) { - return new HTTPError(arg.message, arg.status); - } - if (Number.isInteger(arg.httpStatusCode)) { - return new HTTPError(arg.message, arg.httpStatusCode); - } - return void 0; -} -async function codeQlVersionAtLeast(codeql, requiredVersion) { - return semver.gte((await codeql.getVersion()).version, requiredVersion); -} function getBaseDatabaseOidsFilePath(config) { return path.join(config.dbLocation, BASE_DATABASE_OIDS_FILE_NAME); } @@ -145752,10 +178443,13 @@ async function bundleDb(config, language, codeql, dbName, { includeDiagnostics } ); return databaseBundlePath; } +function durationMsSince(startTime) { + return Math.round(import_perf_hooks.performance.now() - startTime); +} async function delay(milliseconds, opts) { const { allowProcessExit } = opts || {}; - return new Promise((resolve14) => { - const timer = setTimeout(resolve14, milliseconds); + return new Promise((resolve15) => { + const timer = setTimeout(resolve15, milliseconds); if (allowProcessExit) { timer.unref(); } @@ -145764,11 +178458,15 @@ async function delay(milliseconds, opts) { function isGoodVersion(versionSpec) { return !BROKEN_VERSIONS.includes(versionSpec); } -function isInTestMode() { - return process.env["CODEQL_ACTION_TEST_MODE" /* TEST_MODE */] === "true"; +function shouldSkipGenerateFailedSarif(env = getEnv()) { + const skipGenerateFailedSarif = env.getOptional( + "CODEQL_ACTION_SKIP_GENERATE_FAILED_SARIF" /* SKIP_GENERATE_FAILED_SARIF */ + ); + return skipGenerateFailedSarif !== "false" && (shouldSkipSarifUpload(env) || skipGenerateFailedSarif === "true"); } -function shouldSkipSarifUpload() { - return isInTestMode() || process.env["CODEQL_ACTION_SKIP_SARIF_UPLOAD" /* SKIP_SARIF_UPLOAD */] === "true"; +function shouldSkipSarifUpload(env = getEnv()) { + const skipSarifUpload = env.getOptional("CODEQL_ACTION_SKIP_SARIF_UPLOAD" /* SKIP_SARIF_UPLOAD */); + return skipSarifUpload !== "false" && (env.isSkippingUploadsInTests() || skipSarifUpload === "true"); } function getTestingEnvironment() { const testingEnvironment = process.env["CODEQL_ACTION_TESTING_ENVIRONMENT" /* TESTING_ENVIRONMENT */] || ""; @@ -145800,12 +178498,12 @@ function listFolder(dir) { } return files; } -async function tryGetFolderBytes(cacheDir2, logger, quiet = false) { +async function tryGetFolderBytes(cacheDir2, logger2, quiet = false) { try { return await getFolderSize.loose(cacheDir2); } catch (e) { - if (!quiet || logger.isDebug()) { - logger.warning( + if (!quiet || logger2.isDebug()) { + logger2.warning( `Encountered an error while getting size of '${cacheDir2}': ${e}` ); } @@ -145832,14 +178530,14 @@ async function waitForResultWithTimeLimit(timeoutMs, promise, onTimeout) { } async function checkForTimeout() { if (hadTimeout === true) { - core2.info( + core3.info( "A timeout occurred, force exiting the process after 30 seconds to prevent hanging." ); await delay(3e4, { allowProcessExit: true }); process.exit(); } } -function isHostedRunner() { +function looksLikeHostedRunner() { return ( // Name of the runner on hosted Windows runners process.env["RUNNER_NAME"]?.includes("Hosted Agent") || // Name of the runner on hosted POSIX runners @@ -145851,18 +178549,18 @@ function parseMatrixInput(matrixInput) { if (matrixInput === void 0 || matrixInput === "null") { return void 0; } - return JSON.parse(matrixInput); -} -function wrapError(error3) { - return error3 instanceof Error ? error3 : new Error(String(error3)); -} -function getErrorMessage(error3) { - return error3 instanceof Error ? error3.message : String(error3); + try { + return JSON.parse(matrixInput); + } catch (err) { + throw new Error( + `Failed to parse matrix input '${matrixInput}': ${getErrorMessage(err)}` + ); + } } function prettyPrintPack(pack) { return `${pack.name}${pack.version ? `@${pack.version}` : ""}${pack.path ? `:${pack.path}` : ""}`; } -async function checkDiskUsage(logger) { +async function checkDiskUsage(logger2) { try { const diskUsage = await fsPromises.statfs( getRequiredEnvParam("GITHUB_WORKSPACE") @@ -145873,18 +178571,18 @@ async function checkDiskUsage(logger) { if (diskUsage.bavail < 2 * numBlocksPerGb) { const message = `The Actions runner is running low on disk space (${(diskUsage.bavail / numBlocksPerMb).toPrecision(4)} MB available).`; if (process.env["CODEQL_ACTION_HAS_WARNED_ABOUT_DISK_SPACE" /* HAS_WARNED_ABOUT_DISK_SPACE */] !== "true") { - logger.warning(message); + logger2.warning(message); } else { - logger.debug(message); + logger2.debug(message); } - core2.exportVariable("CODEQL_ACTION_HAS_WARNED_ABOUT_DISK_SPACE" /* HAS_WARNED_ABOUT_DISK_SPACE */, "true"); + exportEnvVar("CODEQL_ACTION_HAS_WARNED_ABOUT_DISK_SPACE" /* HAS_WARNED_ABOUT_DISK_SPACE */, "true"); } return { numAvailableBytes: diskUsage.bavail * blockSizeInBytes, numTotalBytes: diskUsage.blocks * blockSizeInBytes }; } catch (error3) { - logger.warning( + logger2.warning( `Failed to check available disk space: ${getErrorMessage(error3)}` ); return void 0; @@ -145897,10 +178595,10 @@ function checkActionVersion(version, githubVersion) { semver.coerce(githubVersion.version) ?? "0.0.0", ">=3.20" )) { - core2.warning( + core3.warning( "CodeQL Action v3 will be deprecated in December 2026. Please update all occurrences of the CodeQL Action in your workflow files to v4. For more information, see https://github.blog/changelog/2025-10-28-upcoming-deprecation-of-codeql-action-v3/" ); - core2.exportVariable("CODEQL_ACTION_DID_LOG_VERSION_DEPRECATION" /* LOG_VERSION_DEPRECATION */, "true"); + exportEnvVar("CODEQL_ACTION_DID_LOG_VERSION_DEPRECATION" /* LOG_VERSION_DEPRECATION */, "true"); } } } @@ -145919,26 +178617,30 @@ var BuildMode = /* @__PURE__ */ ((BuildMode3) => { return BuildMode3; })(BuildMode || {}); function cloneObject(obj) { - return JSON.parse(JSON.stringify(obj)); + try { + return JSON.parse(JSON.stringify(obj)); + } catch (err) { + throw new Error(`Cloning object failed: ${getErrorMessage(err)}`); + } } -async function cleanUpPath(file, name, logger) { - logger.debug(`Cleaning up ${name}.`); +async function cleanUpPath(file, name, logger2) { + logger2.debug(`Cleaning up ${name}.`); try { await fs.promises.rm(file, { force: true, recursive: true }); } catch (e) { - logger.warning(`Failed to clean up ${name}: ${e}.`); + logger2.warning(`Failed to clean up ${name}: ${e}.`); } } -async function isBinaryAccessible(binary, logger) { +async function isBinaryAccessible(binary, logger2) { try { await io.which(binary, true); - logger.debug(`Found ${binary}.`); + logger2.debug(`Found ${binary}.`); return true; } catch (e) { - logger.debug(`Could not find ${binary}: ${e}`); + logger2.debug(`Could not find ${binary}: ${e}`); return false; } } @@ -146000,19 +178702,18 @@ var Failure = class { function getActionsEnv() { return { getRequiredInput, - getOptionalInput, - exportVariable: core3.exportVariable + getOptionalInput }; } var getRequiredInput = function(name) { - const value = core3.getInput(name); + const value = core4.getInput(name); if (!value) { throw new ConfigurationError(`Input required and not supplied: ${name}`); } return value; }; var getOptionalInput = function(name) { - const value = core3.getInput(name); + const value = core4.getInput(name); return value.length > 0 ? value : void 0; }; function getTemporaryDirectory(env = getEnv()) { @@ -146023,7 +178724,7 @@ function getDiffRangesJsonFilePath(env = getEnv()) { return path2.join(getTemporaryDirectory(env), PR_DIFF_RANGE_JSON_FILENAME); } function getActionVersion() { - return "4.37.9"; + return "4.39.3"; } function getWorkflowEventName(env = getEnv()) { return env.getRequired("GITHUB_EVENT_NAME" /* GITHUB_EVENT_NAME */); @@ -146047,27 +178748,33 @@ function getWorkflowEvent(env = getEnv()) { ); } } -async function printDebugLogs(config) { +async function printDebugLogs(logger2, config) { + if (!hasConfigKey(config, "languages") || !hasConfigKey(config, "dbLocation")) { + logger2.debug( + `Not printing debug logs, because the configuration does not include the 'languages' or 'dbLocation' fields.` + ); + return; + } for (const language of config.languages) { const databaseDirectory = getCodeQLDatabasePath(config, language); const logsDirectory = path2.join(databaseDirectory, "log"); if (!doesDirectoryExist(logsDirectory)) { - core3.info(`Directory ${logsDirectory} does not exist.`); + logger2.info(`Directory ${logsDirectory} does not exist.`); continue; } const walkLogFiles = (dir) => { const entries = fs2.readdirSync(dir, { withFileTypes: true }); if (entries.length === 0) { - core3.info(`No debug logs found at directory ${logsDirectory}.`); + logger2.info(`No debug logs found at directory ${logsDirectory}.`); } for (const entry of entries) { if (entry.isFile()) { const absolutePath = path2.resolve(dir, entry.name); - core3.startGroup( + logger2.startGroup( `CodeQL Debug Logs - ${language} - ${entry.name} from file at path ${absolutePath}` ); - process.stdout.write(fs2.readFileSync(absolutePath)); - core3.endGroup(); + logger2.info(fs2.readFileSync(absolutePath, "utf-8")); + logger2.endGroup(); } else if (entry.isDirectory()) { walkLogFiles(path2.resolve(dir, entry.name)); } @@ -146088,7 +178795,7 @@ function getUploadValue(input) { case "never": return "never"; default: - core3.warning( + core4.warning( `Unrecognized 'upload' input to 'analyze' Action: ${input}. Defaulting to 'always'.` ); return "always"; @@ -146157,7 +178864,7 @@ var getFileType = async (filePath) => { }).exec(); return stdout.trim(); } catch (e) { - core3.info( + core4.info( `Could not determine type of ${filePath} from ${stdout}. ${stderr}` ); throw e; @@ -146166,6 +178873,9 @@ var getFileType = async (filePath) => { function isSelfHostedRunner(env = getEnv()) { return env.getOptional("RUNNER_ENVIRONMENT" /* RUNNER_ENVIRONMENT */) === "self-hosted"; } +function isGitHubHostedRunner(env = getEnv()) { + return env.getOptional("RUNNER_ENVIRONMENT" /* RUNNER_ENVIRONMENT */) === "github-hosted"; +} function isDynamicWorkflow(env = getEnv()) { return getWorkflowEventName(env) === "dynamic"; } @@ -146200,7 +178910,7 @@ function ensureEndsInPeriod(text) { return text[text.length - 1] === "." ? text : `${text}.`; } var MAX_STDERR_BUFFER_SIZE = 2e4; -async function runTool(cmd, args = [], opts = {}) { +async function runTool(env, cmd, args = [], opts = {}) { let stdout = ""; let stderr = ""; if (!opts.noStreamStdout) { @@ -146208,6 +178918,7 @@ async function runTool(cmd, args = [], opts = {}) { `); } const exitCode = await new toolrunner.ToolRunner(cmd, args, { + env: env.getDefined(), ignoreReturnCode: true, listeners: { stdout: (data) => { @@ -146239,16 +178950,24 @@ var persistInputs = function(env = getEnv()) { const inputEnvironmentVariables = entries.filter( ([name]) => name.startsWith("INPUT_") ); - core3.saveState(persistedInputsKey, JSON.stringify(inputEnvironmentVariables)); + core4.saveState(persistedInputsKey, JSON.stringify(inputEnvironmentVariables)); }; -var restoreInputs = function() { - const persistedInputs = core3.getState(persistedInputsKey); - if (persistedInputs) { - for (const [name, value] of JSON.parse(persistedInputs)) { - process.env[name] = value; +function restoreInputs(logger2) { + try { + const persistedInputsValue = core4.getState(persistedInputsKey); + if (persistedInputsValue) { + const persistedInputs = JSON.parse(persistedInputsValue); + for (const [name, value] of persistedInputs) { + process.env[name] = value; + } } + } catch (err) { + logger2.error(`Unable to restore inputs: ${getErrorMessage(err)}`); + throw new Error( + "Failed to restore inputs from the state set by this action's main execution." + ); } -}; +} function getPullRequestBranches(env = getEnv()) { const pullRequest = github.context.payload.pull_request; if (pullRequest) { @@ -146287,13 +179006,13 @@ var qualityCategoryMapping = { typescript: "javascript-typescript", kotlin: "java-kotlin" }; -function fixCodeQualityCategory(logger, category, env = getEnv()) { +function fixCodeQualityCategory(logger2, category, env = getEnv()) { if (category !== void 0 && isDefaultSetup(env) && category.startsWith("/language:")) { const language = category.substring("/language:".length); const mappedLanguage = qualityCategoryMapping[language]; if (mappedLanguage) { const newCategory = `/language:${mappedLanguage}`; - logger.info( + logger2.info( `Adjusted category for Code Quality from '${category}' to '${newCategory}'.` ); return newCategory; @@ -146303,32 +179022,44 @@ function fixCodeQualityCategory(logger, category, env = getEnv()) { } // src/logging.ts -var core4 = __toESM(require_core()); +var core5 = __toESM(require_core()); +var joinMessageStrings = (message) => { + if (Array.isArray(message)) { + return message.join(" "); + } else { + return message; + } +}; +var autoJoinMessageStrings = (fn) => { + return (message) => { + return fn(joinMessageStrings(message)); + }; +}; function getActionsLogger() { return { - debug: core4.debug, - info: core4.info, - warning: core4.warning, - error: core4.error, - isDebug: core4.isDebug, - startGroup: core4.startGroup, - endGroup: core4.endGroup + debug: autoJoinMessageStrings(core5.debug), + info: autoJoinMessageStrings(core5.info), + warning: autoJoinMessageStrings(core5.warning), + error: autoJoinMessageStrings(core5.error), + isDebug: core5.isDebug, + startGroup: core5.startGroup, + endGroup: core5.endGroup }; } function withGroup(groupName, f) { - core4.startGroup(groupName); + core5.startGroup(groupName); try { return f(); } finally { - core4.endGroup(); + core5.endGroup(); } } async function withGroupAsync(groupName, f) { - core4.startGroup(groupName); + core5.startGroup(groupName); try { return await f(); } finally { - core4.endGroup(); + core5.endGroup(); } } function formatDuration(durationMs) { @@ -146345,7 +179076,7 @@ function formatDuration(durationMs) { // src/status-report.ts var os3 = __toESM(require("os")); -var core7 = __toESM(require_core()); +var core8 = __toESM(require_core()); // node_modules/uuid/dist-node/regex.js var regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; @@ -146401,7 +179132,7 @@ function _v4(options, buf, offset) { var v4_default = v4; // src/api-client.ts -var core5 = __toESM(require_core()); +var core6 = __toESM(require_core()); var githubUtils = __toESM(require_utils4()); // node_modules/@octokit/plugin-retry/dist-bundle/index.js @@ -146483,6 +179214,9 @@ retry.VERSION = VERSION7; var import_undici = __toESM(require_undici()); // src/repository.ts +function isRepositoryNwoStr(val) { + return val.includes("/"); +} function getRepositoryNwo() { return getRepositoryNwoFromEnv("GITHUB_REPOSITORY"); } @@ -146544,45 +179278,48 @@ function makeProxyRequestOptions(dispatcher) { }; } function createApiClientWithDetails(apiDetails, { allowExternal = false, proxy = void 0 } = {}) { - const auth2 = allowExternal && apiDetails.externalRepoAuth || apiDetails.auth; + const auth2 = allowExternal && apiDetails.externalRepoAuth !== void 0 ? apiDetails.externalRepoAuth : apiDetails.auth; const retryingOctokit = githubUtils.GitHub.plugin(retry); const requestOptions = makeProxyRequestOptions(proxy); - return new retryingOctokit( - githubUtils.getOctokitOptions(auth2, { - baseUrl: apiDetails.apiURL, - userAgent: `CodeQL-Action/${getActionVersion()}`, - log: { - debug: core5.debug, - info: core5.info, - warn: core5.warning, - error: core5.error - }, - request: requestOptions, - retry: { - doNotRetry: DO_NOT_RETRY_STATUSES - } - }) - ); + const opts = { + auth: auth2 !== void 0 && auth2.trim() !== "" ? `token ${auth2}` : void 0, + baseUrl: apiDetails.apiURL, + userAgent: `CodeQL-Action/${getActionVersion()}`, + log: { + debug: core6.debug, + info: core6.info, + warn: core6.warning, + error: core6.error + }, + request: requestOptions, + retry: { + doNotRetry: DO_NOT_RETRY_STATUSES + } + }; + return new retryingOctokit(opts); } function getApiDetails(env = getEnv()) { return { auth: getRequiredInput("token"), - url: env.getRequired("GITHUB_SERVER_URL" /* GITHUB_SERVER_URL */), - apiURL: env.getRequired("GITHUB_API_URL" /* GITHUB_API_URL */) + ...getCurrentInstance(env) }; } -function getApiClient(env = getEnv()) { - return createApiClientWithDetails(getApiDetails(env)); +function getApiClient(env = getEnv(), apiDetails) { + return createApiClientWithDetails(apiDetails ?? getApiDetails(env)); } function getApiClientWithExternalAuth(apiDetails, proxy) { return createApiClientWithDetails(apiDetails, { allowExternal: true, proxy }); } -function getAuthorizationHeaderFor(logger, apiDetails, url2) { +function getAuthorizationHeaderFor(logger2, apiDetails, url2) { + const token = apiDetails.auth?.trim(); + if (token === void 0 || token === "") { + return void 0; + } if (url2.startsWith(`${apiDetails.url}/`) || apiDetails.apiURL && url2.startsWith(`${apiDetails.apiURL}/`)) { - logger.debug(`Providing an authorization token.`); - return `token ${apiDetails.auth}`; + logger2.debug(`Providing an authorization token.`); + return `token ${token}`; } - logger.debug(`Not using an authorization token.`); + logger2.debug(`Not using an authorization token.`); return void 0; } var cachedGitHubVersion = void 0; @@ -146590,21 +179327,26 @@ async function getGitHubVersionFromApi(apiClient, apiDetails) { if (parseGitHubUrl(apiDetails.url) === GITHUB_DOTCOM_URL) { return { type: "GitHub.com" /* DOTCOM */ }; } - const response = await apiClient.rest.meta.get(); - if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === void 0) { - return { type: "GitHub.com" /* DOTCOM */ }; - } - if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === "ghe.com") { - return { type: "GitHub Enterprise Cloud with data residency" /* GHEC_DR */ }; + try { + const response = await apiClient.rest.meta.get(); + if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === void 0) { + return { type: "GitHub.com" /* DOTCOM */ }; + } + if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === "ghe.com") { + return { type: "GitHub Enterprise Cloud with data residency" /* GHEC_DR */ }; + } + const version = response.headers[GITHUB_ENTERPRISE_VERSION_HEADER]; + return { type: "GitHub Enterprise Server" /* GHES */, version }; + } catch (err) { + throw wrapApiConfigurationError(err); } - const version = response.headers[GITHUB_ENTERPRISE_VERSION_HEADER]; - return { type: "GitHub Enterprise Server" /* GHES */, version }; } async function getGitHubVersion() { if (cachedGitHubVersion === void 0) { + const apiDetails = getApiDetails(); cachedGitHubVersion = await getGitHubVersionFromApi( - getApiClient(), - getApiDetails() + createApiClientWithDetails(apiDetails), + apiDetails ); } return cachedGitHubVersion; @@ -146637,7 +179379,7 @@ async function getAnalysisKey() { const workflowPath = await getWorkflowRelativePath(); const jobName = getRequiredEnvParam("GITHUB_JOB"); analysisKey = `${workflowPath}:${jobName}`; - core5.exportVariable("CODEQL_ACTION_ANALYSIS_KEY" /* ANALYSIS_KEY */, analysisKey); + exportEnvVar("CODEQL_ACTION_ANALYSIS_KEY" /* ANALYSIS_KEY */, analysisKey); return analysisKey; } async function getAutomationID() { @@ -146671,14 +179413,6 @@ async function listActionsCaches(keyPrefix, ref) { } ); } -async function deleteActionsCache(id) { - const repositoryNwo = getRepositoryNwo(); - await getApiClient().rest.actions.deleteActionsCacheById({ - owner: repositoryNwo.owner, - repo: repositoryNwo.repo, - cache_id: id - }); -} async function getRepositoryProperties(repositoryNwo) { return getApiClient().request("GET /repos/:owner/:repo/properties/values", { owner: repositoryNwo.owner, @@ -146727,12 +179461,33 @@ function wrapApiConfigurationError(e) { // src/cli/output-cache.ts var fs3 = __toESM(require("fs")); var import_path = __toESM(require("path")); + +// src/cli/types.ts +var versionInfoBaseSchema = { + version: string, + features: optional(object({})), + /** + * The overlay version helps deal with backward incompatible changes for + * overlay analysis. When a precompiled query pack reports the same overlay + * version as the CodeQL CLI, we can use the CodeQL CLI to perform overlay + * analysis with that pack. Otherwise, if the overlay versions are different, + * or if either the pack or the CLI does not report an overlay version, + * we need to revert to non-overlay analysis. + */ + overlayVersion: optional(number) +}; + +// src/cli/output-cache.ts +var outputCacheSchema = { + cmd: string, + entries: object({}) +}; var COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json"; var cachedCodeQlVersion = void 0; function getCommandCacheFilePath(env) { return import_path.default.join(getTemporaryDirectory(env), COMMAND_CACHE_FILENAME); } -function cacheCodeQlVersion(env, cmd, version) { +function cacheCodeQlVersion(cacheFilePath, cmd, version) { if (cachedCodeQlVersion !== void 0) { throw new Error("cacheCodeQlVersion() should be called only once"); } @@ -146741,30 +179496,24 @@ function cacheCodeQlVersion(env, cmd, version) { cmd, entries: { version } }; - fs3.writeFileSync( - getCommandCacheFilePath(env), - JSON.stringify(outputCache), - "utf8" - ); + fs3.writeFileSync(cacheFilePath, JSON.stringify(outputCache), "utf8"); } -function getCachedCodeQlVersion(logger, env, cmd) { +function getCachedCodeQlVersion(logger2, cacheFilePath, cmd) { if (cachedCodeQlVersion !== void 0) { return cachedCodeQlVersion; } let serialized; try { - serialized = fs3.readFileSync(getCommandCacheFilePath(env), "utf8"); + serialized = fs3.readFileSync(cacheFilePath, "utf8"); } catch (e) { - logger.debug( - `Cannot read CLI-cache file ${getCommandCacheFilePath(env)}: ${e}` - ); + logger2.debug(`Cannot read CLI-cache file ${cacheFilePath}: ${e}`); return void 0; } let persisted; try { persisted = JSON.parse(serialized); } catch (e) { - logger.debug(`Cannot parse CLI-cache data as JSON: ${e}`); + logger2.debug(`Cannot parse CLI-cache data as JSON: ${e}`); return void 0; } if (!isOutputCache(persisted) || cmd !== void 0 && persisted.cmd !== cmd) { @@ -146774,12 +179523,10 @@ function getCachedCodeQlVersion(logger, env, cmd) { return cachedCodeQlVersion; } function isVersionInfo(x) { - const candidate = x; - return typeof candidate === "object" && candidate !== null && typeof candidate.version === "string" && (candidate.features === void 0 || typeof candidate.features === "object" && candidate.features !== null) && (candidate.overlayVersion === void 0 || typeof candidate.overlayVersion === "number"); + return isObject2(x) && validateSchema(versionInfoBaseSchema, x); } function isOutputCache(x) { - const candidate = x; - return typeof candidate === "object" && candidate !== null && typeof candidate.cmd === "string" && candidate.entries !== void 0 && isVersionInfo(candidate.entries.version); + return isObject2(x) && validateSchema(outputCacheSchema, x) && isObject2(x.entries) && isVersionInfo(x.entries.version); } // src/config/pack-registries.ts @@ -146803,7 +179550,7 @@ function parseRegistriesWithoutCredentials(registriesInput) { var fs4 = __toESM(require("fs")); var os2 = __toESM(require("os")); var path4 = __toESM(require("path")); -var core6 = __toESM(require_core()); +var core7 = __toESM(require_core()); var toolrunner2 = __toESM(require_toolrunner()); var io3 = __toESM(require_io()); var semver2 = __toESM(require_semver2()); @@ -146834,7 +179581,7 @@ async function getGitVersionOrThrow() { var runGitCommand = async function(workingDirectory, args, customErrorMessage, options) { let stdout = ""; let stderr = ""; - core6.debug(`Running git command: git ${args.join(" ")}`); + core7.debug(`Running git command: git ${args.join(" ")}`); try { await new toolrunner2.ToolRunner(await io3.which("git", true), args, { silent: true, @@ -146855,11 +179602,11 @@ var runGitCommand = async function(workingDirectory, args, customErrorMessage, o if (stderr.includes("not a git repository")) { reason = "The checkout path provided to the action does not appear to be a git repository."; } - core6.info(`git call failed. ${customErrorMessage} Error: ${reason}`); + core7.info(`git call failed. ${customErrorMessage} Error: ${reason}`); throw error3; } }; -var getCommitOid = async function(checkoutPath, ref = "HEAD") { +var getCommitOid = async function(env, checkoutPath, ref = "HEAD") { try { const stdout = await runGitCommand( checkoutPath, @@ -146868,7 +179615,7 @@ var getCommitOid = async function(checkoutPath, ref = "HEAD") { ); return stdout.trim(); } catch { - return getOptionalInput("sha") || getRequiredEnvParam("GITHUB_SHA"); + return getOptionalInput("sha") || env.getRequired("GITHUB_SHA" /* GITHUB_SHA */); } }; var determineBaseBranchHeadCommitOid = async function(checkoutPathOverride) { @@ -146945,7 +179692,7 @@ var getGitRoot = async function(sourceRoot) { ["rev-parse", "--show-toplevel"], `Cannot find Git repository root from the source root ${sourceRoot}.` ); - return stdout.trim(); + return path4.resolve(stdout.trim()); } catch { return void 0; } @@ -146978,12 +179725,12 @@ var getFileOidsUnderPath = async function(basePath) { } return fileOidMap; }; -function getRefFromEnv() { +function getRefFromEnv(env) { let refEnv; try { - refEnv = getRequiredEnvParam("GITHUB_REF"); + refEnv = env.getRequired("GITHUB_REF" /* GITHUB_REF */); } catch (e) { - const maybeRef = process.env["CODE_SCANNING_REF"]; + const maybeRef = env.getOptional("CODE_SCANNING_REF" /* CODE_SCANNING_REF */); if (maybeRef === void 0 || maybeRef.length === 0) { throw e; } @@ -146991,10 +179738,10 @@ function getRefFromEnv() { } return refEnv; } -async function getRef() { +async function getRef(env, checkoutPath) { const refInput = getOptionalInput("ref"); const shaInput = getOptionalInput("sha"); - const checkoutPath = getOptionalInput("checkout_path") || getOptionalInput("source-root") || getRequiredEnvParam("GITHUB_WORKSPACE"); + checkoutPath = checkoutPath ?? env.getRequired("GITHUB_WORKSPACE" /* GITHUB_WORKSPACE */); const hasRefInput = !!refInput; const hasShaInput = !!shaInput; if ((hasRefInput || hasShaInput) && !(hasRefInput && hasShaInput)) { @@ -147002,8 +179749,8 @@ async function getRef() { "Both 'ref' and 'sha' are required if one of them is provided." ); } - const ref = refInput || getRefFromEnv(); - const sha = shaInput || getRequiredEnvParam("GITHUB_SHA"); + const ref = refInput || getRefFromEnv(env); + const sha = shaInput || env.getRequired("GITHUB_SHA" /* GITHUB_SHA */); if (refInput) { return refInput; } @@ -147011,14 +179758,15 @@ async function getRef() { if (!pull_ref_regex.test(ref)) { return ref; } - const head = await getCommitOid(checkoutPath, "HEAD"); + const head = await getCommitOid(env, checkoutPath, "HEAD"); const hasChangedRef = sha !== head && await getCommitOid( + env, checkoutPath, ref.replace(/^refs\/pull\//, "refs/remotes/pull/") ) !== head; if (hasChangedRef) { const newRef = ref.replace(pull_ref_regex, "refs/pull/$1/head"); - core6.debug( + core7.debug( `No longer on merge commit, rewriting ref from ${ref} to ${newRef}.` ); return newRef; @@ -147029,16 +179777,16 @@ async function getRef() { function removeRefsHeadsPrefix(ref) { return ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : ref; } -async function isAnalyzingDefaultBranch() { - if (process.env.CODE_SCANNING_IS_ANALYZING_DEFAULT_BRANCH === "true") { +async function isAnalyzingDefaultBranch(env, checkoutPath) { + if (env.getOptional("CODE_SCANNING_IS_ANALYZING_DEFAULT_BRANCH") === "true") { return true; } - let currentRef = await getRef(); + let currentRef = await getRef(env, checkoutPath); currentRef = removeRefsHeadsPrefix(currentRef); - const event = getWorkflowEvent(); + const event = getWorkflowEvent(env); let defaultBranch = event?.repository?.default_branch; - if (getWorkflowEventName() === "schedule") { - defaultBranch = removeRefsHeadsPrefix(getRefFromEnv()); + if (getWorkflowEventName(env) === "schedule") { + defaultBranch = removeRefsHeadsPrefix(getRefFromEnv(env)); } return currentRef === defaultBranch; } @@ -147212,9 +179960,14 @@ function getAddressString(address) { } // src/status-report.ts +var ACTION_DISPLAY_NAMES = { + ["finish" /* Analyze */]: "analyze", + ["init-post" /* InitPost */]: "init post" +}; function getDisplayActionName(actionName) { - if (actionName === "finish" /* Analyze */) { - return "analyze"; + const displayName = ACTION_DISPLAY_NAMES[actionName]; + if (displayName !== void 0) { + return displayName; } return actionName; } @@ -147226,7 +179979,7 @@ function getJobUUID(action) { } const jobRunUuid = v4_default(); action.logger.info(`Job run UUID is ${jobRunUuid}.`); - action.actions.exportVariable("CODEQL_ACTION_JOB_RUN_UUID" /* JOB_RUN_UUID */, jobRunUuid); + action.env.export("CODEQL_ACTION_JOB_RUN_UUID" /* JOB_RUN_UUID */, jobRunUuid); return jobRunUuid; } function isFirstPartyAnalysis(actionName) { @@ -147268,18 +180021,18 @@ function getJobStatusDisplayName(status) { } function setJobStatusIfUnsuccessful(actionStatus) { if (actionStatus === "user-error") { - core7.exportVariable( + exportEnvVar( "CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */, process.env["CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */] ?? "JOB_STATUS_CONFIGURATION_ERROR" /* ConfigErrorStatus */ ); } else if (actionStatus === "failure" || actionStatus === "aborted") { - core7.exportVariable( + exportEnvVar( "CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */, process.env["CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */] ?? "JOB_STATUS_FAILURE" /* FailureStatus */ ); } } -function getRegistryTypesFromEnv(logger, env = getEnv()) { +function getRegistryTypesFromEnv(logger2, env = getEnv()) { const value = env.getOptional("CODEQL_PROXY_URLS" /* PROXY_URLS */); if (value === void 0) { return void 0; @@ -147287,13 +180040,13 @@ function getRegistryTypesFromEnv(logger, env = getEnv()) { try { const data = JSON.parse(value); if (!isArray(data)) { - logger.debug( + logger2.debug( `Expected '${"CODEQL_PROXY_URLS" /* PROXY_URLS */}' to contain a JSON array, but got '${typeof data}'.` ); return void 0; } if (!validateArray(registryBaseSchema, data)) { - logger.debug( + logger2.debug( `Expected '${"CODEQL_PROXY_URLS" /* PROXY_URLS */}' to contain a JSON array of registry objects, but got something else.` ); return void 0; @@ -147301,16 +180054,16 @@ function getRegistryTypesFromEnv(logger, env = getEnv()) { const types2 = new Set(data.map((r) => r.type)); return Array.from(types2).sort().join(","); } catch (err) { - logger.debug( + logger2.debug( `Failed to parse '${"CODEQL_PROXY_URLS" /* PROXY_URLS */}': ${getErrorMessage(err)}.` ); return void 0; } } -async function createStatusReportBase(actionName, status, actionStartedAt, config, diskInfo, logger, cause, exception) { +async function createStatusReportBase(actionName, status, actionStartedAt, config, diskInfo, logger2, cause, exception) { try { const commitOid = getOptionalInput("sha") || process.env["GITHUB_SHA"] || ""; - const ref = await getRef(); + const ref = await getRef(getEnv(), config?.repositoryRoot); const jobRunUUID = process.env["CODEQL_ACTION_JOB_RUN_UUID" /* JOB_RUN_UUID */] || ""; const workflowRunID = getWorkflowRunID(); const workflowRunAttempt = getWorkflowRunAttempt(); @@ -147320,14 +180073,17 @@ async function createStatusReportBase(actionName, status, actionStartedAt, confi let workflowStartedAt = process.env["CODEQL_WORKFLOW_STARTED_AT" /* WORKFLOW_STARTED_AT */]; if (workflowStartedAt === void 0) { workflowStartedAt = actionStartedAt.toISOString(); - core7.exportVariable("CODEQL_WORKFLOW_STARTED_AT" /* WORKFLOW_STARTED_AT */, workflowStartedAt); + exportEnvVar("CODEQL_WORKFLOW_STARTED_AT" /* WORKFLOW_STARTED_AT */, workflowStartedAt); } const runnerOs = getRequiredEnvParam("RUNNER_OS"); - const codeQlCliVersion = getCachedCodeQlVersion(logger, getEnv()); + const codeQlCliVersion = getCachedCodeQlVersion( + logger2, + getCommandCacheFilePath(getEnv()) + ); const actionRef = process.env["GITHUB_ACTION_REF"] || ""; const testingEnvironment = getTestingEnvironment(); if (testingEnvironment) { - core7.exportVariable("CODEQL_ACTION_TESTING_ENVIRONMENT" /* TESTING_ENVIRONMENT */, testingEnvironment); + exportEnvVar("CODEQL_ACTION_TESTING_ENVIRONMENT" /* TESTING_ENVIRONMENT */, testingEnvironment); } const isSteadyStateDefaultSetupRun = process.env["CODE_SCANNING_IS_STEADY_STATE_DEFAULT_SETUP"] === "true"; const statusReport = { @@ -147346,7 +180102,7 @@ async function createStatusReportBase(actionName, status, actionStartedAt, confi job_name: jobName, job_run_uuid: jobRunUUID, ref, - registry_types: getRegistryTypesFromEnv(logger), + registry_types: getRegistryTypesFromEnv(logger2), runner_os: runnerOs, started_at: workflowStartedAt, status, @@ -147359,7 +180115,7 @@ async function createStatusReportBase(actionName, status, actionStartedAt, confi try { statusReport.actions_event_name = getWorkflowEventName(); } catch (e) { - logger.warning( + logger2.warning( `Could not determine the workflow event name: ${getErrorMessage(e)}.` ); } @@ -147398,7 +180154,7 @@ async function createStatusReportBase(actionName, status, actionStartedAt, confi } return statusReport; } catch (e) { - logger.warning( + logger2.warning( `Failed to gather information for telemetry: ${getErrorMessage(e)}. Will skip sending status report.` ); if (isInTestMode()) { @@ -147412,9 +180168,9 @@ var INCOMPATIBLE_MSG = "CodeQL Action version is incompatible with the API endpo async function sendStatusReport(statusReport) { setJobStatusIfUnsuccessful(statusReport.status); const statusReportJSON = JSON.stringify(statusReport); - core7.debug(`Sending status report: ${statusReportJSON}`); + core8.debug(`Sending status report: ${statusReportJSON}`); if (isInTestMode()) { - core7.debug("In test mode. Status reports are not uploaded."); + core8.debug("In test mode. Status reports are not uploaded."); return; } const nwo = getRepositoryNwo(); @@ -147434,28 +180190,28 @@ async function sendStatusReport(statusReport) { switch (httpError.status) { case 403: if (getWorkflowEventName() === "push" && process.env["GITHUB_ACTOR"] === "dependabot[bot]") { - core7.warning( + core8.warning( `Workflows triggered by Dependabot on the "push" event run with read-only access. Uploading CodeQL results requires write access. To use CodeQL with Dependabot, please ensure you are using the "pull_request" event for this workflow and avoid triggering on the "push" event for Dependabot branches. See ${"https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning#scanning-on-push" /* SCANNING_ON_PUSH */} for more information on how to configure these events.` ); } else { - core7.warning( + core8.warning( `This run of the CodeQL Action does not have permission to access the CodeQL Action API endpoints. This could be because the Action is running on a pull request from a fork. If not, please ensure the workflow has at least the 'security-events: read' permission. Details: ${httpError.message}` ); } return; case 404: - core7.warning(httpError.message); + core8.warning(httpError.message); return; case 422: if (getRequiredEnvParam("GITHUB_SERVER_URL") !== GITHUB_DOTCOM_URL) { - core7.debug(INCOMPATIBLE_MSG); + core8.debug(INCOMPATIBLE_MSG); } else { - core7.debug(OUT_OF_DATE_MSG); + core8.debug(OUT_OF_DATE_MSG); } return; } } - core7.warning( + core8.warning( `An unexpected error occurred when sending a status report: ${getErrorMessage( e )}` @@ -147508,7 +180264,7 @@ async function createInitWithConfigStatusReport(config, initStatusReport, config ) }; } -async function sendUnhandledErrorStatusReport(actionName, actionStartedAt, error3, logger) { +async function sendUnhandledErrorStatusReport(actionName, actionStartedAt, error3, logger2) { try { const statusReport = await createStatusReportBase( actionName, @@ -147516,7 +180272,7 @@ async function sendUnhandledErrorStatusReport(actionName, actionStartedAt, error actionStartedAt, void 0, void 0, - logger, + logger2, `Unhandled CodeQL Action error: ${getErrorMessage(error3)}`, error3 instanceof Error ? error3.stack : void 0 ); @@ -147524,7 +180280,7 @@ async function sendUnhandledErrorStatusReport(actionName, actionStartedAt, error await sendStatusReport(statusReport); } } catch (e) { - logger.warning( + logger2.warning( `Failed to send the unhandled error status report: ${getErrorMessage(e)}.` ); if (isInTestMode()) { @@ -147534,23 +180290,29 @@ async function sendUnhandledErrorStatusReport(actionName, actionStartedAt, error } // src/action-common.ts +function extendActionState(state, extra) { + return { ...state, ...extra }; +} async function runInActions(action) { const startedAt = /* @__PURE__ */ new Date(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); const env = getEnv(); const actionsEnv = getActionsEnv(); try { const actionState = { name: action.name, startedAt, - logger, + platform: process.platform, + arch: process.arch, + osRelease: os4.release(), + logger: logger2, env, actions: actionsEnv }; getJobUUID(actionState); await action.run(actionState); } catch (error3) { - core8.setFailed( + core9.setFailed( `${getDisplayActionName(action.name)} action failed: ${getErrorMessage(error3)}` ); const statusReportError = action.transformTelemetryError !== void 0 ? action.transformTelemetryError(wrapError(error3)) : error3; @@ -147558,7 +180320,7 @@ async function runInActions(action) { action.name, startedAt, statusReportError, - logger + logger2 ); } } @@ -147566,11 +180328,11 @@ async function runInActions(action) { // src/feature-flags.ts var fs6 = __toESM(require("fs")); var path6 = __toESM(require("path")); -var semver4 = __toESM(require_semver2()); +var semver3 = __toESM(require_semver2()); // src/defaults.json -var bundleVersion = "codeql-bundle-v2.26.3"; -var cliVersion = "2.26.3"; +var bundleVersion = "codeql-bundle-v2.27.4"; +var cliVersion = "2.27.4"; // src/overlay/index.ts var fs5 = __toESM(require("fs")); @@ -147589,7 +180351,7 @@ async function writeBaseDatabaseOidsFile(config, sourceRoot) { const baseDatabaseOidsFilePath = getBaseDatabaseOidsFilePath(config); await fs5.promises.writeFile(baseDatabaseOidsFilePath, gitFileOidsJson); } -async function readBaseDatabaseOidsFile(config, logger) { +async function readBaseDatabaseOidsFile(config, logger2) { const baseDatabaseOidsFilePath = getBaseDatabaseOidsFilePath(config); try { const contents = await fs5.promises.readFile( @@ -147598,27 +180360,27 @@ async function readBaseDatabaseOidsFile(config, logger) { ); return JSON.parse(contents); } catch (e) { - logger.error( + logger2.error( `Failed to read overlay-base file OIDs from ${baseDatabaseOidsFilePath}: ${e.message || e}` ); throw e; } } -async function writeOverlayChangesFile(config, sourceRoot, logger) { - const baseFileOids = await readBaseDatabaseOidsFile(config, logger); +async function writeOverlayChangesFile(config, sourceRoot, logger2) { + const baseFileOids = await readBaseDatabaseOidsFile(config, logger2); const overlayFileOids = await getFileOidsUnderPath(sourceRoot); const oidChangedFiles = computeChangedFiles(baseFileOids, overlayFileOids); - logger.info( + logger2.info( `Found ${oidChangedFiles.length} changed file(s) under ${sourceRoot} from OID comparison.` ); - const diffRangeFiles = await getDiffRangeFilePaths(sourceRoot, logger); + const diffRangeFiles = await getDiffRangeFilePaths(sourceRoot, logger2); const changedFiles = [.../* @__PURE__ */ new Set([...oidChangedFiles, ...diffRangeFiles])]; const changedFilesJson = JSON.stringify({ changes: changedFiles }); const overlayChangesFile = path5.join( getTemporaryDirectory(), "overlay-changes.json" ); - logger.debug( + logger2.debug( `Writing overlay changed files to ${overlayChangesFile}: ${changedFilesJson}` ); await fs5.promises.writeFile(overlayChangesFile, changedFilesJson); @@ -147638,10 +180400,10 @@ function computeChangedFiles(baseFileOids, overlayFileOids) { } return changes; } -async function getDiffRangeFilePaths(sourceRoot, logger) { +async function getDiffRangeFilePaths(sourceRoot, logger2) { const jsonFilePath = getDiffRangesJsonFilePath(); if (!fs5.existsSync(jsonFilePath)) { - logger.debug( + logger2.debug( `No diff ranges JSON file found at ${jsonFilePath}; skipping.` ); return []; @@ -147650,7 +180412,7 @@ async function getDiffRangeFilePaths(sourceRoot, logger) { try { contents = await fs5.promises.readFile(jsonFilePath, "utf8"); } catch (e) { - logger.warning( + logger2.warning( `Failed to read diff ranges JSON file at ${jsonFilePath}: ${e}` ); return []; @@ -147659,12 +180421,12 @@ async function getDiffRangeFilePaths(sourceRoot, logger) { try { diffRanges = JSON.parse(contents); } catch (e) { - logger.warning( + logger2.warning( `Failed to parse diff ranges JSON file at ${jsonFilePath}: ${e}` ); return []; } - logger.debug( + logger2.debug( `Read ${diffRanges.length} diff range(s) from ${jsonFilePath} for overlay changes.` ); const repoRoot = await getGitRoot(sourceRoot); @@ -147674,7 +180436,7 @@ async function getDiffRangeFilePaths(sourceRoot, logger) { "Cannot determine git root to convert diff range paths relative to source-root. Failing to avoid omitting files from the analysis." ); } - logger.warning( + logger2.warning( "Cannot determine git root; returning diff range paths as-is." ); return [...new Set(diffRanges.map((r) => r.path))]; @@ -147686,14 +180448,9 @@ async function getDiffRangeFilePaths(sourceRoot, logger) { } // src/tools-features.ts -var semver3 = __toESM(require_semver2()); function isSupportedToolsFeature(versionInfo, feature) { return !!versionInfo.features && versionInfo.features[feature]; } -var SafeArtifactUploadVersion = "2.20.3"; -function isSafeArtifactUpload(codeQlVersion) { - return !codeQlVersion ? true : semver3.gte(codeQlVersion, SafeArtifactUploadVersion); -} // src/feature-flags.ts var DEFAULT_VERSION_FEATURE_FLAG_PREFIX = "default_codeql_version_"; @@ -147714,9 +180471,9 @@ var featureConfig = { envVar: "CODEQL_ACTION_ALLOW_MULTIPLE_ANALYSIS_KINDS", minimumVersion: void 0 }, - ["cleanup_trap_caches" /* CleanupTrapCaches */]: { + ["check_unsupported_traced_analysis" /* CheckUnsupportedTracedAnalysis */]: { defaultValue: false, - envVar: "CODEQL_ACTION_CLEANUP_TRAP_CACHES", + envVar: "CODEQL_ACTION_CHECK_UNSUPPORTED_TRACED_ANALYSIS", minimumVersion: void 0 }, ["config_file_repository_property" /* ConfigFileRepositoryProperty */]: { @@ -147728,7 +180485,7 @@ var featureConfig = { defaultValue: false, envVar: "CODEQL_EXTRACTOR_CPP_AUTOINSTALL_DEPENDENCIES", legacyApi: true, - minimumVersion: "2.15.0" + minimumVersion: void 0 }, ["csharp_cache_bmn" /* CsharpCacheBuildModeNone */]: { defaultValue: false, @@ -147867,21 +180624,6 @@ var featureConfig = { minimumVersion: CODEQL_OVERLAY_MINIMUM_VERSION_RUBY }, // Other overlay-related feature flags - ["overlay_analysis_disable_trap_caching" /* OverlayAnalysisDisableTrapCaching */]: { - defaultValue: false, - envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_DISABLE_TRAP_CACHING", - minimumVersion: void 0 - }, - ["overlay_analysis_match_codeql_version" /* OverlayAnalysisMatchCodeqlVersion */]: { - defaultValue: false, - envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_MATCH_CODEQL_VERSION", - minimumVersion: void 0 - }, - ["overlay_analysis_match_codeql_version_dry_run" /* OverlayAnalysisMatchCodeqlVersionDryRun */]: { - defaultValue: false, - envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_MATCH_CODEQL_VERSION_DRY_RUN", - minimumVersion: void 0 - }, ["overlay_analysis_min_disk_8_gb" /* OverlayAnalysisMinDisk8Gb */]: { defaultValue: false, envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_MIN_DISK_8_GB", @@ -147949,6 +180691,11 @@ var featureConfig = { envVar: "CODEQL_ACTION_START_PROXY_USE_FEATURES_RELEASE", minimumVersion: void 0 }, + ["abort_unsupported_traced_analysis" /* AbortUnsupportedTracedAnalysis */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_ABORT_UNSUPPORTED_TRACED_ANALYSIS", + minimumVersion: void 0 + }, ["tools_repository_property" /* ToolsRepositoryProperty */]: { defaultValue: false, envVar: "CODEQL_ACTION_TOOLS_REPOSITORY_PROPERTY", @@ -147968,8 +180715,8 @@ var featureConfig = { }; var FEATURE_FLAGS_FILE_NAME = "cached-feature-flags.json"; var OfflineFeatures = class { - constructor(logger) { - this.logger = logger; + constructor(logger2) { + this.logger = logger2; } logger; async getEnabledDefaultCliVersions(_variant) { @@ -148027,7 +180774,7 @@ var OfflineFeatures = class { } const minimumVersion2 = config.minimumVersion; if (codeql && minimumVersion2) { - if (!await codeQlVersionAtLeast(codeql, minimumVersion2)) { + if (!await codeql.isVersionAtLeast(minimumVersion2)) { this.logger.debug( `Feature ${feature} is disabled because the CodeQL CLI version is older than the minimum version ${minimumVersion2}.` ); @@ -148071,12 +180818,12 @@ var OfflineFeatures = class { }; var Features = class extends OfflineFeatures { gitHubFeatureFlags; - constructor(repositoryNwo, tempDir, logger) { - super(logger); + constructor(repositoryNwo, tempDir, logger2) { + super(logger2); this.gitHubFeatureFlags = new GitHubFeatureFlags( repositoryNwo, path6.join(tempDir, FEATURE_FLAGS_FILE_NAME), - logger + logger2 ); } async getEnabledDefaultCliVersions(variant) { @@ -148113,10 +180860,10 @@ var Features = class extends OfflineFeatures { } }; var GitHubFeatureFlags = class { - constructor(repositoryNwo, featureFlagsFile, logger) { + constructor(repositoryNwo, featureFlagsFile, logger2) { this.repositoryNwo = repositoryNwo; this.featureFlagsFile = featureFlagsFile; - this.logger = logger; + this.logger = logger2; this.hasAccessedRemoteFeatureFlags = false; } repositoryNwo; @@ -148134,7 +180881,7 @@ var GitHubFeatureFlags = class { DEFAULT_VERSION_FEATURE_FLAG_PREFIX.length, f.length - DEFAULT_VERSION_FEATURE_FLAG_SUFFIX.length ).replace(/_/g, "."); - if (!semver4.valid(version)) { + if (!semver3.valid(version)) { this.logger.warning( `Ignoring feature flag ${f} as it does not specify a valid CodeQL version.` ); @@ -148151,7 +180898,7 @@ var GitHubFeatureFlags = class { const response = await this.getAllFeatures(); const sortedCliVersions = Object.entries(response).map( ([f, isEnabled]) => isEnabled ? this.getCliVersionFromFeatureFlag(f) : void 0 - ).filter((f) => f !== void 0).sort(semver4.rcompare); + ).filter((f) => f !== void 0).sort(semver3.rcompare); if (sortedCliVersions.length === 0) { this.logger.warning( `Feature flags do not specify a default CLI version. Falling back to the CLI version shipped with the Action. This is ${cliVersion}.` @@ -148284,14 +181031,14 @@ var GitHubFeatureFlags = class { function supportsFeatureFlags(githubVariant) { return githubVariant === "GitHub.com" /* DOTCOM */ || githubVariant === "GitHub Enterprise Cloud with data residency" /* GHEC_DR */; } -function initFeatures(gitHubVersion, repositoryNwo, tempDir, logger) { +function initFeatures(gitHubVersion, repositoryNwo, tempDir, logger2) { if (!supportsFeatureFlags(gitHubVersion.type)) { - logger.debug( + logger2.debug( "Not running against github.com. Using default values for all features." ); - return new OfflineFeatures(logger); + return new OfflineFeatures(logger2); } else { - return new Features(repositoryNwo, tempDir, logger); + return new Features(repositoryNwo, tempDir, logger2); } } @@ -148331,7 +181078,7 @@ function isOnlyCodeScanningEnabled(analysisKinds) { function makeAnalysisKindUsageError(message) { return `The \`analysis-kinds\` input is experimental and for GitHub-internal use only. Its behaviour may change at any time or be removed entirely. ${message}`; } -async function getAnalysisKinds(logger, features, skipCache = false) { +async function getAnalysisKinds(logger2, features, skipCache = false) { if (!skipCache && cachedAnalysisKinds !== void 0) { return cachedAnalysisKinds; } @@ -148340,7 +181087,7 @@ async function getAnalysisKinds(logger, features, skipCache = false) { ); if (!isInTestMode() && !isDynamicWorkflow() && !isOnlyCodeScanningEnabled(analysisKinds)) { const codeQualityHint = analysisKinds.includes("code-quality" /* CodeQuality */) ? " If your intention is to use quality queries outside of Code Quality, use the `queries` input with `code-quality` instead." : ""; - logger.error( + logger2.error( makeAnalysisKindUsageError( `An analysis kind other than \`code-scanning\` was specified in a custom workflow. This is not supported and will become a fatal error in a future version of the CodeQL Action.${codeQualityHint}` ) @@ -148348,7 +181095,7 @@ async function getAnalysisKinds(logger, features, skipCache = false) { } const qualityQueriesInput = getOptionalInput("quality-queries"); if (qualityQueriesInput !== void 0) { - logger.warning( + logger2.warning( "The `quality-queries` input is deprecated and will be removed in a future version of the CodeQL Action. Use the `analysis-kinds` input to configure different analysis kinds instead." ); } @@ -148366,7 +181113,7 @@ async function getAnalysisKinds(logger, features, skipCache = false) { } } if (!isInTestMode() && analysisKinds.length > 1 && !await features.getValue("allow_multiple_analysis_kinds" /* AllowMultipleAnalysisKinds */)) { - logger.error( + logger2.error( makeAnalysisKindUsageError( "Specifying multiple values as input is no longer supported. Continuing with only `analysis-kinds: code-scanning`." ) @@ -148440,23 +181187,22 @@ var SarifScanOrder = [ ]; // src/analyze.ts -var fs17 = __toESM(require("fs")); +var fs19 = __toESM(require("fs")); var path16 = __toESM(require("path")); -var import_perf_hooks3 = require("perf_hooks"); -var io5 = __toESM(require_io()); - -// src/autobuild.ts -var core13 = __toESM(require_core()); +var import_perf_hooks5 = require("perf_hooks"); +var io6 = __toESM(require_io()); // src/codeql.ts -var fs16 = __toESM(require("fs")); +var fs18 = __toESM(require("fs")); var path15 = __toESM(require("path")); var core12 = __toESM(require_core()); -var toolrunner3 = __toESM(require_toolrunner()); +var toolrunner4 = __toESM(require_toolrunner()); +var semver11 = __toESM(require_semver2()); // src/cli-errors.ts var SUPPORTED_PLATFORMS = [ ["linux", "x64"], + ["linux", "arm64"], ["win32", "x64"], ["darwin", "x64"], ["darwin", "arm64"] @@ -148703,17 +181449,16 @@ function wrapCliConfigurationError(cliError) { } // src/config-utils.ts -var fs10 = __toESM(require("fs")); +var fs11 = __toESM(require("fs")); var path11 = __toESM(require("path")); -var import_perf_hooks = require("perf_hooks"); -var core10 = __toESM(require_core()); +var import_perf_hooks2 = require("perf_hooks"); // src/caching-utils.ts var crypto2 = __toESM(require("crypto")); -var core9 = __toESM(require_core()); -async function getTotalCacheSize(paths, logger, quiet = false) { +var core10 = __toESM(require_core()); +async function getTotalCacheSize(paths, logger2, quiet = false) { const sizes = await Promise.all( - paths.map((cacheDir2) => tryGetFolderBytes(cacheDir2, logger, quiet)) + paths.map((cacheDir2) => tryGetFolderBytes(cacheDir2, logger2, quiet)) ); return sizes.map((a) => a || 0).reduce((a, b) => a + b, 0); } @@ -148739,7 +181484,7 @@ function getCachingKind(input) { case "restore": return "restore" /* Restore */; default: - core9.warning( + core10.warning( `Unrecognized 'dependency-caching' input: ${input}. Defaulting to 'none'.` ); return "none" /* None */; @@ -148753,7 +181498,7 @@ function createCacheKeyHash(components) { function getDependencyCachingEnabled() { const dependencyCaching = getOptionalInput("dependency-caching") || process.env["CODEQL_ACTION_DEPENDENCY_CACHING" /* DEPENDENCY_CACHING */]; if (dependencyCaching !== void 0) return getCachingKind(dependencyCaching); - if (!isHostedRunner()) return "none" /* None */; + if (!looksLikeHostedRunner()) return "none" /* None */; if (!isDefaultSetup()) return "none" /* None */; return "none" /* None */; } @@ -148761,13 +181506,17 @@ function getDependencyCachingEnabled() { // src/config/db-config.ts var path8 = __toESM(require("path")); var jsonschema = __toESM(require_lib2()); -var semver5 = __toESM(require_semver2()); +var semver4 = __toESM(require_semver2()); // src/diagnostics.ts -var import_fs = require("fs"); +var fs7 = __toESM(require("fs")); var import_path2 = __toESM(require("path")); -var unwrittenDiagnostics = []; -var unwrittenDefaultLanguageDiagnostics = []; +var TEMP_DIAGNOSTIC_DIR_NAME = "codeql-action-temp-diagnostics"; +var CODEQL_ACTION_DIAGNOSTIC_SUBDIR_PARTS = [ + "diagnostic", + "codeql-action" +]; +var temporaryDiagnostics = []; var diagnosticCounter = 0; function makeDiagnostic(id, name, data = void 0) { return { @@ -148776,19 +181525,38 @@ function makeDiagnostic(id, name, data = void 0) { source: { ...data?.source, id, name } }; } -function addDiagnostic(config, language, diagnostic) { - const logger = getActionsLogger(); +function getLanguageDiagnosticsPath(basePath, language) { + return import_path2.default.resolve( + basePath, + language, + ...CODEQL_ACTION_DIAGNOSTIC_SUBDIR_PARTS + ); +} +function getTempDiagnosticsRoot(tmpDir) { + return import_path2.default.resolve(tmpDir, TEMP_DIAGNOSTIC_DIR_NAME); +} +function getTempLanguageDiagnosticsPath(tmpDir, language) { + const root = getTempDiagnosticsRoot(tmpDir); + if (language !== void 0) { + return getLanguageDiagnosticsPath(root, language); + } + return import_path2.default.resolve(root, ...CODEQL_ACTION_DIAGNOSTIC_SUBDIR_PARTS); +} +function getDatabaseDiagnosticsPath(config, language) { + return getLanguageDiagnosticsPath(config.dbLocation, language); +} +function addDiagnostic(config, language, diagnostic, logger2 = getActionsLogger()) { const databasePath = language ? getCodeQLDatabasePath(config, language) : config.dbLocation; - if ((0, import_fs.existsSync)(databasePath)) { - writeDiagnostic(config, language, diagnostic); + if (fs7.existsSync(databasePath)) { + writeDiagnostic({ logger: logger2 }, config, language, diagnostic); } else { - logger.debug( + logger2.debug( `Writing a diagnostic for ${language}, but the database at ${databasePath} does not exist yet.` ); - unwrittenDiagnostics.push({ diagnostic, language }); + writeTemporaryDiagnosticFile(logger2, config.tempDir, language, diagnostic); } } -function addNoLanguageDiagnostic(config, diagnostic) { +function addNoLanguageDiagnostic(config, diagnostic, logger2 = getActionsLogger()) { if (config !== void 0) { addDiagnostic( config, @@ -148798,58 +181566,106 @@ function addNoLanguageDiagnostic(config, diagnostic) { diagnostic ); } else { - unwrittenDefaultLanguageDiagnostics.push(diagnostic); + logger2.debug( + `Writing a diagnostic not associated with any language, but we have no configuration to tell us where the database is yet.` + ); + writeTemporaryDiagnosticFile( + logger2, + getTemporaryDirectory(), + void 0, + diagnostic + ); } } -function writeDiagnostic(config, language, diagnostic) { - const logger = getActionsLogger(); - const databasePath = language ? getCodeQLDatabasePath(config, language) : config.dbLocation; - const diagnosticsPath = import_path2.default.resolve( - databasePath, - "diagnostic", - "codeql-action" - ); +function writeTemporaryDiagnosticFile(logger2, tempDir, language, diagnostic) { + const tempDiagnosticsPath = getTempLanguageDiagnosticsPath(tempDir, language); try { - (0, import_fs.mkdirSync)(diagnosticsPath, { recursive: true }); - const uniqueSuffix = (diagnosticCounter++).toString(); - const sanitizedTimestamp = diagnostic.timestamp.replace( - /[^a-zA-Z0-9.-]/g, - "" - ); - const jsonPath = import_path2.default.resolve( - diagnosticsPath, - `codeql-action-${sanitizedTimestamp}-${uniqueSuffix}.json` + const diagnosticPath = writeDiagnosticFile(tempDiagnosticsPath, diagnostic); + temporaryDiagnostics.push({ path: diagnosticPath, language }); + } catch (err) { + logger2.warning( + `Unable to write temporary diagnostic to '${tempDiagnosticsPath}': ${getErrorMessage(err)} + +${JSON.stringify(diagnostic)}` ); - (0, import_fs.writeFileSync)(jsonPath, JSON.stringify(diagnostic)); + } +} +function writeDiagnosticFile(diagnosticsPath, diagnostic) { + fs7.mkdirSync(diagnosticsPath, { recursive: true }); + const uniqueSuffix = (diagnosticCounter++).toString(); + const sanitizedTimestamp = diagnostic.timestamp.replace( + /[^a-zA-Z0-9.-]/g, + "" + ); + const jsonPath = import_path2.default.resolve( + diagnosticsPath, + `codeql-action-${sanitizedTimestamp}-${uniqueSuffix}.json` + ); + fs7.writeFileSync(jsonPath, JSON.stringify(diagnostic)); + return jsonPath; +} +function writeDiagnostic(action, config, language, diagnostic) { + const diagnosticsPath = getDatabaseDiagnosticsPath(config, language); + try { + writeDiagnosticFile(diagnosticsPath, diagnostic); } catch (err) { - logger.warning(`Unable to write diagnostic message to database: ${err}`); - logger.debug(JSON.stringify(diagnostic)); + action.logger.warning( + `Unable to write diagnostic message to database: ${err}` + ); + action.logger.debug(JSON.stringify(diagnostic)); } } -function logUnwrittenDiagnostics() { - const logger = getActionsLogger(); - const num = unwrittenDiagnostics.length; - if (num > 0) { - logger.warning( - `${num} diagnostic(s) could not be written to the database and will not appear on the Tool Status Page.` +function logTemporaryDiagnostics(action) { + const num = temporaryDiagnostics.length; + if (num > 0 && action.logger.isDebug()) { + action.logger.startGroup("Diagnostics in temporary location"); + action.logger.debug( + `${num} diagnostic(s) were not moved to the database and remain in the temporary directory.` ); - for (const unwritten of unwrittenDiagnostics) { - logger.debug(JSON.stringify(unwritten.diagnostic)); + for (const temporary of temporaryDiagnostics) { + try { + action.logger.debug(fs7.readFileSync(temporary.path, "utf-8")); + } catch (err) { + action.logger.debug( + `Failed to read diagnostics from temporary location at '${temporary.path}': ${getErrorMessage(err)}` + ); + } } + action.logger.endGroup(); } } -function flushDiagnostics(config) { - const logger = getActionsLogger(); - const diagnosticsCount = unwrittenDiagnostics.length + unwrittenDefaultLanguageDiagnostics.length; - logger.debug(`Writing ${diagnosticsCount} diagnostic(s) to database.`); - for (const unwritten of unwrittenDiagnostics) { - writeDiagnostic(config, unwritten.language, unwritten.diagnostic); - } - for (const unwritten of unwrittenDefaultLanguageDiagnostics) { - addNoLanguageDiagnostic(config, unwritten); +function flushDiagnostics(action, config) { + const diagnosticsCount = temporaryDiagnostics.length; + action.logger.debug( + `Moving ${diagnosticsCount} diagnostic(s) to their respective databases.` + ); + const failedFlushDiagnostics = []; + for (const temporary of temporaryDiagnostics) { + const directory = getDatabaseDiagnosticsPath( + config, + temporary.language ?? config.languages[0] + ); + const filename = import_path2.default.basename(temporary.path); + const destination = import_path2.default.join(directory, filename); + try { + fs7.mkdirSync(directory, { recursive: true }); + try { + fs7.renameSync(temporary.path, destination); + } catch (renameErr) { + if (!isErrnoException(renameErr) || renameErr.code !== "EXDEV") { + throw renameErr; + } + fs7.copyFileSync(temporary.path, destination); + fs7.unlinkSync(temporary.path); + } + } catch (err) { + action.logger.warning( + `Failed to relocate '${temporary.path}' to '${destination}': ${getErrorMessage(err)}` + ); + failedFlushDiagnostics.push(temporary); + } } - unwrittenDiagnostics = []; - unwrittenDefaultLanguageDiagnostics = []; + temporaryDiagnostics = failedFlushDiagnostics; } function makeTelemetryDiagnostic(id, name, attributes, tags) { return makeDiagnostic(id, name, { @@ -148948,7 +181764,7 @@ var repositoryPropertyParsers = { ["github-codeql-file-coverage-on-prs" /* FILE_COVERAGE_ON_PRS */]: booleanProperty, ["github-codeql-tools" /* TOOLS */]: stringProperty }; -async function loadPropertiesFromApi(logger, repositoryNwo) { +async function loadPropertiesFromApi(logger2, repositoryNwo) { try { const response = await getRepositoryProperties(repositoryNwo); const remoteProperties = response.data; @@ -148957,7 +181773,7 @@ async function loadPropertiesFromApi(logger, repositoryNwo) { `Expected repository properties API to return an array, but got: ${JSON.stringify(response.data)}` ); } - logger.debug( + logger2.debug( `Retrieved ${remoteProperties.length} repository properties: ${remoteProperties.map((p) => p.property_name).join(", ")}` ); const properties = {}; @@ -148969,26 +181785,26 @@ async function loadPropertiesFromApi(logger, repositoryNwo) { ); } if (isKnownPropertyName(property.property_name)) { - setProperty(properties, property.property_name, property.value, logger); + setProperty(properties, property.property_name, property.value, logger2); } else if (property.property_name.startsWith(GITHUB_CODEQL_PROPERTY_PREFIX) && !isDynamicWorkflow()) { unrecognisedProperties.push(property.property_name); } } if (Object.keys(properties).length === 0) { - logger.debug("No known repository properties were found."); + logger2.debug("No known repository properties were found."); } else { - logger.debug( + logger2.debug( "Loaded the following values for the repository properties:" ); for (const [property, value] of Object.entries(properties).sort( ([nameA], [nameB]) => nameA.localeCompare(nameB) )) { - logger.debug(` ${property}: ${value}`); + logger2.debug(` ${property}: ${value}`); } } if (unrecognisedProperties.length > 0) { const unrecognisedPropertyList = unrecognisedProperties.map((name) => `'${name}'`).join(", "); - logger.warning( + logger2.warning( `Found repository properties (${unrecognisedPropertyList}), which look like CodeQL Action repository properties, but which are not understood by this version of the CodeQL Action. Do you need to update to a newer version?` ); } @@ -148999,19 +181815,19 @@ async function loadPropertiesFromApi(logger, repositoryNwo) { ); } } -function setProperty(properties, name, value, logger) { +function setProperty(properties, name, value, logger2) { const propertyOptions = repositoryPropertyParsers[name]; if (propertyOptions.validate(value)) { - properties[name] = propertyOptions.parse(name, value, logger); + properties[name] = propertyOptions.parse(name, value, logger2); } else { throw new Error( `Unexpected value for repository property '${name}' (${typeof value}), got: ${JSON.stringify(value)}` ); } } -function parseBooleanRepositoryProperty(name, value, logger) { +function parseBooleanRepositoryProperty(name, value, logger2) { if (value !== "true" && value !== "false") { - logger.warning( + logger2.warning( `Repository property '${name}' has unexpected value '${value}'. Expected 'true' or 'false'. Defaulting to false.` ); } @@ -149026,21 +181842,21 @@ var KNOWN_REPOSITORY_PROPERTY_NAMES = new Set( function isKnownPropertyName(name) { return KNOWN_REPOSITORY_PROPERTY_NAMES.has(name); } -async function loadRepositoryProperties(repositoryNwo, logger) { +async function loadRepositoryProperties(repositoryNwo, logger2) { const repositoryOwnerType = github2.context.payload.repository?.owner.type; - logger.debug( + logger2.debug( `Repository owner type is '${repositoryOwnerType ?? "unknown"}'.` ); if (repositoryOwnerType === "User") { - logger.debug( + logger2.debug( "Skipping loading repository properties because the repository is owned by a user and therefore cannot have repository properties." ); return new Success({}); } try { - return new Success(await loadPropertiesFromApi(logger, repositoryNwo)); + return new Success(await loadPropertiesFromApi(logger2, repositoryNwo)); } catch (error3) { - logger.warning( + logger2.warning( `Failed to load repository properties: ${getErrorMessage(error3)}` ); return new Failure(error3); @@ -149048,6 +181864,13 @@ async function loadRepositoryProperties(repositoryNwo, logger) { } // src/config/db-config.ts +var defaultSuites = /* @__PURE__ */ new Set([ + "security-experimental", + "security-extended", + "security-and-quality", + "code-quality", + "code-scanning" +]); var ORG_SCHEMA = { /** An array of model pack names. */ "model-packs": optional(array(string)) @@ -149061,8 +181884,18 @@ var DEFAULT_SETUP_CONFIG_SCHEMA = { object(DEFAULT_SETUP_SCHEMA) ) }; -function mergeDefaultSetupAndUserConfigs(logger, fromConfigInput, fromConfigFile) { - logger.debug( +function matchesDefaultSetupConfigSchema(config) { + if (!isObject2(config)) { + return false; + } + const result = checkSchema( + DEFAULT_SETUP_CONFIG_SCHEMA, + config + ); + return result.valid && result.unknownKeys.length === 0; +} +function mergeDefaultSetupAndUserConfigs(logger2, fromConfigInput, fromConfigFile) { + logger2.debug( "Combining configuration files from 'config' and 'config-file' inputs" ); const schemaCheckResult = checkSchema( @@ -149070,7 +181903,7 @@ function mergeDefaultSetupAndUserConfigs(logger, fromConfigInput, fromConfigFile fromConfigInput ); if (schemaCheckResult.invalidKeys.length > 0) { - logger.warning( + logger2.warning( `Invalid keys in Default Setup configuration: ${schemaCheckResult.invalidKeys.join(", ")}` ); addNoLanguageDiagnostic( @@ -149086,7 +181919,7 @@ function mergeDefaultSetupAndUserConfigs(logger, fromConfigInput, fromConfigFile ); } if (schemaCheckResult.unknownKeys.length > 0) { - logger.warning( + logger2.warning( `Unrecognised keys in Default Setup configuration: ${schemaCheckResult.unknownKeys.join(", ")}` ); addNoLanguageDiagnostic( @@ -149106,7 +181939,7 @@ function mergeDefaultSetupAndUserConfigs(logger, fromConfigInput, fromConfigFile threatModels.add(configFileThreatModel); } if (fromConfigFile["default-setup"]) { - logger.warning( + logger2.warning( `The 'default-setup' configuration key is not supported in user-supplied configuration files and will be ignored.` ); } @@ -149159,7 +181992,7 @@ function parsePacksSpecification(packStr) { } if (version) { try { - new semver5.Range(version); + new semver4.Range(version); } catch { throw new ConfigurationError(getPacksStrInvalid(packStr)); } @@ -149223,61 +182056,50 @@ async function calculateAugmentation(rawPacksInput, rawQueriesInput, repositoryP languages, packsInputCombines ); - const queriesInputCombines = shouldCombine(rawQueriesInput); - const queriesInput = parseQueriesFromInput( - rawQueriesInput, - queriesInputCombines + const queries = parseQueriesFromInput(rawQueriesInput); + const repoPropertyQueries = parseQueriesFromInput( + repositoryProperties["github-codeql-extra-queries" /* EXTRA_QUERIES */], + "github-codeql-extra-queries" /* EXTRA_QUERIES */ ); - const repoExtraQueries = repositoryProperties["github-codeql-extra-queries" /* EXTRA_QUERIES */]; - const repoExtraQueriesCombines = shouldCombine(repoExtraQueries); - const repoPropertyQueries = { - combines: repoExtraQueriesCombines, - input: parseQueriesFromInput( - repoExtraQueries, - repoExtraQueriesCombines, - new ConfigurationError( - getRepoPropertyError( - "github-codeql-extra-queries" /* EXTRA_QUERIES */, - getEmptyCombinesError() - ) - ) - ) - }; return { packsInputCombines, packsInput: packsInput?.[languages[0]], - queriesInput, - queriesInputCombines, + queriesInput: queries.input, + queriesInputCombines: queries.combines, repoPropertyQueries }; } -function parseQueriesFromInput(rawQueriesInput, queriesInputCombines, errorToThrow) { - if (!rawQueriesInput) { - return void 0; +function parseQueriesFromInput(value, repositoryProperty) { + if (!value) { + return { combines: false, input: void 0 }; } - const trimmedInput = queriesInputCombines ? rawQueriesInput.trim().slice(1).trim() : rawQueriesInput?.trim() ?? ""; - if (queriesInputCombines && trimmedInput.length === 0) { - if (errorToThrow) { - throw errorToThrow; - } + const combines = shouldCombine(value); + const trimmedInput = combines ? value.trim().slice(1).trim() : value.trim(); + if (combines && trimmedInput.length === 0) { throw new ConfigurationError( - getConfigFilePropertyError( + repositoryProperty !== void 0 ? getRepoPropertyError( + repositoryProperty, + getEmptyCombinesError() + ) : getConfigFilePropertyError( void 0, "queries", "A '+' was used in the 'queries' input to specify that you wished to add some packs to your CodeQL analysis. However, no packs were specified. Please either remove the '+' or specify some packs." ) ); } - return trimmedInput.split(",").map((query) => ({ uses: query.trim() })); + return { + combines, + input: trimmedInput.split(",").map((query) => ({ uses: query.trim() })) + }; } -function combineQueries(logger, config, augmentationProperties) { +function combineQueries(logger2, config, augmentationProperties) { const result = []; if (augmentationProperties.repoPropertyQueries?.input) { - logger.info( + logger2.info( `Found query configuration in the repository properties (${"github-codeql-extra-queries" /* EXTRA_QUERIES */}): ${augmentationProperties.repoPropertyQueries.input.map((q) => q.uses).join(", ")}` ); if (!augmentationProperties.repoPropertyQueries.combines) { - logger.info( + logger2.info( `The queries configured in the repository properties don't allow combining with other query settings. Any queries configured elsewhere will be ignored.` ); return augmentationProperties.repoPropertyQueries.input; @@ -149297,14 +182119,14 @@ function combineQueries(logger, config, augmentationProperties) { } return result; } -function generateCodeScanningConfig(logger, originalUserInput, augmentationProperties) { +function generateCodeScanningConfig(logger2, originalUserInput, augmentationProperties) { const augmentedConfig = cloneObject(originalUserInput); augmentedConfig.queries = combineQueries( - logger, + logger2, augmentedConfig, augmentationProperties ); - logger.debug( + logger2.debug( `Combined queries: ${augmentedConfig.queries?.map((q) => q.uses).join(",")}` ); if (augmentedConfig.queries?.length === 0) { @@ -149331,7 +182153,7 @@ function generateCodeScanningConfig(logger, originalUserInput, augmentationPrope } return augmentedConfig; } -function parseUserConfig(logger, pathInput, contents, validateConfig) { +function parseUserConfig(logger2, pathInput, contents, validateConfig) { try { const schema = ( // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -149342,7 +182164,7 @@ function parseUserConfig(logger, pathInput, contents, validateConfig) { const result = new jsonschema.Validator().validate(doc, schema); if (result.errors.length > 0) { for (const error3 of result.errors) { - logger.error(error3.stack); + logger2.error(error3.stack); } throw new ConfigurationError( getInvalidConfigFileMessage( @@ -149437,13 +182259,13 @@ async function parseRemoteFileAddress(actionState, configFile) { var LOCAL_PATH_PREFIX = "./"; var REMOTE_PATH_PREFIX = "remote="; async function getConfigFileInput({ - logger, + logger: logger2, actions, features }, repositoryProperties, analysisKinds) { const input = actions.getOptionalInput("config-file"); if (input !== void 0) { - logger.info(`Using configuration file input from workflow: ${input}`); + logger2.info(`Using configuration file input from workflow: ${input}`); return input; } const propertyValue = repositoryProperties["github-codeql-config-file" /* CONFIG_FILE */]; @@ -149453,16 +182275,16 @@ async function getConfigFileInput({ "config_file_repository_property" /* ConfigFileRepositoryProperty */ ); if (analysisKindSupported && useRepositoryProperty) { - logger.info( + logger2.info( `Using configuration file input from repository property: ${propertyValue}` ); return propertyValue; } else if (!analysisKindSupported) { - logger.info( + logger2.info( "Ignoring configuration file input from repository property, because it is unsupported for the current analysis kind." ); } else { - logger.info( + logger2.info( "Ignoring configuration file input from repository property, because the corresponding feature flag is disabled." ); } @@ -149505,8 +182327,8 @@ async function getRemoteConfig(actionState, configFile, apiDetails) { } // src/diff-informed-analysis-utils.ts -var fs7 = __toESM(require("fs")); -async function getDiffInformedAnalysisBranches(codeql, features, logger) { +var fs8 = __toESM(require("fs")); +async function getDiffInformedAnalysisBranches(codeql, features, logger2) { if (!await features.getValue("diff_informed_queries" /* DiffInformedQueries */, codeql)) { return void 0; } @@ -149516,18 +182338,18 @@ async function getDiffInformedAnalysisBranches(codeql, features, logger) { } const branches = getPullRequestBranches(); if (!branches) { - logger.info( + logger2.info( "Not performing diff-informed analysis because we are not analyzing a pull request." ); } return branches; } -async function prepareDiffInformedAnalysis(codeql, features, logger) { +async function prepareDiffInformedAnalysis(codeql, features, logger2) { let branches; try { - branches = await getDiffInformedAnalysisBranches(codeql, features, logger); + branches = await getDiffInformedAnalysisBranches(codeql, features, logger2); } catch (e) { - logger.warning( + logger2.warning( `Failed to determine branch information for diff-informed analysis: ${getErrorMessage(e)}` ); return false; @@ -149536,57 +182358,57 @@ async function prepareDiffInformedAnalysis(codeql, features, logger) { return false; } try { - return await computeAndPersistDiffRanges(branches, logger); + return await computeAndPersistDiffRanges(branches, logger2); } catch (e) { - logger.warning( + logger2.warning( `Failed to compute diff-informed analysis ranges: ${getErrorMessage(e)}` ); return false; } } -function writeDiffRangesJsonFile(logger, ranges) { +function writeDiffRangesJsonFile(logger2, ranges) { const jsonContents = JSON.stringify(ranges, null, 2); const jsonFilePath = getDiffRangesJsonFilePath(); - fs7.writeFileSync(jsonFilePath, jsonContents); - logger.debug( + fs8.writeFileSync(jsonFilePath, jsonContents); + logger2.debug( `Wrote pr-diff-range JSON file to ${jsonFilePath}: ${jsonContents}` ); } -function readDiffRangesJsonFile(logger) { +function readDiffRangesJsonFile(logger2) { const jsonFilePath = getDiffRangesJsonFilePath(); - if (!fs7.existsSync(jsonFilePath)) { - logger.debug(`Diff ranges JSON file does not exist at ${jsonFilePath}`); + if (!fs8.existsSync(jsonFilePath)) { + logger2.debug(`Diff ranges JSON file does not exist at ${jsonFilePath}`); return void 0; } - const jsonContents = fs7.readFileSync(jsonFilePath, "utf8"); - logger.debug( + const jsonContents = fs8.readFileSync(jsonFilePath, "utf8"); + logger2.debug( `Read pr-diff-range JSON file from ${jsonFilePath}: ${jsonContents}` ); try { return JSON.parse(jsonContents); } catch (e) { - logger.warning( + logger2.warning( `Failed to parse diff ranges JSON file at ${jsonFilePath}: ${e}` ); return void 0; } } -async function getPullRequestEditedDiffRanges(branches, logger) { - const fileDiffs = await getFileDiffsWithBasehead(branches, logger); +async function getPullRequestEditedDiffRanges(branches, logger2) { + const fileDiffs = await getFileDiffsWithBasehead(branches, logger2); if (fileDiffs === void 0) { return void 0; } if (fileDiffs.length >= 300) { - logger.warning( + logger2.warning( `Cannot retrieve the full diff because there are too many (${fileDiffs.length}) changed files in the pull request.` ); return void 0; } const results = []; for (const filediff of fileDiffs) { - const diffRanges = getDiffRanges(filediff, logger); + const diffRanges = getDiffRanges(filediff, logger2); if (diffRanges === void 0) { return void 0; } @@ -149594,20 +182416,20 @@ async function getPullRequestEditedDiffRanges(branches, logger) { } return results; } -async function computeAndPersistDiffRanges(branches, logger) { - logger.info("Computing PR diff ranges..."); - const ranges = await getPullRequestEditedDiffRanges(branches, logger); +async function computeAndPersistDiffRanges(branches, logger2) { + logger2.info("Computing PR diff ranges..."); + const ranges = await getPullRequestEditedDiffRanges(branches, logger2); if (ranges === void 0) { return false; } - writeDiffRangesJsonFile(logger, ranges); + writeDiffRangesJsonFile(logger2, ranges); const distinctFiles = new Set(ranges.map((r) => r.path)).size; - logger.info( + logger2.info( `Persisted ${ranges.length} diff range(s) across ${distinctFiles} file(s).` ); return true; } -async function getFileDiffsWithBasehead(branches, logger) { +async function getFileDiffsWithBasehead(branches, logger2) { const repositoryNwo = getRepositoryNwoFromEnv( "CODE_SCANNING_REPOSITORY", "GITHUB_REPOSITORY" @@ -149622,15 +182444,15 @@ async function getFileDiffsWithBasehead(branches, logger) { per_page: 1 } ); - logger.debug( + logger2.debug( `Response from compareCommitsWithBasehead(${basehead}): ${JSON.stringify(response, null, 2)}` ); return response.data.files; } catch (error3) { if (error3.status) { - logger.warning(`Error retrieving diff ${basehead}: ${error3.message}`); - logger.debug( + logger2.warning(`Error retrieving diff ${basehead}: ${error3.message}`); + logger2.debug( `Error running compareCommitsWithBasehead(${basehead}): Request: ${JSON.stringify(error3.request, null, 2)} Error Response: ${JSON.stringify(error3.response, null, 2)}` @@ -149641,7 +182463,7 @@ Error Response: ${JSON.stringify(error3.response, null, 2)}` } } } -function getDiffRanges(fileDiff, logger) { +function getDiffRanges(fileDiff, logger2) { if (fileDiff.patch === void 0) { if (fileDiff.changes === 0) { return []; @@ -149681,7 +182503,7 @@ function getDiffRanges(fileDiff, logger) { if (diffLine.startsWith("@@ ")) { const match2 = diffLine.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/); if (match2 === null) { - logger.warning( + logger2.warning( `Cannot parse diff hunk header for ${fileDiff.filename}: ${diffLine}` ); return void 0; @@ -149725,18 +182547,18 @@ var builtin_default = { }; // src/languages/index.ts -var BuiltInLanguage = /* @__PURE__ */ ((BuiltInLanguage3) => { - BuiltInLanguage3["actions"] = "actions"; - BuiltInLanguage3["cpp"] = "cpp"; - BuiltInLanguage3["csharp"] = "csharp"; - BuiltInLanguage3["go"] = "go"; - BuiltInLanguage3["java"] = "java"; - BuiltInLanguage3["javascript"] = "javascript"; - BuiltInLanguage3["python"] = "python"; - BuiltInLanguage3["ruby"] = "ruby"; - BuiltInLanguage3["rust"] = "rust"; - BuiltInLanguage3["swift"] = "swift"; - return BuiltInLanguage3; +var BuiltInLanguage = /* @__PURE__ */ ((BuiltInLanguage4) => { + BuiltInLanguage4["actions"] = "actions"; + BuiltInLanguage4["cpp"] = "cpp"; + BuiltInLanguage4["csharp"] = "csharp"; + BuiltInLanguage4["go"] = "go"; + BuiltInLanguage4["java"] = "java"; + BuiltInLanguage4["javascript"] = "javascript"; + BuiltInLanguage4["python"] = "python"; + BuiltInLanguage4["ruby"] = "ruby"; + BuiltInLanguage4["rust"] = "rust"; + BuiltInLanguage4["swift"] = "swift"; + return BuiltInLanguage4; })(BuiltInLanguage || {}); var builtInLanguageSet = new Set(builtin_default.languages); function isBuiltInLanguage(language) { @@ -149810,9 +182632,9 @@ Improved incremental analysis will be automatically retried when the next versio } // src/overlay/status.ts -var fs8 = __toESM(require("fs")); +var fs9 = __toESM(require("fs")); var path9 = __toESM(require("path")); -var actionsCache = __toESM(require_cache4()); +var actionsCache = __toESM(require_cache6()); var MAX_CACHE_OPERATION_MS = 3e4; var STATUS_FILE_NAME = "overlay-status.json"; function getStatusFilePath(languages) { @@ -149835,80 +182657,80 @@ function createOverlayStatus(attributes, checkRunId) { job }; } -async function shouldSkipOverlayAnalysis(codeql, languages, diskUsage, logger) { - const status = await getOverlayStatus(codeql, languages, diskUsage, logger); +async function shouldSkipOverlayAnalysis(codeql, languages, diskUsage, logger2) { + const status = await getOverlayStatus(codeql, languages, diskUsage, logger2); if (status === void 0) { return false; } if (status.attemptedToBuildOverlayBaseDatabase && !status.builtOverlayBaseDatabase) { - logger.debug( + logger2.debug( "Cached overlay status indicates that building an overlay base database was unsuccessful." ); return true; } - logger.debug( + logger2.debug( "Cached overlay status does not indicate a previous unsuccessful attempt to build an overlay base database." ); return false; } -async function getOverlayStatus(codeql, languages, diskUsage, logger) { +async function getOverlayStatus(codeql, languages, diskUsage, logger2) { const cacheKey3 = await getCacheKey(codeql, languages, diskUsage); const statusFile = getStatusFilePath(languages); try { - await fs8.promises.mkdir(path9.dirname(statusFile), { recursive: true }); + await fs9.promises.mkdir(path9.dirname(statusFile), { recursive: true }); const foundKey = await waitForResultWithTimeLimit( MAX_CACHE_OPERATION_MS, - actionsCache.restoreCache([statusFile], cacheKey3), + actionsCache.restoreCache([statusFile], cacheKey3, [cacheKey3]), () => { - logger.warning("Timed out restoring overlay status from cache."); + logger2.warning("Timed out restoring overlay status from cache."); } ); if (foundKey === void 0) { - logger.debug("No overlay status found in Actions cache."); + logger2.debug("No overlay status found in Actions cache."); return void 0; } - if (!fs8.existsSync(statusFile)) { - logger.debug( + if (!fs9.existsSync(statusFile)) { + logger2.debug( "Overlay status cache entry found but status file is missing." ); return void 0; } - const contents = await fs8.promises.readFile(statusFile, "utf-8"); + const contents = await fs9.promises.readFile(statusFile, "utf-8"); const parsed = JSON.parse(contents); - if (!isObject(parsed) || typeof parsed["attemptedToBuildOverlayBaseDatabase"] !== "boolean" || typeof parsed["builtOverlayBaseDatabase"] !== "boolean") { - logger.debug( + if (!isObject2(parsed) || typeof parsed["attemptedToBuildOverlayBaseDatabase"] !== "boolean" || typeof parsed["builtOverlayBaseDatabase"] !== "boolean") { + logger2.debug( "Ignoring overlay status cache entry with unexpected format." ); return void 0; } return parsed; } catch (error3) { - logger.warning( + logger2.warning( `Failed to restore overlay status from cache: ${getErrorMessage(error3)}` ); return void 0; } } -async function saveOverlayStatus(codeql, languages, diskUsage, status, logger) { +async function saveOverlayStatus(codeql, languages, diskUsage, status, logger2) { const cacheKey3 = await getCacheKey(codeql, languages, diskUsage); const statusFile = getStatusFilePath(languages); try { - await fs8.promises.mkdir(path9.dirname(statusFile), { recursive: true }); - await fs8.promises.writeFile(statusFile, JSON.stringify(status)); + await fs9.promises.mkdir(path9.dirname(statusFile), { recursive: true }); + await fs9.promises.writeFile(statusFile, JSON.stringify(status)); const cacheId = await waitForResultWithTimeLimit( MAX_CACHE_OPERATION_MS, actionsCache.saveCache([statusFile], cacheKey3), () => { - logger.warning("Timed out saving overlay status to cache."); + logger2.warning("Timed out saving overlay status to cache."); } ); if (cacheId === void 0) { return false; } - logger.debug(`Saved overlay status to Actions cache with key ${cacheKey3}`); + logger2.debug(`Saved overlay status to Actions cache with key ${cacheKey3}`); return true; } catch (error3) { - logger.warning( + logger2.warning( `Failed to save overlay status to cache: ${getErrorMessage(error3)}` ); return false; @@ -149920,21 +182742,21 @@ async function getCacheKey(codeql, languages, diskUsage) { } // src/trap-caching.ts -var fs9 = __toESM(require("fs")); +var fs10 = __toESM(require("fs")); var path10 = __toESM(require("path")); -var actionsCache2 = __toESM(require_cache4()); +var actionsCache2 = __toESM(require_cache6()); var CACHE_VERSION = 1; var CODEQL_TRAP_CACHE_PREFIX = "codeql-trap"; var MINIMUM_CACHE_MB_TO_UPLOAD = 10; var MAX_CACHE_OPERATION_MS2 = 12e4; -async function downloadTrapCaches(codeql, languages, logger) { +async function downloadTrapCaches(codeql, languages, logger2, repositoryRoot) { const result = {}; const languagesSupportingCaching = await getLanguagesSupportingCaching( codeql, languages, - logger + logger2 ); - logger.info( + logger2.info( `Found ${languagesSupportingCaching.length} languages that support TRAP caching` ); if (languagesSupportingCaching.length === 0) return result; @@ -149944,11 +182766,11 @@ async function downloadTrapCaches(codeql, languages, logger) { ); for (const language of languagesSupportingCaching) { const cacheDir2 = path10.join(cachesDir, language); - fs9.mkdirSync(cacheDir2, { recursive: true }); + fs10.mkdirSync(cacheDir2, { recursive: true }); result[language] = cacheDir2; } - if (await isAnalyzingDefaultBranch()) { - logger.info( + if (await isAnalyzingDefaultBranch(getEnv(), repositoryRoot)) { + logger2.info( "Analyzing default branch. Skipping downloading of TRAP caches." ); return result; @@ -149956,49 +182778,52 @@ async function downloadTrapCaches(codeql, languages, logger) { let baseSha = "unknown"; const eventPath = process.env.GITHUB_EVENT_PATH; if (getWorkflowEventName() === "pull_request" && eventPath !== void 0) { - const event = JSON.parse(fs9.readFileSync(path10.resolve(eventPath), "utf-8")); + const event = JSON.parse(fs10.readFileSync(path10.resolve(eventPath), "utf-8")); baseSha = event.pull_request?.base?.sha || baseSha; } for (const language of languages) { const cacheDir2 = result[language]; if (cacheDir2 === void 0) continue; const preferredKey = await cacheKey(codeql, language, baseSha); - logger.info( + logger2.info( `Looking in Actions cache for TRAP cache with key ${preferredKey}` ); const found = await waitForResultWithTimeLimit( MAX_CACHE_OPERATION_MS2, actionsCache2.restoreCache([cacheDir2], preferredKey, [ + preferredKey, // Fall back to any cache with the right key prefix await cachePrefix(codeql, language) ]), () => { - logger.info( + logger2.info( `Timed out downloading cache for ${language}, will continue without it` ); } ); if (found === void 0) { - logger.info(`No TRAP cache found in Actions cache for ${language}`); + logger2.info(`No TRAP cache found in Actions cache for ${language}`); delete result[language]; } } return result; } -async function uploadTrapCaches(codeql, config, logger) { - if (!await isAnalyzingDefaultBranch()) return false; +async function uploadTrapCaches(codeql, config, logger2) { + if (!await isAnalyzingDefaultBranch(getEnv(), config.repositoryRoot)) { + return false; + } for (const language of config.languages) { const cacheDir2 = config.trapCaches[language]; if (cacheDir2 === void 0) continue; - const trapFolderSize = await tryGetFolderBytes(cacheDir2, logger); + const trapFolderSize = await tryGetFolderBytes(cacheDir2, logger2); if (trapFolderSize === void 0) { - logger.info( + logger2.info( `Skipping upload of TRAP cache for ${language} as we couldn't determine its size` ); continue; } if (trapFolderSize < MINIMUM_CACHE_MB_TO_UPLOAD * 1048576) { - logger.info( + logger2.info( `Skipping upload of TRAP cache for ${language} as it is too small` ); continue; @@ -150008,12 +182833,12 @@ async function uploadTrapCaches(codeql, config, logger) { language, process.env.GITHUB_SHA || "unknown" ); - logger.info(`Uploading TRAP cache to Actions cache with key ${key}`); + logger2.info(`Uploading TRAP cache to Actions cache with key ${key}`); await waitForResultWithTimeLimit( MAX_CACHE_OPERATION_MS2, actionsCache2.saveCache([cacheDir2], key), () => { - logger.info( + logger2.info( `Timed out waiting for TRAP cache for ${language} to upload, will continue without uploading` ); } @@ -150021,95 +182846,29 @@ async function uploadTrapCaches(codeql, config, logger) { } return true; } -async function cleanupTrapCaches(config, features, logger) { - if (!await features.getValue("cleanup_trap_caches" /* CleanupTrapCaches */)) { - return { - trap_cache_cleanup_skipped_because: "feature disabled" - }; - } - logger.warning( - "TRAP cache cleanup is deprecated and will be removed in May 2026. We recommend instead disabling TRAP caching by passing the `trap-caching: false` input to the `init` Action." - ); - if (!await isAnalyzingDefaultBranch()) { - return { - trap_cache_cleanup_skipped_because: "not analyzing default branch" - }; - } - try { - let totalBytesCleanedUp = 0; - const allCaches = await listActionsCaches( - CODEQL_TRAP_CACHE_PREFIX, - await getRef() +function warnIfTrapCacheCleanupEnvVarIsSet({ + env, + logger: logger2 +}) { + if (env.getOptional("CODEQL_ACTION_CLEANUP_TRAP_CACHES") !== void 0) { + logger2.warning( + "TRAP cache cleanup has been removed, so the CODEQL_ACTION_CLEANUP_TRAP_CACHES environment variable no longer has any effect and can be removed from your workflow. If you used TRAP cache cleanup to limit Actions cache usage, we recommend disabling TRAP caching instead by passing the `trap-caching: false` input to the `init` Action." ); - for (const language of config.languages) { - if (config.trapCaches[language]) { - const cachesToRemove = await getTrapCachesForLanguage( - allCaches, - language, - logger - ); - cachesToRemove.sort((a, b) => a.created_at.localeCompare(b.created_at)); - const mostRecentCache = cachesToRemove.pop(); - logger.debug( - `Keeping most recent TRAP cache (${JSON.stringify(mostRecentCache)})` - ); - if (cachesToRemove.length === 0) { - logger.info(`No TRAP caches to clean up for ${language}.`); - continue; - } - for (const cache of cachesToRemove) { - logger.debug(`Cleaning up TRAP cache (${JSON.stringify(cache)})`); - await deleteActionsCache(cache.id); - } - const bytesCleanedUp = cachesToRemove.reduce( - (acc, item) => acc + item.size_in_bytes, - 0 - ); - totalBytesCleanedUp += bytesCleanedUp; - const megabytesCleanedUp = (bytesCleanedUp / (1024 * 1024)).toFixed(2); - logger.info( - `Cleaned up ${megabytesCleanedUp} MiB of old TRAP caches for ${language}.` - ); - } - } - return { trap_cache_cleanup_size_bytes: totalBytesCleanedUp }; - } catch (e) { - if (asHTTPError(e)?.status === 403) { - logger.warning( - `Could not cleanup TRAP caches as the token did not have the required permissions. To clean up TRAP caches, ensure the token has the "actions:write" permission. See ${"https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs" /* ASSIGNING_PERMISSIONS_TO_JOBS */} for more information.` - ); - } else { - logger.info(`Failed to cleanup TRAP caches, continuing. Details: ${e}`); - } - return { trap_cache_cleanup_error: getErrorMessage(e) }; } } -async function getTrapCachesForLanguage(allCaches, language, logger) { - logger.debug(`Listing TRAP caches for ${language}`); - for (const cache of allCaches) { - if (!cache.created_at || !cache.id || !cache.key || !cache.size_in_bytes) { - throw new Error( - `An unexpected cache item was returned from the API that was missing one or more required fields: ${JSON.stringify(cache)}` - ); - } - } - return allCaches.filter((cache) => { - return cache.key?.includes(`-${language}-`); - }); -} -async function getLanguagesSupportingCaching(codeql, languages, logger) { +async function getLanguagesSupportingCaching(codeql, languages, logger2) { const result = []; const resolveResult = await codeql.resolveLanguages(); outer: for (const lang of languages) { const extractorsForLanguage = resolveResult.extractors[lang]; if (extractorsForLanguage === void 0) { - logger.info( + logger2.info( `${lang} does not support TRAP caching (couldn't find an extractor)` ); continue; } if (extractorsForLanguage.length !== 1) { - logger.info( + logger2.info( `${lang} does not support TRAP caching (found multiple extractors)` ); continue; @@ -150117,14 +182876,14 @@ async function getLanguagesSupportingCaching(codeql, languages, logger) { const extractor = extractorsForLanguage[0]; const trapCacheOptions = extractor.extractor_options?.trap?.properties?.cache?.properties; if (trapCacheOptions === void 0) { - logger.info( + logger2.info( `${lang} does not support TRAP caching (missing option group)` ); continue; } for (const requiredOpt of ["dir", "bound", "write"]) { if (!(requiredOpt in trapCacheOptions)) { - logger.info( + logger2.info( `${lang} does not support TRAP caching (missing ${requiredOpt} option)` ); continue outer; @@ -150153,7 +182912,7 @@ var OVERLAY_MINIMUM_DISK_SPACE_MB_BY_FEATURE = { }; var OVERLAY_MINIMUM_MEMORY_MB = 5 * 1024; var CODEQL_VERSION_REDUCED_OVERLAY_MEMORY_USAGE = "2.24.3"; -async function getSupportedLanguageMap(codeql, logger) { +async function getSupportedLanguageMap(codeql, logger2) { const resolveSupportedLanguagesUsingCli = await codeql.supportsFeature( "builtinExtractorsSpecifyDefaultQueries" /* BuiltinExtractorsSpecifyDefaultQueries */ ); @@ -150161,7 +182920,7 @@ async function getSupportedLanguageMap(codeql, logger) { filterToLanguagesWithQueries: resolveSupportedLanguagesUsingCli }); if (resolveSupportedLanguagesUsingCli) { - logger.debug( + logger2.debug( `The CodeQL CLI supports the following languages: ${Object.keys(resolveResult.extractors).join(", ")}` ); } @@ -150181,36 +182940,36 @@ async function getSupportedLanguageMap(codeql, logger) { var baseWorkflowsPath = ".github/workflows"; function hasActionsWorkflows(sourceRoot) { const workflowsPath = path11.resolve(sourceRoot, baseWorkflowsPath); - const stats = fs10.lstatSync(workflowsPath, { throwIfNoEntry: false }); - return stats !== void 0 && stats.isDirectory() && fs10.readdirSync(workflowsPath).length > 0; + const stats = fs11.lstatSync(workflowsPath, { throwIfNoEntry: false }); + return stats !== void 0 && stats.isDirectory() && fs11.readdirSync(workflowsPath).length > 0; } -async function getRawLanguagesInRepo(repository, sourceRoot, logger) { - logger.debug( +async function getRawLanguagesInRepo(repository, sourceRoot, logger2) { + logger2.debug( `Automatically detecting languages (${repository.owner}/${repository.repo})` ); const response = await getApiClient().rest.repos.listLanguages({ owner: repository.owner, repo: repository.repo }); - logger.debug(`Languages API response: ${JSON.stringify(response)}`); + logger2.debug(`Languages API response: ${JSON.stringify(response)}`); const result = Object.keys(response.data).map( (language) => language.trim().toLowerCase() ); if (hasActionsWorkflows(sourceRoot)) { - logger.debug(`Found a .github/workflows directory`); + logger2.debug(`Found a .github/workflows directory`); result.push("actions"); } - logger.debug(`Raw languages in repository: ${result.join(", ")}`); + logger2.debug(`Raw languages in repository: ${result.join(", ")}`); return result; } -async function getLanguages(codeql, languagesInput, repository, sourceRoot, logger) { +async function getLanguages(codeql, languagesInput, repository, sourceRoot, logger2) { const { rawLanguages, autodetected } = await getRawLanguages( languagesInput, repository, sourceRoot, - logger + logger2 ); - const languageMap = await getSupportedLanguageMap(codeql, logger); + const languageMap = await getSupportedLanguageMap(codeql, logger2); const languagesSet = /* @__PURE__ */ new Set(); const unknownLanguages = []; for (const language of rawLanguages) { @@ -150231,22 +182990,22 @@ async function getLanguages(codeql, languagesInput, repository, sourceRoot, logg throw new ConfigurationError(getNoLanguagesError()); } if (autodetected) { - logger.info(`Autodetected languages: ${languages.join(", ")}`); + logger2.info(`Autodetected languages: ${languages.join(", ")}`); } else { - logger.info(`Languages from configuration: ${languages.join(", ")}`); + logger2.info(`Languages from configuration: ${languages.join(", ")}`); } return languages; } function getRawLanguagesNoAutodetect(languagesInput) { return (languagesInput || "").split(",").map((x) => x.trim().toLowerCase()).filter((x) => x.length > 0); } -async function getRawLanguages(languagesInput, repository, sourceRoot, logger) { +async function getRawLanguages(languagesInput, repository, sourceRoot, logger2) { const languagesFromInput = getRawLanguagesNoAutodetect(languagesInput); if (languagesFromInput.length > 0) { return { rawLanguages: languagesFromInput, autodetected: false }; } return { - rawLanguages: await getRawLanguagesInRepo(repository, sourceRoot, logger), + rawLanguages: await getRawLanguagesInRepo(repository, sourceRoot, logger2), autodetected: true }; } @@ -150268,21 +183027,21 @@ async function initActionState({ features, repositoryProperties, analysisKinds, - logger, + logger: logger2, enableFileCoverageInformation -}, userConfig) { +}, userConfig, repositoryRoot) { const languages = await getLanguages( codeql, languagesInput, repository, sourceRoot, - logger + logger2 ); const buildMode = await parseBuildModeInput( buildModeInput, languages, features, - logger + logger2 ); const augmentationProperties = await calculateAugmentation( packsInput, @@ -150291,7 +183050,7 @@ async function initActionState({ languages ); if (analysisKinds.length === 1 && analysisKinds.includes("code-quality" /* CodeQuality */) && augmentationProperties.repoPropertyQueries.input) { - logger.info( + logger2.info( `Ignoring queries configured in the repository properties, because query customisations are not supported for Code Quality analyses.` ); augmentationProperties.repoPropertyQueries = { @@ -150300,12 +183059,13 @@ async function initActionState({ }; } const computedConfig = generateCodeScanningConfig( - logger, + logger2, userConfig, augmentationProperties ); return { version: getActionVersion(), + repositoryRoot, analysisKinds, languages, buildMode, @@ -150327,13 +183087,20 @@ async function initActionState({ useOverlayDatabaseCaching: false, overlayModeSetExplicitly: false, repositoryProperties, - enableFileCoverageInformation + enableFileCoverageInformation, + // We don't set this to `true` until `init` is successful. + successfullyInitialised: false }; } -async function downloadCacheWithTime(codeQL, languages, logger) { - const start = import_perf_hooks.performance.now(); - const trapCaches = await downloadTrapCaches(codeQL, languages, logger); - const trapCacheDownloadTime = import_perf_hooks.performance.now() - start; +async function downloadCacheWithTime(codeQL, languages, logger2, repositoryRoot) { + const start = import_perf_hooks2.performance.now(); + const trapCaches = await downloadTrapCaches( + codeQL, + languages, + logger2, + repositoryRoot + ); + const trapCacheDownloadTime = import_perf_hooks2.performance.now() - start; return { trapCaches, trapCacheDownloadTime }; } async function loadUserConfig(actionState, configFile, workspacePath, apiDetails, tempDir) { @@ -150411,55 +183178,52 @@ async function getMinimumDiskSpaceMb(features) { } return minimumMb; } -function runnerHasSufficientDiskSpace(diskUsage, logger, minimumDiskSpaceMb) { +function runnerHasSufficientDiskSpace(diskUsage, logger2, minimumDiskSpaceMb) { const diskSpaceMb = Math.round(diskUsage.numAvailableBytes / 1e6); if (diskUsage.numAvailableBytes < minimumDiskSpaceMb * 1e6) { - logger.info( + logger2.info( `Setting overlay database mode to ${"none" /* None */} due to insufficient disk space (${diskSpaceMb} MB, needed ${minimumDiskSpaceMb} MB).` ); return false; } - logger.debug( + logger2.debug( `Disk space available for CodeQL analysis is ${diskSpaceMb} MB, which is at or above the minimum of ${minimumDiskSpaceMb} MB.` ); return true; } -async function runnerHasSufficientMemory(codeql, ramInput, logger) { - if (await codeQlVersionAtLeast( - codeql, - CODEQL_VERSION_REDUCED_OVERLAY_MEMORY_USAGE - )) { - logger.debug( +async function runnerHasSufficientMemory(codeql, ramInput, logger2) { + if (await codeql.isVersionAtLeast(CODEQL_VERSION_REDUCED_OVERLAY_MEMORY_USAGE)) { + logger2.debug( `Skipping memory check for overlay analysis because CodeQL version is at least ${CODEQL_VERSION_REDUCED_OVERLAY_MEMORY_USAGE}.` ); return true; } - const memoryFlagValue = getCodeQLMemoryLimit(ramInput, logger); + const memoryFlagValue = getCodeQLMemoryLimit(ramInput, logger2); if (memoryFlagValue < OVERLAY_MINIMUM_MEMORY_MB) { - logger.info( + logger2.info( `Setting overlay database mode to ${"none" /* None */} due to insufficient memory for CodeQL analysis (${memoryFlagValue} MB, needed ${OVERLAY_MINIMUM_MEMORY_MB} MB).` ); return false; } - logger.debug( + logger2.debug( `Memory available for CodeQL analysis is ${memoryFlagValue} MB, which is at or above the minimum of ${OVERLAY_MINIMUM_MEMORY_MB} MB.` ); return true; } -async function checkRunnerResources(codeql, features, diskUsage, ramInput, logger) { +async function checkRunnerResources(codeql, features, diskUsage, ramInput, logger2) { const minimumDiskSpaceMb = await getMinimumDiskSpaceMb(features); - if (!runnerHasSufficientDiskSpace(diskUsage, logger, minimumDiskSpaceMb)) { + if (!runnerHasSufficientDiskSpace(diskUsage, logger2, minimumDiskSpaceMb)) { return new Failure("insufficient-disk-space" /* InsufficientDiskSpace */); } - if (!await runnerHasSufficientMemory(codeql, ramInput, logger)) { + if (!await runnerHasSufficientMemory(codeql, ramInput, logger2)) { return new Failure("insufficient-memory" /* InsufficientMemory */); } return new Success(void 0); } -async function checkOverlayEnablement(codeql, features, languages, sourceRoot, buildMode, ramInput, codeScanningConfig, repositoryProperties, gitVersion, logger) { +async function checkOverlayEnablement(codeql, features, languages, repositoryRoot, sourceRoot, buildMode, ramInput, codeScanningConfig, repositoryProperties, gitVersion, logger2) { const modeEnv = process.env.CODEQL_OVERLAY_DATABASE_MODE; if (modeEnv === "overlay" /* Overlay */ || modeEnv === "overlay-base" /* OverlayBase */ || modeEnv === "none" /* None */) { - logger.info( + logger2.info( `Setting overlay database mode to ${modeEnv} from the CODEQL_OVERLAY_DATABASE_MODE environment variable.` ); if (modeEnv === "none" /* None */) { @@ -150471,14 +183235,15 @@ async function checkOverlayEnablement(codeql, features, languages, sourceRoot, b true, codeql, languages, + repositoryRoot, sourceRoot, buildMode, gitVersion, - logger + logger2 ); } if (repositoryProperties["github-codeql-disable-overlay" /* DISABLE_OVERLAY */] === true) { - logger.info( + logger2.info( `Setting overlay database mode to ${"none" /* None */} because the ${"github-codeql-disable-overlay" /* DISABLE_OVERLAY */} repository property is set to true.` ); return new Failure("disabled-by-repository-property" /* DisabledByRepositoryProperty */); @@ -150500,9 +183265,9 @@ async function checkOverlayEnablement(codeql, features, languages, sourceRoot, b "overlay_analysis_status_check" /* OverlayAnalysisStatusCheck */ ); const needDiskUsage = performResourceChecks || checkOverlayStatus; - const diskUsage = needDiskUsage ? await checkDiskUsage(logger) : void 0; + const diskUsage = needDiskUsage ? await checkDiskUsage(logger2) : void 0; if (needDiskUsage && diskUsage === void 0) { - logger.warning( + logger2.warning( `Unable to determine disk usage, therefore setting overlay database mode to ${"none" /* None */}.` ); return new Failure("unable-to-determine-disk-usage" /* UnableToDetermineDiskUsage */); @@ -150512,13 +183277,13 @@ async function checkOverlayEnablement(codeql, features, languages, sourceRoot, b features, diskUsage, ramInput, - logger + logger2 ) : new Success(void 0); if (resourceResult.isFailure()) { return resourceResult; } - if (checkOverlayStatus && diskUsage !== void 0 && await shouldSkipOverlayAnalysis(codeql, languages, diskUsage, logger)) { - logger.info( + if (checkOverlayStatus && diskUsage !== void 0 && await shouldSkipOverlayAnalysis(codeql, languages, diskUsage, logger2)) { + logger2.info( `Setting overlay database mode to ${"none" /* None */} because overlay analysis previously failed with this combination of languages, disk space, and CodeQL version.` ); return new Failure("skipped-due-to-cached-status" /* SkippedDueToCachedStatus */); @@ -150526,12 +183291,12 @@ async function checkOverlayEnablement(codeql, features, languages, sourceRoot, b let overlayDatabaseMode; if (isAnalyzingPullRequest()) { overlayDatabaseMode = "overlay" /* Overlay */; - logger.info( + logger2.info( `Setting overlay database mode to ${overlayDatabaseMode} with caching because we are analyzing a pull request.` ); - } else if (await isAnalyzingDefaultBranch()) { + } else if (await isAnalyzingDefaultBranch(getEnv(), repositoryRoot)) { overlayDatabaseMode = "overlay-base" /* OverlayBase */; - logger.info( + logger2.info( `Setting overlay database mode to ${overlayDatabaseMode} with caching because we are analyzing the default branch.` ); } else { @@ -150543,13 +183308,14 @@ async function checkOverlayEnablement(codeql, features, languages, sourceRoot, b false, codeql, languages, + repositoryRoot, sourceRoot, buildMode, gitVersion, - logger + logger2 ); } -async function validateOverlayDatabaseMode(overlayDatabaseMode, useOverlayDatabaseCaching, overlayModeSetExplicitly, codeql, languages, sourceRoot, buildMode, gitVersion, logger) { +async function validateOverlayDatabaseMode(overlayDatabaseMode, useOverlayDatabaseCaching, overlayModeSetExplicitly, codeql, languages, repositoryRoot, sourceRoot, buildMode, gitVersion, logger2) { if (buildMode !== "none" /* None */ && (await Promise.all( languages.map( async (l) => l !== "go" /* go */ && // Workaround to allow overlay analysis for Go with any build @@ -150559,33 +183325,32 @@ async function validateOverlayDatabaseMode(overlayDatabaseMode, useOverlayDataba await codeql.isTracedLanguage(l) ) )).some(Boolean)) { - logger.warning( + logger2.warning( `Cannot build an ${overlayDatabaseMode} database because build-mode is set to "${buildMode}" instead of "none". Falling back to creating a normal full database instead.` ); return new Failure("incompatible-build-mode" /* IncompatibleBuildMode */); } - if (!await codeQlVersionAtLeast(codeql, CODEQL_OVERLAY_MINIMUM_VERSION)) { - logger.warning( + if (!await codeql.isVersionAtLeast(CODEQL_OVERLAY_MINIMUM_VERSION)) { + logger2.warning( `Cannot build an ${overlayDatabaseMode} database because the CodeQL CLI is older than ${CODEQL_OVERLAY_MINIMUM_VERSION}. Falling back to creating a normal full database instead.` ); return new Failure("incompatible-codeql" /* IncompatibleCodeQl */); } - const gitRoot = await getGitRoot(sourceRoot); - if (gitRoot === void 0) { - logger.warning( + if (repositoryRoot === void 0) { + logger2.warning( `Cannot build an ${overlayDatabaseMode} database because the source root "${sourceRoot}" is not inside a git repository. Falling back to creating a normal full database instead.` ); return new Failure("no-git-root" /* NoGitRoot */); } - if (hasSubmodules(gitRoot)) { + if (hasSubmodules(repositoryRoot)) { if (gitVersion === void 0) { - logger.warning( + logger2.warning( `Cannot build an ${overlayDatabaseMode} database because the repository has submodules and the Git version could not be determined. Falling back to creating a normal full database instead.` ); return new Failure("incompatible-git" /* IncompatibleGit */); } if (!gitVersion.isAtLeast(GIT_MINIMUM_VERSION_FOR_OVERLAY_WITH_SUBMODULES)) { - logger.warning( + logger2.warning( `Cannot build an ${overlayDatabaseMode} database because the repository has submodules and the installed Git version is older than ${GIT_MINIMUM_VERSION_FOR_OVERLAY_WITH_SUBMODULES}. Falling back to creating a normal full database instead.` ); return new Failure("incompatible-git" /* IncompatibleGit */); @@ -150597,28 +183362,28 @@ async function validateOverlayDatabaseMode(overlayDatabaseMode, useOverlayDataba overlayModeSetExplicitly }); } -async function isTrapCachingEnabled(features, overlayDatabaseMode) { +function isTrapCachingEnabled(overlayDatabaseMode) { const trapCaching = getOptionalInput("trap-caching"); if (trapCaching !== void 0) return trapCaching === "true"; - if (!isHostedRunner()) return false; - if (overlayDatabaseMode !== "none" /* None */ && await features.getValue("overlay_analysis_disable_trap_caching" /* OverlayAnalysisDisableTrapCaching */)) { + if (!looksLikeHostedRunner()) return false; + if (overlayDatabaseMode !== "none" /* None */) { return false; } return true; } -async function setCppTrapCachingEnvironmentVariables(config, logger) { +async function setCppTrapCachingEnvironmentVariables(config, logger2) { if (config.languages.includes("cpp" /* cpp */)) { const envVar = "CODEQL_EXTRACTOR_CPP_TRAP_CACHING"; if (process.env[envVar]) { - logger.info( + logger2.info( `Environment variable ${envVar} already set, leaving it unchanged.` ); } else if (config.trapCaches["cpp" /* cpp */]) { - logger.info("Enabling TRAP caching for C/C++."); - core10.exportVariable(envVar, "true"); + logger2.info("Enabling TRAP caching for C/C++."); + exportEnvVar(envVar, "true"); } else { - logger.debug(`Disabling TRAP caching for C/C++.`); - core10.exportVariable(envVar, "false"); + logger2.debug(`Disabling TRAP caching for C/C++.`); + exportEnvVar(envVar, "false"); } } } @@ -150631,9 +183396,9 @@ function userConfigFromActionPath(tempDir) { function hasQueryCustomisation(userConfig) { return isDefined2(userConfig["disable-default-queries"]) || isDefined2(userConfig.queries) || isDefined2(userConfig["query-filters"]); } -async function applyIncrementalAnalysisSettings(config, hasDiffRanges, codeql, logger) { +async function applyIncrementalAnalysisSettings(config, hasDiffRanges, codeql, logger2) { if (config.overlayDatabaseMode === "overlay" /* Overlay */ && !hasDiffRanges && !config.overlayModeSetExplicitly) { - logger.info( + logger2.info( `Reverting overlay database mode to ${"none" /* None */} because the PR diff ranges could not be computed.` ); config.overlayDatabaseMode = "none" /* None */; @@ -150651,19 +183416,10 @@ async function applyIncrementalAnalysisSettings(config, hasDiffRanges, codeql, l } } async function determineUserConfig(action, tempDir, inputs) { - const validateConfig = await action.features.getValue( - "validate_db_config" /* ValidateDbConfig */ - ); - if (inputs.configInput) { + if (inputs.configInput !== void 0) { const computedConfigPath = userConfigFromActionPath(tempDir); const allowMergeConfigs = () => action.features.getValue("allow_merge_config_files" /* AllowMergeConfigFiles */); if (inputs.configFile && isDefaultSetup(action.env) && await allowMergeConfigs()) { - const fromConfigInput = parseUserConfig( - action.logger, - "`config` input", - inputs.configInput, - validateConfig - ); const fromConfigFile = await loadUserConfig( action, inputs.configFile, @@ -150673,10 +183429,10 @@ async function determineUserConfig(action, tempDir, inputs) { ); const mergedConfig = mergeDefaultSetupAndUserConfigs( action.logger, - fromConfigInput, + inputs.configInput, fromConfigFile ); - fs10.writeFileSync(computedConfigPath, dump(mergedConfig)); + fs11.writeFileSync(computedConfigPath, dump(mergedConfig)); action.logger.debug( `Using merged configurations from 'config' input with configuration from '${inputs.configFile}': ${computedConfigPath}` ); @@ -150688,11 +183444,12 @@ async function determineUserConfig(action, tempDir, inputs) { `Both a config file and config input were provided. Ignoring config file.` ); } - fs10.writeFileSync(computedConfigPath, inputs.configInput); + fs11.writeFileSync(computedConfigPath, dump(inputs.configInput)); inputs.configFile = computedConfigPath; action.logger.debug( `Using config from action input: ${inputs.configFile}` ); + return inputs.configInput; } } if (!inputs.configFile) { @@ -150710,10 +183467,11 @@ async function determineUserConfig(action, tempDir, inputs) { } } async function initConfig(actionState, inputs) { - const { logger, features } = actionState; + const { logger: logger2, features } = actionState; const { tempDir } = inputs; + const repositoryRoot = await getGitRoot(inputs.sourceRoot); const userConfig = await determineUserConfig(actionState, tempDir, inputs); - const config = await initActionState(inputs, userConfig); + const config = await initActionState(inputs, userConfig, repositoryRoot); if (config.analysisKinds.length === 1 && isCodeQualityEnabled(config)) { if (hasQueryCustomisation(config.computedConfig)) { throw new ConfigurationError( @@ -150728,28 +183486,28 @@ async function initConfig(actionState, inputs) { let gitVersion = void 0; try { gitVersion = await getGitVersionOrThrow(); - logger.info(`Using Git version ${gitVersion.fullVersion}`); + logger2.info(`Using Git version ${gitVersion.fullVersion}`); } catch (e) { - logger.warning(`Could not determine Git version: ${getErrorMessage(e)}`); + logger2.warning(`Could not determine Git version: ${getErrorMessage(e)}`); if (isInTestMode() && process.env["CODEQL_ACTION_TOLERATE_MISSING_GIT_VERSION" /* TOLERATE_MISSING_GIT_VERSION */] !== "true") { throw e; } } if (await features.getValue("ignore_generated_files" /* IgnoreGeneratedFiles */) && isDynamicWorkflow()) { try { - const generatedFilesCheckStartedAt = import_perf_hooks.performance.now(); + const generatedFilesCheckStartedAt = import_perf_hooks2.performance.now(); const generatedFiles = await getGeneratedFiles(inputs.sourceRoot); const generatedFilesDuration = Math.round( - import_perf_hooks.performance.now() - generatedFilesCheckStartedAt + import_perf_hooks2.performance.now() - generatedFilesCheckStartedAt ); if (generatedFiles.length > 0) { config.computedConfig["paths-ignore"] ??= []; config.computedConfig["paths-ignore"].push(...generatedFiles); - logger.info( + logger2.info( `Detected ${generatedFiles.length} generated file(s), which will be excluded from analysis: ${joinAtMost(generatedFiles, ", ", 10)}` ); } else { - logger.info(`Found no generated files.`); + logger2.info(`Found no generated files.`); } await logGeneratedFilesTelemetry( config, @@ -150757,22 +183515,23 @@ async function initConfig(actionState, inputs) { generatedFiles.length ); } catch (error3) { - logger.info(`Cannot ignore generated files: ${getErrorMessage(error3)}`); + logger2.info(`Cannot ignore generated files: ${getErrorMessage(error3)}`); } } else { - logger.debug(`Skipping check for generated files.`); + logger2.debug(`Skipping check for generated files.`); } const overlayDatabaseModeResult = await checkOverlayEnablement( inputs.codeql, inputs.features, config.languages, + repositoryRoot, inputs.sourceRoot, config.buildMode, inputs.ramInput, config.computedConfig, config.repositoryProperties, gitVersion, - logger + logger2 ); if (overlayDatabaseModeResult.isSuccess()) { const { @@ -150780,7 +183539,7 @@ async function initConfig(actionState, inputs) { useOverlayDatabaseCaching, overlayModeSetExplicitly } = overlayDatabaseModeResult.value; - logger.info( + logger2.info( `Using overlay database mode: ${overlayDatabaseMode} ${useOverlayDatabaseCaching ? "with" : "without"} caching.` ); config.overlayDatabaseMode = overlayDatabaseMode; @@ -150788,7 +183547,7 @@ async function initConfig(actionState, inputs) { config.overlayModeSetExplicitly = overlayModeSetExplicitly; } else { const overlayDisabledReason = overlayDatabaseModeResult.value; - logger.info( + logger2.info( `Using overlay database mode: ${"none" /* None */} without caching.` ); config.overlayDatabaseMode = "none" /* None */; @@ -150802,24 +183561,25 @@ async function initConfig(actionState, inputs) { const hasDiffRanges = await prepareDiffInformedAnalysis( inputs.codeql, inputs.features, - logger + logger2 ); await applyIncrementalAnalysisSettings( config, hasDiffRanges, inputs.codeql, - logger + logger2 ); - if (await isTrapCachingEnabled(features, config.overlayDatabaseMode)) { + if (isTrapCachingEnabled(config.overlayDatabaseMode)) { const { trapCaches, trapCacheDownloadTime } = await downloadCacheWithTime( inputs.codeql, config.languages, - logger + logger2, + repositoryRoot ); config.trapCaches = trapCaches; config.trapCacheDownloadTime = trapCacheDownloadTime; } - await setCppTrapCachingEnvironmentVariables(config, logger); + await setCppTrapCachingEnvironmentVariables(config, logger2); return config; } function isExplicitLocalPath(configPath) { @@ -150840,38 +183600,65 @@ function isLocal(configPath) { } return !containsAtRef(configPath); } -function getLocalConfig(logger, configFile, validateConfig) { - if (!fs10.existsSync(configFile)) { +function getLocalConfig(logger2, configFile, validateConfig) { + if (!fs11.existsSync(configFile)) { throw new ConfigurationError( getConfigFileDoesNotExistErrorMessage(configFile) ); } return parseUserConfig( - logger, + logger2, configFile, - fs10.readFileSync(configFile, "utf-8"), + fs11.readFileSync(configFile, "utf-8"), validateConfig ); } function getPathToParsedConfigFile(tempDir) { return path11.join(tempDir, "config"); } -async function saveConfig(config, logger) { +function getPathToFailedConfigFile(tempDir) { + return path11.join(tempDir, "failed-config"); +} +function saveConfigFile(logger2, configFilePath, config) { const configString = JSON.stringify(config); + fs11.mkdirSync(path11.dirname(configFilePath), { recursive: true }); + fs11.writeFileSync(configFilePath, configString, "utf8"); + logger2.debug("Saved config:"); + logger2.debug(configString); +} +async function saveConfig(config, logger2) { const configFile = getPathToParsedConfigFile(config.tempDir); - fs10.mkdirSync(path11.dirname(configFile), { recursive: true }); - fs10.writeFileSync(configFile, configString, "utf8"); - logger.debug("Saved config:"); - logger.debug(configString); + saveConfigFile(logger2, configFile, config); } -async function getConfig(tempDir, logger) { - const configFile = getPathToParsedConfigFile(tempDir); - if (!fs10.existsSync(configFile)) { +function saveAbortedInitConfig(action, config) { + if (action.name !== "init" /* Init */) { + throw new Error( + `Internal error: 'saveAbortedInitConfig' should only be called by '${"init" /* Init */}', but was called by '${action.name}'.` + ); + } + const failedConfig = { + version: config.version, + tempDir: config.tempDir, + codeQLCmd: config.codeQLCmd, + debugMode: config.debugMode, + gitHubVersion: config.gitHubVersion, + languages: config.languages, + analysisKinds: config.analysisKinds + }; + action.logger.debug(`Saving config for failed init step.`); + saveConfigFile( + action.logger, + getPathToFailedConfigFile(config.tempDir), + failedConfig + ); +} +function readConfigFile(logger2, configFilePath) { + if (!fs11.existsSync(configFilePath)) { return void 0; } - const configString = fs10.readFileSync(configFile, "utf8"); - logger.debug("Loaded config:"); - logger.debug(configString); + const configString = fs11.readFileSync(configFilePath, "utf8"); + logger2.debug("Loaded config:"); + logger2.debug(configString); const config = JSON.parse(configString); if (config.version === void 0) { throw new ConfigurationError( @@ -150880,12 +183667,29 @@ async function getConfig(tempDir, logger) { } if (config.version !== getActionVersion()) { throw new ConfigurationError( - `Loaded a configuration file for version '${config.version}', but running version '${getActionVersion()}'` + [ + `Loaded a configuration file for version '${config.version}', but running version '${getActionVersion()}'.`, + "All steps in a workflow that use `github/codeql-action` must use the same version to work correctly.", + "If you are using Dependabot to manage dependency updates, you can configure a dependency group to update all `github/codeql-action` steps at the same time.", + "For more information, see https://docs.github.com/en/code-security/reference/supply-chain-security/dependabot-options-reference#groups--" + ].join(" ") ); } return config; } -async function generateRegistries(registriesInput, tempDir, logger) { +async function getConfig(tempDir, logger2) { + const configFile = getPathToParsedConfigFile(tempDir); + return readConfigFile(logger2, configFile); +} +function getAbortedInitConfig(action, tempDir) { + if (action.name !== "init-post" /* InitPost */) { + throw new Error( + `Internal error: 'getAbortedInitConfig' should only be called by '${"init-post" /* InitPost */}', but was called by '${action.name}'.` + ); + } + return readConfigFile(action.logger, getPathToFailedConfigFile(tempDir)); +} +async function generateRegistries(registriesInput, tempDir, logger2) { const registries = parseRegistries(registriesInput); let registriesAuthTokens; let qlconfigFile; @@ -150893,13 +183697,13 @@ async function generateRegistries(registriesInput, tempDir, logger) { const qlconfig = createRegistriesBlock(registries); qlconfigFile = path11.join(tempDir, "qlconfig.yml"); const qlconfigContents = dump(qlconfig); - fs10.writeFileSync(qlconfigFile, qlconfigContents, "utf8"); - logger.debug("Generated qlconfig.yml:"); - logger.debug(qlconfigContents); + fs11.writeFileSync(qlconfigFile, qlconfigContents, "utf8"); + logger2.debug("Generated qlconfig.yml:"); + logger2.debug(qlconfigContents); registriesAuthTokens = registries.map((registry) => `${registry.url}=${registry.token}`).join(","); } if (typeof process.env.CODEQL_REGISTRIES_AUTH === "string") { - logger.debug( + logger2.debug( "Using CODEQL_REGISTRIES_AUTH environment variable to authenticate with registries." ); } @@ -150943,7 +183747,7 @@ async function wrapEnvironment(env, operation) { } } } -async function parseBuildModeInput(input, languages, features, logger) { +async function parseBuildModeInput(input, languages, features, logger2) { if (input === void 0) { return void 0; } @@ -150955,13 +183759,13 @@ async function parseBuildModeInput(input, languages, features, logger) { ); } if (languages.includes("csharp" /* csharp */) && await features.getValue("disable_csharp_buildless" /* DisableCsharpBuildless */)) { - logger.warning( + logger2.warning( "Scanning C# code without a build is temporarily unavailable. Falling back to 'autobuild' build mode." ); return "autobuild" /* Autobuild */; } if (languages.includes("java" /* java */) && await features.getValue("disable_java_buildless_enabled" /* DisableJavaBuildlessEnabled */)) { - logger.warning( + logger2.warning( "Scanning Java code without a build is temporarily unavailable. Falling back to 'autobuild' build mode." ); return "autobuild" /* Autobuild */; @@ -151022,25 +183826,54 @@ async function logGeneratedFilesTelemetry(config, duration, generatedFilesCount) } // src/setup-codeql.ts -var fs14 = __toESM(require("fs")); +var fs16 = __toESM(require("fs")); var path13 = __toESM(require("path")); +var import_perf_hooks4 = require("perf_hooks"); var toolcache3 = __toESM(require_tool_cache()); -var import_fast_deep_equal = __toESM(require_fast_deep_equal()); -var semver9 = __toESM(require_semver2()); +var semver10 = __toESM(require_semver2()); + +// src/codeql-bundle.ts +function getCodeQLBundleName(compressionMethod, platform2, language) { + const extensions = { + gzip: ".tar.gz", + zstd: ".tar.zst" + }; + const extension = extensions[compressionMethod]; + if (platform2 === void 0) { + return `codeql-bundle${extension}`; + } + if (language !== void 0) { + return `codeql-bundle-${language}-${platform2}${extension}`; + } + return `codeql-bundle-${platform2}${extension}`; +} +var PER_LANGUAGE_BUNDLE_NAME = /^codeql-bundle-(.+)-(?:linux64|osx64|win64)\.tar\.(?:gz|zst)$/; +function getCodeQLBundleFromUrl(url2) { + let assetName; + try { + const pathname = new URL(url2).pathname; + assetName = decodeURIComponent(pathname.split("/").pop() ?? ""); + } catch { + return { kind: "combined", url: url2 }; + } + const match2 = assetName.match(PER_LANGUAGE_BUNDLE_NAME); + const language = match2 ? parseBuiltInLanguage(match2[1]) : void 0; + return language === void 0 ? { kind: "combined", url: url2 } : { kind: "per-language", url: url2, language }; +} // src/overlay/caching.ts -var fs11 = __toESM(require("fs")); -var actionsCache3 = __toESM(require_cache4()); -var semver6 = __toESM(require_semver2()); +var fs12 = __toESM(require("fs")); +var actionsCache3 = __toESM(require_cache6()); +var semver5 = __toESM(require_semver2()); var OVERLAY_BASE_DATABASE_MAX_UPLOAD_SIZE_MB = 7500; var OVERLAY_BASE_DATABASE_MAX_UPLOAD_SIZE_BYTES = OVERLAY_BASE_DATABASE_MAX_UPLOAD_SIZE_MB * 1e6; var CACHE_VERSION2 = 1; var CACHE_PREFIX = "codeql-overlay-base-database"; var MAX_CACHE_OPERATION_MS3 = 6e5; -async function checkOverlayBaseDatabase(codeql, config, logger, warningPrefix) { +async function checkOverlayBaseDatabase(codeql, config, logger2, warningPrefix) { const baseDatabaseOidsFilePath = getBaseDatabaseOidsFilePath(config); - if (!fs11.existsSync(baseDatabaseOidsFilePath)) { - logger.warning( + if (!fs12.existsSync(baseDatabaseOidsFilePath)) { + logger2.warning( `${warningPrefix}: ${baseDatabaseOidsFilePath} does not exist` ); return false; @@ -151050,36 +183883,36 @@ async function checkOverlayBaseDatabase(codeql, config, logger, warningPrefix) { try { const resolveDatabaseOutput = await codeql.resolveDatabase(dbPath); if (resolveDatabaseOutput === void 0 || !("overlayBaseSpecifier" in resolveDatabaseOutput)) { - logger.info(`${warningPrefix}: no overlayBaseSpecifier defined`); + logger2.info(`${warningPrefix}: no overlayBaseSpecifier defined`); return false; } else { - logger.debug( + logger2.debug( `Overlay base specifier for ${language} overlay-base database found: ${resolveDatabaseOutput.overlayBaseSpecifier}` ); } } catch (e) { - logger.warning(`${warningPrefix}: failed to resolve database: ${e}`); + logger2.warning(`${warningPrefix}: failed to resolve database: ${e}`); return false; } } return true; } -async function cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger) { +async function cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger2, checkoutPath) { const overlayDatabaseMode = config.overlayDatabaseMode; if (overlayDatabaseMode !== "overlay-base" /* OverlayBase */) { - logger.debug( + logger2.debug( `Overlay database mode is ${overlayDatabaseMode}. Skip uploading overlay-base database to cache.` ); return false; } if (!config.useOverlayDatabaseCaching) { - logger.debug( + logger2.debug( "Overlay database caching is disabled. Skip uploading overlay-base database to cache." ); return false; } if (isInTestMode()) { - logger.debug( + logger2.debug( "In test mode. Skip uploading overlay-base database to cache." ); return false; @@ -151087,7 +183920,7 @@ async function cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger const databaseIsValid = await checkOverlayBaseDatabase( codeql, config, - logger, + logger2, "Abort uploading overlay-base database to cache" ); if (!databaseIsValid) { @@ -151097,29 +183930,28 @@ async function cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger await codeql.databaseCleanupCluster(config, "overlay" /* Overlay */); }); const dbLocation = config.dbLocation; - const databaseSizeBytes = await tryGetFolderBytes(dbLocation, logger); + const databaseSizeBytes = await tryGetFolderBytes(dbLocation, logger2); if (databaseSizeBytes === void 0) { - logger.warning( + logger2.warning( "Failed to determine database size. Skip uploading overlay-base database to cache." ); return false; } if (databaseSizeBytes > OVERLAY_BASE_DATABASE_MAX_UPLOAD_SIZE_BYTES) { const databaseSizeMB = Math.round(databaseSizeBytes / 1e6); - logger.warning( + logger2.warning( `Database size (${databaseSizeMB} MB) exceeds maximum upload size (${OVERLAY_BASE_DATABASE_MAX_UPLOAD_SIZE_MB} MB). Skip uploading overlay-base database to cache.` ); return false; } const codeQlVersion = (await codeql.getVersion()).version; - const checkoutPath = getRequiredInput("checkout_path"); const cacheSaveKey = await getCacheSaveKey( config, codeQlVersion, checkoutPath, - logger + logger2 ); - logger.info( + logger2.info( `Uploading overlay-base database to Actions cache with key ${cacheSaveKey}` ); try { @@ -151130,34 +183962,34 @@ async function cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger } ); if (cacheId === void 0) { - logger.warning("Timed out while uploading overlay-base database"); + logger2.warning("Timed out while uploading overlay-base database"); return false; } } catch (error3) { - logger.warning( + logger2.warning( `Failed to upload overlay-base database to cache: ${error3 instanceof Error ? error3.message : String(error3)}` ); return false; } - logger.info(`Successfully uploaded overlay-base database from ${dbLocation}`); + logger2.info(`Successfully uploaded overlay-base database from ${dbLocation}`); return true; } -async function downloadOverlayBaseDatabaseFromCache(codeql, config, logger) { +async function downloadOverlayBaseDatabaseFromCache(codeql, config, logger2) { const overlayDatabaseMode = config.overlayDatabaseMode; if (overlayDatabaseMode !== "overlay" /* Overlay */) { - logger.debug( + logger2.debug( `Overlay database mode is ${overlayDatabaseMode}. Skip downloading overlay-base database from cache.` ); return void 0; } if (!config.useOverlayDatabaseCaching) { - logger.debug( + logger2.debug( "Overlay database caching is disabled. Skip downloading overlay-base database from cache." ); return void 0; } if (isInTestMode()) { - logger.debug( + logger2.debug( "In test mode. Skip downloading overlay-base database from cache." ); return void 0; @@ -151168,7 +184000,7 @@ async function downloadOverlayBaseDatabaseFromCache(codeql, config, logger) { config, codeQlVersion ); - logger.info( + logger2.info( `Looking in Actions cache for overlay-base database with restore key ${cacheRestoreKeyPrefix}` ); let databaseDownloadDurationMs = 0; @@ -151197,7 +184029,7 @@ async function downloadOverlayBaseDatabaseFromCache(codeql, config, logger) { actionsCache3.restoreCache( [dbLocation], cacheRestoreKeyPrefix, - void 0, + [cacheRestoreKeyPrefix], { // Azure SDK download (which is the default) uses 128MB segments; see // https://github.com/actions/toolkit/blob/main/packages/cache/README.md. @@ -151208,21 +184040,21 @@ async function downloadOverlayBaseDatabaseFromCache(codeql, config, logger) { } ), () => { - logger.info("Timed out downloading overlay-base database from cache"); + logger2.info("Timed out downloading overlay-base database from cache"); } ); databaseDownloadDurationMs = Math.round( performance.now() - databaseDownloadStart ); if (foundKey === void 0) { - logger.info("No overlay-base database found in Actions cache"); + logger2.info("No overlay-base database found in Actions cache"); return void 0; } - logger.info( + logger2.info( `Downloaded overlay-base database in cache with key ${foundKey}` ); } catch (error3) { - logger.warning( + logger2.warning( `Failed to download overlay-base database from cache: ${error3 instanceof Error ? error3.message : String(error3)}` ); return void 0; @@ -151230,38 +184062,38 @@ async function downloadOverlayBaseDatabaseFromCache(codeql, config, logger) { const databaseIsValid = await checkOverlayBaseDatabase( codeql, config, - logger, + logger2, "Downloaded overlay-base database is invalid" ); if (!databaseIsValid) { - logger.warning("Downloaded overlay-base database failed validation"); + logger2.warning("Downloaded overlay-base database failed validation"); return void 0; } - const databaseSizeBytes = await tryGetFolderBytes(dbLocation, logger); + const databaseSizeBytes = await tryGetFolderBytes(dbLocation, logger2); if (databaseSizeBytes === void 0) { - logger.info( + logger2.info( "Filesystem error while accessing downloaded overlay-base database" ); return void 0; } - logger.info(`Successfully downloaded overlay-base database to ${dbLocation}`); + logger2.info(`Successfully downloaded overlay-base database to ${dbLocation}`); return { databaseSizeBytes: Math.round(databaseSizeBytes), databaseDownloadDurationMs }; } -async function getCacheSaveKey(config, codeQlVersion, checkoutPath, logger) { +async function getCacheSaveKey(config, codeQlVersion, checkoutPath, logger2) { let runId = 1; let attemptId = 1; try { runId = getWorkflowRunID(); attemptId = getWorkflowRunAttempt(); } catch (e) { - logger.warning( + logger2.warning( `Failed to get workflow run ID or attempt ID. Reason: ${getErrorMessage(e)}` ); } - const sha = await getCommitOid(checkoutPath); + const sha = await getCommitOid(getEnv(), checkoutPath); const restoreKeyPrefix = await getCacheRestoreKeyPrefix( config, codeQlVersion @@ -151280,10 +184112,10 @@ async function getCacheKeyPrefixBase(parsedLanguages) { const componentsHash = createCacheKeyHash(cacheKeyComponents); return `${CACHE_PREFIX}-${CACHE_VERSION2}-${componentsHash}-${languagesComponent}-`; } -async function getCodeQlVersionsForOverlayBaseDatabases(rawLanguages, logger) { +async function getCodeQlVersionsForOverlayBaseDatabases(rawLanguages, logger2) { const languages = rawLanguages.map(parseBuiltInLanguage); if (languages.includes(void 0)) { - logger.warning( + logger2.warning( "One or more provided languages are not recognized as built-in languages. Skipping searching for overlay-base databases in cache." ); return void 0; @@ -151292,15 +184124,15 @@ async function getCodeQlVersionsForOverlayBaseDatabases(rawLanguages, logger) { ...new Set(languages.filter((l) => l !== void 0)) ]; const cacheKeyPrefix = await getCacheKeyPrefixBase(dedupedLanguages); - logger.debug( + logger2.debug( `Searching for overlay-base databases in Actions cache with prefix ${cacheKeyPrefix}` ); const caches = await listActionsCaches(cacheKeyPrefix); if (caches.length === 0) { - logger.info("No overlay-base databases found in Actions cache."); + logger2.info("No overlay-base databases found in Actions cache."); return []; } - logger.info( + logger2.info( `Found ${caches.length} overlay-base ${caches.length === 1 ? "database" : "databases"} in the Actions cache.` ); const versionRegex = /^([\d.]+)-/; @@ -151309,35 +184141,380 @@ async function getCodeQlVersionsForOverlayBaseDatabases(rawLanguages, logger) { if (!cache.key) continue; const suffix = cache.key.substring(cacheKeyPrefix.length); const match2 = suffix.match(versionRegex); - if (match2 && semver6.valid(match2[1])) { + if (match2 && semver5.valid(match2[1])) { versionSet.add(match2[1]); } } if (versionSet.size === 0) { - logger.info( + logger2.info( "Could not parse any CodeQL versions from overlay-base database cache keys." ); return []; } - const versions = [...versionSet].sort(semver6.rcompare); - logger.info( + const versions = [...versionSet].sort(semver5.rcompare); + logger2.info( `Found overlay databases for the following CodeQL versions in the Actions cache: ${versions.join(", ")}` ); return versions; } +// src/per-language-bundles.ts +var semver7 = __toESM(require_semver2()); + +// src/platform.ts +var import_fs = __toESM(require("fs")); +var toolrunner3 = __toESM(require_toolrunner()); +var io4 = __toESM(require_io()); +var semver6 = __toESM(require_semver2()); +function getBundlePlatform(platform2 = process.platform, arch2 = process.arch) { + switch (platform2) { + case "win32": + return "win64" /* Win64 */; + case "linux": + return arch2 === "arm64" ? "linux-arm64" /* LinuxArm64 */ : "linux64" /* Linux64 */; + case "darwin": + return "osx64" /* Osx64 */; + default: + return void 0; + } +} +function darwinVersion(action) { + if (action.platform !== "darwin") { + return void 0; + } + const version = semver6.parse(action.osRelease); + if (version === null) { + return action.osRelease; + } + return version; +} +var XCODE_SELECT_LINK_PATH = "/private/var/db/xcode_select_link"; +var XCODE_APP_FILENAME_PATTERN = new RegExp( + /(?Xcode_(?\d+(\.\d+)?).*\.app)/ +); +function xcodeVersionFromLink(logger2) { + try { + const xcodePath = import_fs.default.readlinkSync(XCODE_SELECT_LINK_PATH); + if (xcodePath.trim() === "") { + logger2.debug( + `Resolving ${XCODE_SELECT_LINK_PATH} unexpectedly returned nothing.` + ); + return void 0; + } + const matchResult = xcodePath.match(XCODE_APP_FILENAME_PATTERN); + if (matchResult?.groups === void 0) { + logger2.debug( + `Xcode path '${xcodePath}' does not contain expected pattern.` + ); + return void 0; + } + const majorMinor = matchResult.groups["majorMinor"]; + const version = semver6.coerce(majorMinor); + if (version === null) { + logger2.debug(`Couldn't parse '${majorMinor}' as a semantic version.`); + return void 0; + } + return version; + } catch (err) { + logger2.debug(`Unable to determine Xcode version: ${getErrorMessage(err)}`); + return void 0; + } +} +async function xcodeVersionFromXcodeBuild(logger2) { + try { + const xcrun = await io4.which("xcrun", true); + let stdout = ""; + let stderr = ""; + const exitCode = await new toolrunner3.ToolRunner( + xcrun, + ["xcodebuild", "-version"], + { + silent: true, + ignoreReturnCode: true, + listeners: { + stdout: (data) => { + stdout += data.toString("utf-8"); + }, + stderr: (data) => { + stderr += data.toString("utf-8"); + } + } + } + ).exec(); + if (exitCode !== 0) { + logger2.debug(`xcodebuild returned exit code ${exitCode}`); + logger2.debug(`stdout: +${stdout}`); + logger2.debug(`stderr: +${stderr}`); + return void 0; + } + const match2 = stdout.match(/^Xcode (\d+(\.\d+)?)/); + if (match2 === null) { + logger2.debug( + `Output doesn't appear to contain the Xcode product version.` + ); + logger2.debug(`stdout: +${stdout}`); + logger2.debug(`stderr: +${stderr}`); + return void 0; + } + const version = semver6.coerce(match2[1].trim()); + if (version === null) { + logger2.debug( + `xcodebuild's output couldn't be parsed as a version: +${stdout}` + ); + logger2.debug(`stderr: +${stderr}`); + return void 0; + } + return version; + } catch (err) { + logger2.debug( + `Unable to determine Xcode version from xcodebuild: ${getErrorMessage(err)}` + ); + return void 0; + } +} +async function xcodeSdkVersion(logger2) { + try { + const xcrun = await io4.which("xcrun", true); + let stdout = ""; + let stderr = ""; + const exitCode = await new toolrunner3.ToolRunner( + xcrun, + ["--sdk", "macosx", "--show-sdk-version"], + { + silent: true, + ignoreReturnCode: true, + listeners: { + stdout: (data) => { + stdout += data.toString("utf-8"); + }, + stderr: (data) => { + stderr += data.toString("utf-8"); + } + } + } + ).exec(); + if (exitCode !== 0) { + logger2.debug(`xcrun returned exit code ${exitCode}`); + logger2.debug(`stdout: +${stdout}`); + logger2.debug(`stderr: +${stderr}`); + return void 0; + } + const version = semver6.coerce(stdout.trim()); + if (version === null) { + logger2.debug( + `xcrun's output couldn't be parsed as a version: +${stdout}` + ); + logger2.debug(`stderr: +${stderr}`); + return void 0; + } + return version; + } catch (err) { + logger2.debug( + `Unable to determine Xcode SDK version: ${getErrorMessage(err)}` + ); + return void 0; + } +} + +// src/per-language-bundles.ts +var MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION = "2.27.1"; +var PER_LANGUAGE_BUNDLE_LANGUAGES = { + ["linux64" /* Linux64 */]: /* @__PURE__ */ new Set([ + "actions" /* actions */, + "cpp" /* cpp */, + "csharp" /* csharp */, + "go" /* go */, + "java" /* java */, + "javascript" /* javascript */, + "python" /* python */, + "ruby" /* ruby */, + "rust" /* rust */ + ]), + ["linux-arm64" /* LinuxArm64 */]: /* @__PURE__ */ new Set(), + ["osx64" /* Osx64 */]: /* @__PURE__ */ new Set(["swift" /* swift */]), + ["win64" /* Win64 */]: /* @__PURE__ */ new Set() +}; +function getOtherLanguagePacksReason(inputs) { + if (inputs.configFile !== void 0) { + return `the configuration file '${inputs.configFile}' may use queries that need library packs for other languages`; + } + if (inputs.configInput !== void 0 && !matchesDefaultSetupConfigSchema(inputs.configInput)) { + return "the 'config' input may use queries that need library packs for other languages"; + } + const query = findNonBuiltInQuery( + parseQueriesFromInput(inputs.queriesInput).input + ); + if (query !== void 0) { + return `the query '${query}' from the 'queries' input may need library packs for other languages`; + } + const extraQuery = findNonBuiltInQuery( + parseQueriesFromInput( + inputs.extraQueriesProperty, + "github-codeql-extra-queries" /* EXTRA_QUERIES */ + ).input + ); + if (extraQuery !== void 0) { + return `the query '${extraQuery}' from the '${"github-codeql-extra-queries" /* EXTRA_QUERIES */}' repository property may need library packs for other languages`; + } + return void 0; +} +function findNonBuiltInQuery(queries) { + return queries?.find((query) => !defaultSuites.has(query.uses))?.uses; +} +function getPerLanguageBundleLanguage(action, options) { + const { + rawLanguages, + otherLanguagePacksReason, + cliVersion: cliVersion2, + compressionMethod, + platform: platform2, + variant, + isLatestNightly + } = options; + const explain = (reason) => { + action.logger.debug( + `Not using a per-language CodeQL bundle since ${reason}.` + ); + return void 0; + }; + if (otherLanguagePacksReason !== void 0) { + return explain(otherLanguagePacksReason); + } + if (rawLanguages?.length !== 1) { + return explain( + `exactly one language must be requested via the 'languages' input, but ${rawLanguages?.length ?? 0} were` + ); + } + const language = parseBuiltInLanguage(rawLanguages[0]); + if (language === void 0) { + return explain(`'${rawLanguages[0]}' is not a known CodeQL language`); + } + if (compressionMethod !== "zstd") { + return explain(`the bundle would be downloaded as '${compressionMethod}'`); + } + if (variant !== "GitHub.com" /* DOTCOM */) { + return explain(`we are running against ${variant}`); + } + if (!isGitHubHostedRunner(action.env)) { + return explain("the job is not running on a GitHub-hosted runner"); + } + if (!isLatestNightly) { + if (cliVersion2 === void 0) { + return explain("the requested CLI version is unknown"); + } + if (!semver7.gte(cliVersion2, MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION)) { + return explain( + `the requested CodeQL version ${cliVersion2} is older than ${MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION}, which is the first version for which per-language bundles are published` + ); + } + } + if (platform2 === void 0 || !PER_LANGUAGE_BUNDLE_LANGUAGES[platform2].has(language)) { + return explain( + `no per-language bundle is published for ${language} on ${platform2 ?? "an unknown platform"}` + ); + } + return language; +} +function logPerLanguageBundleFallback({ logger: logger2 }, language, location) { + logger2.warning( + `No per-language CodeQL bundle for '${language}' was found at ${location}, so falling back to the bundle that contains all languages. This analysis will still produce correct results, but will take longer to set up.` + ); +} + +// src/setup/repository.ts +var CODEQL_DEFAULT_ACTION_REPOSITORY = "github/codeql-action"; +function getCodeQLActionRepository(action) { + if (isRunningLocalAction(action.env)) { + action.logger.info( + "The CodeQL Action is checked out locally. Using the default CodeQL Action repository." + ); + return CODEQL_DEFAULT_ACTION_REPOSITORY; + } + const actionRepository = action.env.getRequired( + "GITHUB_ACTION_REPOSITORY" /* GITHUB_ACTION_REPOSITORY */ + ); + if (isRepositoryNwoStr(actionRepository)) { + return actionRepository; + } + throw new Error( + `The value of '${"GITHUB_ACTION_REPOSITORY" /* GITHUB_ACTION_REPOSITORY */}' is '${actionRepository}', which does not match the expected 'owner/repo' format.` + ); +} +var DEFAULT_DOWNLOAD_SOURCE = [ + GITHUB_DOTCOM_URL, + CODEQL_DEFAULT_ACTION_REPOSITORY +]; +var isSameDownloadSource = ([srcUrl, srcRepo], [otherUrl, otherRepo]) => { + return srcUrl === otherUrl && srcRepo === otherRepo; +}; +function getDefaultDotcomDownloadURL(tagName, assetName) { + return `${GITHUB_DOTCOM_URL}/${CODEQL_DEFAULT_ACTION_REPOSITORY}/releases/download/${tagName}/${assetName}`; +} +async function getCodeQLAssetDownloadURL(action, apiDetails, tagName, assetName, assetKind = "CodeQL bundle") { + const codeQLActionRepository = getCodeQLActionRepository(action); + const potentialDownloadSources = [ + // This GitHub instance, and this Action. + [apiDetails.url, codeQLActionRepository], + // This GitHub instance, and the canonical Action. + [apiDetails.url, CODEQL_DEFAULT_ACTION_REPOSITORY], + // GitHub.com, and the canonical Action. + DEFAULT_DOWNLOAD_SOURCE + ]; + const uniqueDownloadSources = potentialDownloadSources.filter( + (source, index2, self2) => { + return !self2.slice(0, index2).some((other) => isSameDownloadSource(source, other)); + } + ); + for (const [instanceURL, repository] of uniqueDownloadSources) { + if (isSameDownloadSource(DEFAULT_DOWNLOAD_SOURCE, [instanceURL, repository])) { + break; + } + const { owner: repositoryOwner, repo: repositoryName } = parseRepositoryNwo(repository); + try { + const release3 = await getApiClient().rest.repos.getReleaseByTag({ + owner: repositoryOwner, + repo: repositoryName, + tag: tagName + }); + for (const asset of release3.data.assets) { + if (asset.name === assetName) { + action.logger.info( + `Found ${assetKind} ${assetName} in ${repository} on ${instanceURL} with URL ${asset.url}.` + ); + return asset.url; + } + } + } catch (e) { + action.logger.info( + `Looked for ${assetKind} ${assetName} in ${repository} on ${instanceURL} but got error ${e}.` + ); + } + } + return getDefaultDotcomDownloadURL(tagName, assetName); +} + // src/tar.ts var import_child_process = require("child_process"); -var fs12 = __toESM(require("fs")); +var fs14 = __toESM(require("fs")); var stream = __toESM(require("stream")); var import_toolrunner = __toESM(require_toolrunner()); -var io4 = __toESM(require_io()); +var io5 = __toESM(require_io()); var toolcache = __toESM(require_tool_cache()); -var semver7 = __toESM(require_semver2()); +var semver8 = __toESM(require_semver2()); var MIN_REQUIRED_BSD_TAR_VERSION = "3.4.3"; var MIN_REQUIRED_GNU_TAR_VERSION = "1.31"; async function getTarVersion() { - const tar = await io4.which("tar", true); + const tar = await io5.which("tar", true); let stdout = ""; const exitCode = await new import_toolrunner.ToolRunner(tar, ["--version"], { listeners: { @@ -151354,30 +184531,30 @@ async function getTarVersion() { if (!match2?.[1]) { throw new Error("Failed to parse output of tar --version."); } - return { type: "gnu", version: match2[1] }; + return { type: "gnu", version: match2[1], path: tar }; } else if (stdout.includes("bsdtar")) { const match2 = stdout.match(/bsdtar ([0-9.]+)/); if (!match2?.[1]) { throw new Error("Failed to parse output of tar --version."); } - return { type: "bsd", version: match2[1] }; + return { type: "bsd", version: match2[1], path: tar }; } else { throw new Error("Unknown tar version"); } } -async function isZstdAvailable(logger) { - const foundZstdBinary = await isBinaryAccessible("zstd", logger); +async function isZstdAvailable(logger2) { + const foundZstdBinary = await isBinaryAccessible("zstd", logger2); try { const tarVersion = await getTarVersion(); const { type, version } = tarVersion; - logger.info(`Found ${type} tar version ${version}.`); + logger2.info(`Found ${type} tar version ${version}.`); switch (type) { case "gnu": return { available: foundZstdBinary && // GNU tar only uses major and minor version numbers - semver7.gte( - semver7.coerce(version), - semver7.coerce(MIN_REQUIRED_GNU_TAR_VERSION) + semver8.gte( + semver8.coerce(version), + semver8.coerce(MIN_REQUIRED_GNU_TAR_VERSION) ), foundZstdBinary, version: tarVersion @@ -151386,7 +184563,7 @@ async function isZstdAvailable(logger) { return { available: foundZstdBinary && // Do a loose comparison since these version numbers don't contain // a patch version number. - semver7.gte(version, MIN_REQUIRED_BSD_TAR_VERSION), + semver8.gte(version, MIN_REQUIRED_BSD_TAR_VERSION), foundZstdBinary, version: tarVersion }; @@ -151394,14 +184571,14 @@ async function isZstdAvailable(logger) { assertNever(type); } } catch (e) { - logger.warning( + logger2.warning( `Failed to determine tar version, therefore will assume zstd is not available. The underlying error was: ${e}` ); return { available: false, foundZstdBinary }; } } -async function extract(tarPath, dest, compressionMethod, tarVersion, logger) { - fs12.mkdirSync(dest, { recursive: true }); +async function extract(tarPath, dest, compressionMethod, tarVersion, logger2) { + fs14.mkdirSync(dest, { recursive: true }); switch (compressionMethod) { case "gzip": return await toolcache.extractTar(tarPath, dest); @@ -151411,13 +184588,13 @@ async function extract(tarPath, dest, compressionMethod, tarVersion, logger) { "Could not determine tar version, which is required to extract a Zstandard archive." ); } - await extractTarZst(tarPath, dest, tarVersion, logger); + await extractTarZst(tarPath, dest, tarVersion, logger2); return dest; } } } -async function extractTarZst(tar, dest, tarVersion, logger) { - logger.debug( +async function extractTarZst(tar, dest, tarVersion, logger2) { + logger2.debug( `Extracting to ${dest}.${tar instanceof stream.Readable ? ` Input stream has high water mark ${tar.readableHighWaterMark}.` : ""}` ); try { @@ -151427,10 +184604,10 @@ async function extractTarZst(tar, dest, tarVersion, logger) { args.push("--overwrite"); } args.push("-f", tar instanceof stream.Readable ? "-" : tar, "-C", dest); - process.stdout.write(`[command]tar ${args.join(" ")} + process.stdout.write(`[command]${tarVersion.path} ${args.join(" ")} `); - await new Promise((resolve14, reject) => { - const tarProcess = (0, import_child_process.spawn)("tar", args, { stdio: "pipe" }); + await new Promise((resolve15, reject) => { + const tarProcess = (0, import_child_process.spawn)(tarVersion.path, args, { stdio: "pipe" }); let stdout = ""; tarProcess.stdout?.on("data", (data) => { stdout += data.toString(); @@ -151457,19 +184634,19 @@ async function extractTarZst(tar, dest, tarVersion, logger) { if (code !== 0) { reject( new CommandInvocationError( - "tar", + tarVersion.path, args, code ?? void 0, - stdout, - stderr + stderr, + stdout ) ); } - resolve14(); + resolve15(); }); }); } catch (e) { - await cleanUpPath(dest, "extraction destination directory", logger); + await cleanUpPath(dest, "extraction destination directory", logger2); throw e; } } @@ -151487,95 +184664,100 @@ function inferCompressionMethod(tarPath) { } // src/tools-download.ts -var fs13 = __toESM(require("fs")); -var os4 = __toESM(require("os")); +var fs15 = __toESM(require("fs")); +var os5 = __toESM(require("os")); var path12 = __toESM(require("path")); -var import_perf_hooks2 = require("perf_hooks"); +var import_perf_hooks3 = require("perf_hooks"); var core11 = __toESM(require_core()); var import_http_client = __toESM(require_lib()); var toolcache2 = __toESM(require_tool_cache()); var import_follow_redirects = __toESM(require_follow_redirects()); -var semver8 = __toESM(require_semver2()); +var semver9 = __toESM(require_semver2()); var STREAMING_HIGH_WATERMARK_BYTES = 4 * 1024 * 1024; var STREAMING_STALL_TIMEOUT_MS = 5 * 60 * 1e3; var TOOLCACHE_TOOL_NAME = "CodeQL"; -async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorization, headers, tarVersion, logger) { - logger.info( +async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorization, headers, tarVersion, logger2) { + logger2.info( `Downloading CodeQL tools from ${codeqlURL} . This may take a while.` ); + const startTime = import_perf_hooks3.performance.now(); try { if (compressionMethod === "zstd" && process.platform === "linux") { - logger.info(`Streaming the extraction of the CodeQL bundle.`); - const toolsInstallStart = import_perf_hooks2.performance.now(); + logger2.info(`Streaming the extraction of the CodeQL bundle.`); await downloadAndExtractZstdWithStreaming( codeqlURL, dest, authorization, headers, tarVersion, - logger + logger2 ); - const combinedDurationMs = Math.round( - import_perf_hooks2.performance.now() - toolsInstallStart - ); - logger.info( + const totalDurationMs = durationMsSince(startTime); + logger2.info( `Finished downloading and extracting CodeQL bundle to ${dest} (${formatDuration( - combinedDurationMs + totalDurationMs )}).` ); - return {}; + return { totalDurationMs }; } } catch (e) { + await cleanUpPath(dest, "CodeQL bundle", logger2); + if (asHTTPError(e)?.status === 404) { + throw e; + } core11.warning( `Failed to download and extract CodeQL bundle using streaming with error: ${getErrorMessage(e)}` ); core11.warning(`Falling back to downloading the bundle before extracting.`); - await cleanUpPath(dest, "CodeQL bundle", logger); } - const toolsDownloadStart = import_perf_hooks2.performance.now(); + const toolsDownloadStart = import_perf_hooks3.performance.now(); const archivedBundlePath = await toolcache2.downloadTool( codeqlURL, void 0, authorization, headers ); - const downloadDurationMs = Math.round(import_perf_hooks2.performance.now() - toolsDownloadStart); - logger.info( + const downloadDurationMs = durationMsSince(toolsDownloadStart); + logger2.info( `Finished downloading CodeQL bundle to ${archivedBundlePath} (${formatDuration( downloadDurationMs )}).` ); let extractionDurationMs; try { - logger.info("Extracting CodeQL bundle."); - const extractionStart = import_perf_hooks2.performance.now(); + logger2.info("Extracting CodeQL bundle."); + const extractionStart = import_perf_hooks3.performance.now(); await extract( archivedBundlePath, dest, compressionMethod, tarVersion, - logger + logger2 ); - extractionDurationMs = Math.round(import_perf_hooks2.performance.now() - extractionStart); - logger.info( + extractionDurationMs = durationMsSince(extractionStart); + logger2.info( `Finished extracting CodeQL bundle to ${dest} (${formatDuration( extractionDurationMs )}).` ); } finally { - await cleanUpPath(archivedBundlePath, "CodeQL bundle archive", logger); + await cleanUpPath(archivedBundlePath, "CodeQL bundle archive", logger2); } - return { downloadDurationMs }; + return { + downloadDurationMs, + extractionDurationMs, + totalDurationMs: durationMsSince(startTime) + }; } -async function downloadAndExtractZstdWithStreaming(codeqlURL, dest, authorization, headers, tarVersion, logger) { - fs13.mkdirSync(dest, { recursive: true }); +async function downloadAndExtractZstdWithStreaming(codeqlURL, dest, authorization, headers, tarVersion, logger2) { + fs15.mkdirSync(dest, { recursive: true }); const agent = new import_http_client.HttpClient().getAgent(codeqlURL); headers = Object.assign( { "User-Agent": "CodeQL Action" }, authorization ? { authorization } : {}, headers ); - const response = await new Promise((resolve14, reject) => { + const response = await new Promise((resolve15, reject) => { const request3 = import_follow_redirects.https.get( codeqlURL, { @@ -151585,7 +184767,7 @@ async function downloadAndExtractZstdWithStreaming(codeqlURL, dest, authorizatio // Use the agent to respect proxy settings. agent }, - (r) => resolve14(r) + (r) => resolve15(r) ); request3.on("error", reject); request3.setTimeout(STREAMING_STALL_TIMEOUT_MS, () => { @@ -151598,127 +184780,142 @@ async function downloadAndExtractZstdWithStreaming(codeqlURL, dest, authorizatio }); if (response.statusCode !== 200) { response.resume(); - throw new Error( - `Failed to download CodeQL bundle from ${codeqlURL}. HTTP status code: ${response.statusCode}.` - ); + const baseMessage = `Failed to download CodeQL bundle from ${codeqlURL}.`; + if (response.statusCode !== void 0) { + throw new HTTPError( + `${baseMessage} HTTP status code: ${response.statusCode}.`, + response.statusCode + ); + } + throw new Error(baseMessage); } - await extractTarZst(response, dest, tarVersion, logger); + await extractTarZst(response, dest, tarVersion, logger2); } -function getToolcacheDirectory(version) { +function getToolcacheToolDirectory(env) { return path12.join( - getRequiredEnvParam("RUNNER_TOOL_CACHE"), - TOOLCACHE_TOOL_NAME, - semver8.clean(version) || version, - os4.arch() || "" + env.getRequired("RUNNER_TOOL_CACHE" /* RUNNER_TOOL_CACHE */), + TOOLCACHE_TOOL_NAME ); } -function writeToolcacheMarkerFile(extractedPath, logger) { - const markerFilePath = `${extractedPath}.complete`; - fs13.writeFileSync(markerFilePath, ""); - logger.info(`Created toolcache marker file ${markerFilePath}`); +function getToolcacheVersionDirectoryName(version) { + return semver9.clean(version) || version; } - -// src/setup-codeql.ts -var CODEQL_DEFAULT_ACTION_REPOSITORY = "github/codeql-action"; -var CODEQL_NIGHTLIES_REPOSITORY_OWNER = "dsp-testing"; -var CODEQL_NIGHTLIES_REPOSITORY_NAME = "codeql-cli-nightlies"; -var CODEQL_BUNDLE_VERSION_ALIAS = ["linked", "latest"]; -var CODEQL_NIGHTLY_TOOLS_INPUTS = ["nightly", "nightly-latest"]; -var CODEQL_TOOLCACHE_INPUT = "toolcache"; -function getCodeQLBundleExtension(compressionMethod) { - switch (compressionMethod) { - case "gzip": - return ".tar.gz"; - case "zstd": - return ".tar.zst"; - default: - assertNever(compressionMethod); - } +function getToolcacheDirectory(version) { + return path12.join( + getToolcacheToolDirectory(getEnv()), + getToolcacheVersionDirectoryName(version), + os5.arch() || "" + ); } -function getCodeQLBundleName(compressionMethod) { - const extension = getCodeQLBundleExtension(compressionMethod); - let platform2; - if (process.platform === "win32") { - platform2 = "win64"; - } else if (process.platform === "linux") { - platform2 = "linux64"; - } else if (process.platform === "darwin") { - platform2 = "osx64"; - } else { - return `codeql-bundle${extension}`; +function isToolcacheOnWorkspaceFilesystem(logger2) { + try { + return fs15.statSync(getRequiredEnvParam("RUNNER_TOOL_CACHE")).dev === fs15.statSync(getRequiredEnvParam("GITHUB_WORKSPACE")).dev; + } catch (e) { + logger2.debug( + `Could not determine whether the toolcache is on the same filesystem as the workspace: ${getErrorMessage(e)}` + ); + return false; } - return `codeql-bundle-${platform2}${extension}`; } -function getCodeQLActionRepository(logger) { - if (isRunningLocalAction()) { - logger.info( - "The CodeQL Action is checked out locally. Using the default CodeQL Action repository." +async function deleteToolcacheBundles({ + env, + logger: logger2 +}) { + let toolDirectory; + try { + toolDirectory = getToolcacheToolDirectory(env); + } catch (e) { + logger2.info( + `Unable to determine toolcache directory: ${getErrorMessage(e)}` ); - return CODEQL_DEFAULT_ACTION_REPOSITORY; + return { deletedVersions: [], failed: true }; } - return getRequiredEnvParam("GITHUB_ACTION_REPOSITORY"); -} -async function getCodeQLBundleDownloadURL(tagName, apiDetails, compressionMethod, logger) { - const codeQLActionRepository = getCodeQLActionRepository(logger); - const potentialDownloadSources = [ - // This GitHub instance, and this Action. - [apiDetails.url, codeQLActionRepository], - // This GitHub instance, and the canonical Action. - [apiDetails.url, CODEQL_DEFAULT_ACTION_REPOSITORY], - // GitHub.com, and the canonical Action. - [GITHUB_DOTCOM_URL, CODEQL_DEFAULT_ACTION_REPOSITORY] - ]; - const uniqueDownloadSources = potentialDownloadSources.filter( - (source, index2, self2) => { - return !self2.slice(0, index2).some((other) => (0, import_fast_deep_equal.default)(source, other)); + try { + if ((await fs15.promises.lstat(toolDirectory)).isSymbolicLink()) { + logger2.info( + `Not deleting the CodeQL tools from the toolcache since '${toolDirectory}' is a symlink.` + ); + return { deletedVersions: [], failed: true }; } - ); - const codeQLBundleName = getCodeQLBundleName(compressionMethod); - for (const downloadSource of uniqueDownloadSources) { - const [apiURL, repository] = downloadSource; - if (apiURL === GITHUB_DOTCOM_URL && repository === CODEQL_DEFAULT_ACTION_REPOSITORY) { - break; + } catch (e) { + if (e?.code === "ENOENT") { + logger2.debug( + `There are no CodeQL tools at '${toolDirectory}' to delete from the toolcache.` + ); + return { deletedVersions: [], failed: false }; } - const [repositoryOwner, repositoryName] = repository.split("/"); - try { - const release2 = await getApiClient().rest.repos.getReleaseByTag({ - owner: repositoryOwner, - repo: repositoryName, - tag: tagName - }); - for (const asset of release2.data.assets) { - if (asset.name === codeQLBundleName) { - logger.info( - `Found CodeQL bundle ${codeQLBundleName} in ${repository} on ${apiURL} with URL ${asset.url}.` - ); - return asset.url; - } + logger2.info( + `Failed to inspect the CodeQL tools at '${toolDirectory}': ${getErrorMessage(e)}` + ); + return { deletedVersions: [], failed: true }; + } + try { + const entries = await fs15.promises.readdir(toolDirectory, { + withFileTypes: true + }); + const deletedVersions = []; + let failed = false; + for (const entry of entries) { + if (!entry.isDirectory()) { + logger2.debug( + `Not deleting '${entry.name}' from the CodeQL toolcache since it is not a directory.` + ); + continue; + } + const versionDirectory = path12.join(toolDirectory, entry.name); + try { + await fs15.promises.rm(versionDirectory, { + force: true, + recursive: true + }); + deletedVersions.push(entry.name); + logger2.info( + `Deleted the CodeQL tools at '${versionDirectory}' from the toolcache to free up disk space.` + ); + } catch (e) { + failed = true; + logger2.info( + `Failed to delete the CodeQL tools at '${versionDirectory}' from the toolcache: ${getErrorMessage(e)}` + ); } - } catch (e) { - logger.info( - `Looked for CodeQL bundle ${codeQLBundleName} in ${repository} on ${apiURL} but got error ${e}.` - ); } + return { deletedVersions: deletedVersions.sort(), failed }; + } catch (e) { + logger2.info( + `Failed to clean up the CodeQL toolcache at '${toolDirectory}': ${getErrorMessage(e)}` + ); + return { deletedVersions: [], failed: true }; } - return `https://github.com/${CODEQL_DEFAULT_ACTION_REPOSITORY}/releases/download/${tagName}/${codeQLBundleName}`; } -function tryGetBundleVersionFromTagName(tagName, logger) { - const match2 = tagName.match(/^codeql-bundle-(.*)$/); +function writeToolcacheMarkerFile(extractedPath, logger2) { + const markerFilePath = `${extractedPath}.complete`; + fs15.writeFileSync(markerFilePath, ""); + logger2.info(`Created toolcache marker file ${markerFilePath}`); +} + +// src/setup-codeql.ts +var CODEQL_NIGHTLIES_REPOSITORY_OWNER = "dsp-testing"; +var CODEQL_NIGHTLIES_REPOSITORY_NAME = "codeql-cli-nightlies"; +var CODEQL_BUNDLE_VERSION_ALIAS = ["linked", "latest"]; +var CODEQL_NIGHTLY_TOOLS_INPUTS = ["nightly", "nightly-latest"]; +var CODEQL_TOOLCACHE_INPUT = "toolcache"; +function tryGetBundleVersionFromTagName(tagName, logger2) { + const match2 = tagName.match(/^codeql-bundle-(.+)$/); if (match2 === null || match2.length < 2) { - logger.debug(`Could not determine bundle version from tag ${tagName}.`); + logger2.debug(`Could not determine bundle version from tag ${tagName}.`); return void 0; } return match2[1]; } -function tryGetTagNameFromUrl(url2, logger) { +function tryGetTagNameFromUrl(url2, logger2) { const matches = [...url2.matchAll(/\/(codeql-bundle-[^/]*)\//g)]; if (matches.length === 0) { - logger.debug(`Could not determine tag name for URL ${url2}.`); + logger2.debug(`Could not determine tag name for URL ${url2}.`); return void 0; } const match2 = matches[matches.length - 1]; if (match2?.length !== 2) { - logger.debug( + logger2.debug( `Could not determine tag name for URL ${url2}. Matched ${JSON.stringify( match2 )}.` @@ -151727,27 +184924,27 @@ function tryGetTagNameFromUrl(url2, logger) { } return match2[1]; } -function convertToSemVer(version, logger) { - if (!semver9.valid(version)) { - logger.debug( +function convertToSemVer(version, logger2) { + if (!semver10.valid(version)) { + logger2.debug( `Bundle version ${version} is not in SemVer format. Will treat it as pre-release 0.0.0-${version}.` ); version = `0.0.0-${version}`; } - const s = semver9.clean(version); + const s = semver10.clean(version); if (!s) { throw new Error(`Bundle version ${version} is not in SemVer format.`); } return s; } -async function findOverridingToolsInCache(humanReadableVersion, logger) { +async function findOverridingToolsInCache(humanReadableVersion, logger2) { const candidates = toolcache3.findAllVersions("CodeQL").filter(isGoodVersion).map((version) => ({ folder: toolcache3.find("CodeQL", version), version - })).filter(({ folder }) => fs14.existsSync(path13.join(folder, "pinned-version"))); + })).filter(({ folder }) => fs16.existsSync(path13.join(folder, "pinned-version"))); if (candidates.length === 1) { const candidate = candidates[0]; - logger.debug( + logger2.debug( `CodeQL tools version ${candidate.version} in toolcache overriding version ${humanReadableVersion}.` ); return { @@ -151756,35 +184953,28 @@ async function findOverridingToolsInCache(humanReadableVersion, logger) { toolsVersion: candidate.version }; } else if (candidates.length === 0) { - logger.debug( + logger2.debug( "Did not find any candidate pinned versions of the CodeQL tools in the toolcache." ); } else { - logger.debug( + logger2.debug( "Could not use CodeQL tools from the toolcache since more than one candidate pinned version was found in the toolcache." ); } return void 0; } -async function getEnabledVersionsWithOverlayBaseDatabases(defaultCliVersion, rawLanguages, features, logger) { +async function getEnabledVersionsWithOverlayBaseDatabases(defaultCliVersion, rawLanguages, logger2) { if (rawLanguages === void 0 || rawLanguages.length === 0) { return []; } - const isEnabled = await features.getValue( - "overlay_analysis_match_codeql_version" /* OverlayAnalysisMatchCodeqlVersion */ - ); - const isDryRun = !isEnabled && await features.getValue("overlay_analysis_match_codeql_version_dry_run" /* OverlayAnalysisMatchCodeqlVersionDryRun */); - if (!isEnabled && !isDryRun) { - return []; - } let cachedVersions; try { cachedVersions = await getCodeQlVersionsForOverlayBaseDatabases( rawLanguages, - logger + logger2 ); } catch (e) { - logger.warning( + logger2.warning( `Could not list overlay-base databases in the Actions cache while choosing a default CodeQL CLI version, falling back to the highest enabled version. Details: ${getErrorMessage(e)}` ); return []; @@ -151793,59 +184983,31 @@ async function getEnabledVersionsWithOverlayBaseDatabases(defaultCliVersion, raw return []; } const cachedVersionsSet = new Set(cachedVersions); - const overlayVersions = defaultCliVersion.enabledVersions.filter( + return defaultCliVersion.enabledVersions.filter( (v) => cachedVersionsSet.has(v.cliVersion) ); - if (overlayVersions.length === 0) { - return []; - } - const isCachedVersionDifferent = overlayVersions[0].cliVersion !== defaultCliVersion.enabledVersions[0].cliVersion; - if (isCachedVersionDifferent) { - addNoLanguageDiagnostic( - void 0, - makeTelemetryDiagnostic( - "codeql-action/overlay-aware-default-codeql-version", - "Overlay-aware default CodeQL version selection", - { - cachedVersions, - enabledVersions: defaultCliVersion.enabledVersions.map( - (v) => v.cliVersion - ), - isDryRun, - overlayAwareVersion: overlayVersions[0].cliVersion - } - ) - ); - } - if (isDryRun) { - logger.debug( - `Overlay-aware default CodeQL version selection is running in dry-run mode. Would have used version ${overlayVersions[0].cliVersion}.` - ); - return []; - } - return overlayVersions; } -async function resolveDefaultCliVersion(defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, features, logger) { - if (!useOverlayAwareDefaultCliVersion || !isAnalyzingPullRequest()) { +async function resolveDefaultCliVersion(defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, logger2) { + if (!useOverlayAwareDefaultCliVersion || // Listing the Actions cache can't change which version we use if only one version is enabled. + defaultCliVersion.enabledVersions.length === 1 || !isAnalyzingPullRequest()) { return defaultCliVersion.enabledVersions[0]; } const overlayVersions = await getEnabledVersionsWithOverlayBaseDatabases( defaultCliVersion, rawLanguages, - features, - logger + logger2 ); if (overlayVersions.length > 0) { - logger.info( + logger2.info( `Using CodeQL version ${overlayVersions[0].cliVersion} since this is the highest enabled version that has a cached overlay-base database.` ); return overlayVersions[0]; } return defaultCliVersion.enabledVersions[0]; } -async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, apiDetails, variant, tarSupportsZstd, features, logger) { +async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, otherLanguagePacksReason, useOverlayAwareDefaultCliVersion, apiDetails, variant, tarSupportsZstd, features, logger2) { if (toolsInput && !isReservedToolsValue(toolsInput) && !toolsInput.startsWith("http")) { - logger.info(`Using CodeQL CLI from local path ${toolsInput}`); + logger2.info(`Using CodeQL CLI from local path ${toolsInput}`); const compressionMethod2 = inferCompressionMethod(toolsInput); if (compressionMethod2 === void 0) { throw new ConfigurationError( @@ -151862,13 +185024,14 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO let cliVersion2; let tagName; let url2; + let bundle; const canForceNightlyWithFF = isDynamicWorkflow() || isInTestMode(); const forceNightlyValueFF = await features.getValue("force_nightly" /* ForceNightly */); const forceNightly = forceNightlyValueFF && canForceNightlyWithFF; const nightlyRequestedByToolsInput = toolsInput !== void 0 && CODEQL_NIGHTLY_TOOLS_INPUTS.includes(toolsInput); if (forceNightly || nightlyRequestedByToolsInput) { if (forceNightly) { - logger.info( + logger2.info( `Using the latest CodeQL CLI nightly, as forced by the ${"force_nightly" /* ForceNightly */} feature flag.` ); addNoLanguageDiagnostic( @@ -151888,21 +185051,27 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO ) ); } else { - logger.info( + logger2.info( `Using the latest CodeQL CLI nightly, as requested by 'tools: ${toolsInput}'.` ); } - toolsInput = await getNightlyToolsUrl(logger); + bundle = await getLatestNightlyBundle( + { env: getEnv(), logger: logger2 }, + rawLanguages, + otherLanguagePacksReason, + variant + ); + toolsInput = bundle.url; } const forceShippedTools = toolsInput && CODEQL_BUNDLE_VERSION_ALIAS.includes(toolsInput); if (forceShippedTools) { cliVersion2 = cliVersion; tagName = bundleVersion; - logger.info( + logger2.info( `'tools: ${toolsInput}' was requested, so using CodeQL version ${cliVersion2}, the version shipped with the Action.` ); if (toolsInput === "latest") { - logger.warning( + logger2.warning( "`tools: latest` has been renamed to `tools: linked`, but the old name is still supported. No action is required." ); } @@ -151910,21 +185079,21 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO let latestToolcacheVersion; const allowToolcacheValue = isDynamicWorkflow() || isInTestMode(); if (allowToolcacheValue) { - logger.info( + logger2.info( `Attempting to use the latest CodeQL CLI version in the toolcache, as requested by 'tools: ${toolsInput}'.` ); - latestToolcacheVersion = getLatestToolcacheVersion(logger); + latestToolcacheVersion = getLatestToolcacheVersion(logger2); if (latestToolcacheVersion) { cliVersion2 = latestToolcacheVersion; } } if (latestToolcacheVersion === void 0) { if (allowToolcacheValue) { - logger.info( + logger2.info( `Found no CodeQL CLI in the toolcache, ignoring 'tools: ${toolsInput}'...` ); } else { - logger.warning( + logger2.warning( `Ignoring 'tools: ${toolsInput}' because the workflow was not triggered dynamically.` ); } @@ -151932,19 +185101,18 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, - features, - logger + logger2 ); cliVersion2 = version.cliVersion; tagName = version.tagName; } } else if (toolsInput !== void 0) { - tagName = tryGetTagNameFromUrl(toolsInput, logger); + tagName = tryGetTagNameFromUrl(toolsInput, logger2); url2 = toolsInput; if (tagName) { - const bundleVersion3 = tryGetBundleVersionFromTagName(tagName, logger); - if (bundleVersion3 && semver9.valid(bundleVersion3)) { - cliVersion2 = convertToSemVer(bundleVersion3, logger); + const bundleVersion3 = tryGetBundleVersionFromTagName(tagName, logger2); + if (bundleVersion3 !== void 0 && semver10.valid(bundleVersion3)) { + cliVersion2 = convertToSemVer(bundleVersion3, logger2); } } } else { @@ -151952,26 +185120,26 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, - features, - logger + logger2 ); cliVersion2 = version.cliVersion; tagName = version.tagName; } - const bundleVersion2 = tagName && tryGetBundleVersionFromTagName(tagName, logger); - const humanReadableVersion = cliVersion2 ?? (bundleVersion2 && convertToSemVer(bundleVersion2, logger)) ?? tagName ?? url2 ?? "unknown"; - logger.debug( + const bundleVersion2 = tagName !== void 0 ? tryGetBundleVersionFromTagName(tagName, logger2) : void 0; + const resolvedVersion = cliVersion2 ?? (bundleVersion2 !== void 0 ? convertToSemVer(bundleVersion2, logger2) : void 0); + const humanReadableVersion = resolvedVersion ?? tagName ?? url2 ?? "unknown"; + logger2.debug( `Attempting to obtain CodeQL tools. CLI version: ${cliVersion2 ?? "unknown"}, bundle tag name: ${tagName ?? "unknown"}, URL: ${url2 ?? "unspecified"}.` ); let codeqlFolder; if (cliVersion2) { codeqlFolder = toolcache3.find("CodeQL", cliVersion2); if (!codeqlFolder) { - logger.debug( + logger2.debug( `Didn't find a version of the CodeQL tools in the toolcache with a version number exactly matching ${cliVersion2}.` ); const allVersions = toolcache3.findAllVersions("CodeQL"); - logger.debug( + logger2.debug( `Found the following versions of the CodeQL tools in the toolcache: ${JSON.stringify( allVersions )}.` @@ -151980,19 +185148,19 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO (version) => version.startsWith(`${cliVersion2}-`) ); if (candidateVersions.length === 1) { - logger.debug( + logger2.debug( `Exactly one version of the CodeQL tools starting with ${cliVersion2} found in the toolcache, using that.` ); codeqlFolder = toolcache3.find("CodeQL", candidateVersions[0]); } else if (candidateVersions.length === 0) { - logger.debug( + logger2.debug( `Didn't find any versions of the CodeQL tools starting with ${cliVersion2} in the toolcache. Trying next fallback method.` ); } else { - logger.warning( + logger2.warning( `Found ${candidateVersions.length} versions of the CodeQL tools starting with ${cliVersion2} in the toolcache, but at most one was expected.` ); - logger.debug("Trying next fallback method."); + logger2.debug("Trying next fallback method."); } } } @@ -152000,32 +185168,32 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO const fallbackVersion = await tryGetFallbackToolcacheVersion( cliVersion2, tagName, - logger + logger2 ); if (fallbackVersion) { codeqlFolder = toolcache3.find("CodeQL", fallbackVersion); } else { - logger.debug( + logger2.debug( `Could not determine a fallback toolcache version number for CodeQL tools version ${humanReadableVersion}.` ); } } if (codeqlFolder) { - logger.info( + logger2.info( `Found CodeQL tools version ${humanReadableVersion} in the toolcache.` ); } else { - logger.info( + logger2.info( `Did not find CodeQL tools version ${humanReadableVersion} in the toolcache.` ); } if (codeqlFolder) { if (cliVersion2) { - logger.info( + logger2.info( `Using CodeQL CLI version ${cliVersion2} from toolcache at ${codeqlFolder}` ); } else { - logger.info(`Using CodeQL CLI from toolcache at ${codeqlFolder}`); + logger2.info(`Using CodeQL CLI from toolcache at ${codeqlFolder}`); } return { codeqlFolder, @@ -152036,7 +185204,7 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO if (variant === "GitHub Enterprise Server" /* GHES */ && !forceShippedTools && !toolsInput) { const result = await findOverridingToolsInCache( humanReadableVersion, - logger + logger2 ); if (result !== void 0) { return result; @@ -152044,13 +185212,45 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO } let compressionMethod; if (!url2) { + const bundleTagName = tagName; + if (bundleTagName === void 0) { + throw new Error( + "Could not determine a release tag for the requested CodeQL bundle." + ); + } compressionMethod = cliVersion2 !== void 0 && await useZstdBundle(cliVersion2, tarSupportsZstd) ? "zstd" : "gzip"; - url2 = await getCodeQLBundleDownloadURL( - tagName, - apiDetails, + const action = { env: getEnv(), logger: logger2 }; + const platform2 = getBundlePlatform(); + const perLanguageBundleLanguage = getPerLanguageBundleLanguage(action, { + rawLanguages, + otherLanguagePacksReason, + cliVersion: cliVersion2, compressionMethod, - logger + platform: platform2, + variant + }); + const resolveBundleURL = (language) => getCodeQLAssetDownloadURL( + action, + apiDetails, + bundleTagName, + getCodeQLBundleName(compressionMethod, platform2, language) ); + const combinedBundleURL = await resolveBundleURL(); + if (perLanguageBundleLanguage !== void 0) { + logger2.info( + `Selected the per-language CodeQL bundle for '${perLanguageBundleLanguage}'.` + ); + url2 = await resolveBundleURL(perLanguageBundleLanguage); + bundle = { + kind: "per-language", + url: url2, + language: perLanguageBundleLanguage, + combinedBundleURL + }; + } else { + url2 = combinedBundleURL; + bundle = { kind: "combined", url: url2 }; + } } else { const method = inferCompressionMethod(url2); if (method === void 0) { @@ -152059,33 +185259,41 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO ); } compressionMethod = method; + bundle ??= getCodeQLBundleFromUrl(url2); + if (bundle.kind === "per-language") { + logger2.info( + `${url2} appears to be a CodeQL bundle that contains only ${bundle.language}.` + ); + } } if (cliVersion2) { - logger.info(`Using CodeQL CLI version ${cliVersion2} sourced from ${url2} .`); + logger2.info(`Using CodeQL CLI version ${cliVersion2} sourced from ${url2} .`); } else { - logger.info(`Using CodeQL CLI sourced from ${url2} .`); + logger2.info(`Using CodeQL CLI sourced from ${url2} .`); } return { - bundleVersion: tagName && tryGetBundleVersionFromTagName(tagName, logger), + bundle, + bundleVersion: bundleVersion2, cliVersion: cliVersion2, - codeqlURL: url2, compressionMethod, sourceType: "download", - toolsVersion: cliVersion2 ?? humanReadableVersion + toolsVersion: resolvedVersion ?? "unknown" }; } -async function tryGetFallbackToolcacheVersion(cliVersion2, tagName, logger) { - const bundleVersion2 = tryGetBundleVersionFromTagName(tagName, logger); - if (!bundleVersion2) { +async function tryGetFallbackToolcacheVersion(cliVersion2, tagName, logger2) { + const bundleVersion2 = tryGetBundleVersionFromTagName(tagName, logger2); + if (bundleVersion2 === void 0) { return void 0; } - const fallbackVersion = convertToSemVer(bundleVersion2, logger); - logger.debug( + const fallbackVersion = convertToSemVer(bundleVersion2, logger2); + logger2.debug( `Computed a fallback toolcache version number of ${fallbackVersion} for CodeQL version ${cliVersion2 ?? tagName}.` ); return fallbackVersion; } -var downloadCodeQL = async function(codeqlURL, compressionMethod, maybeBundleVersion, maybeCliVersion, apiDetails, tarVersion, tempDir, logger) { +var downloadCodeQL = async function(source, apiDetails, tarVersion, tempDir, logger2) { + const { bundle, compressionMethod } = source; + const codeqlURL = bundle.url; const parsedCodeQLURL = new URL(codeqlURL); const searchParams = new URLSearchParams(parsedCodeQLURL.search); const headers = { @@ -152093,20 +185301,18 @@ var downloadCodeQL = async function(codeqlURL, compressionMethod, maybeBundleVer }; let authorization = void 0; if (searchParams.has("token")) { - logger.debug("CodeQL tools URL contains an authorization token."); + logger2.debug("CodeQL tools URL contains an authorization token."); } else { authorization = getAuthorizationHeaderFor( - logger, + logger2, apiDetails, codeqlURL ); } - const toolcacheInfo = getToolcacheDestinationInfo( - maybeBundleVersion, - maybeCliVersion, - logger + const toolcacheDestination = getToolcacheDestination({ logger: logger2 }, source); + const extractedBundlePath = toolcacheDestination.orElse( + getTempExtractionDir(tempDir) ); - const extractedBundlePath = toolcacheInfo?.path ?? getTempExtractionDir(tempDir); const statusReport = await downloadAndExtract( codeqlURL, compressionMethod, @@ -152114,65 +185320,91 @@ var downloadCodeQL = async function(codeqlURL, compressionMethod, maybeBundleVer authorization, { "User-Agent": "CodeQL Action", ...headers }, tarVersion, - logger + logger2 ); - if (!toolcacheInfo) { - logger.debug( - `Could not cache CodeQL tools because we could not determine the bundle version from the URL ${codeqlURL}.` - ); - return { - codeqlFolder: extractedBundlePath, - statusReport, - toolsVersion: maybeCliVersion ?? "unknown" - }; + if (toolcacheDestination.isSuccess()) { + writeToolcacheMarkerFile(toolcacheDestination.value, logger2); + } else { + logger2.debug(toolcacheDestination.value); } - writeToolcacheMarkerFile(toolcacheInfo.path, logger); return { codeqlFolder: extractedBundlePath, - statusReport, - toolsVersion: maybeCliVersion ?? toolcacheInfo.version + statusReport: bundle.kind === "per-language" ? { + ...statusReport, + perLanguage: { tools_bundle_language: bundle.language } + } : statusReport }; }; -function getToolcacheDestinationInfo(maybeBundleVersion, maybeCliVersion, logger) { - if (maybeBundleVersion) { - const version = getCanonicalToolcacheVersion( - maybeCliVersion, - maybeBundleVersion, - logger +function getToolcacheDestination({ logger: logger2 }, source) { + if (source.bundle.kind !== "combined") { + return new Failure( + "Not caching the CodeQL tools because they came from a bundle that contains only a single language." ); - return { - path: getToolcacheDirectory(version), - version - }; } - return void 0; + if (!source.bundleVersion) { + return new Failure( + `Could not cache CodeQL tools because we could not determine the bundle version from the URL ${source.bundle.url}.` + ); + } + return new Success( + getToolcacheDirectory( + getCanonicalToolcacheVersion( + source.cliVersion, + source.bundleVersion, + logger2 + ) + ) + ); +} +async function tryDeleteToolcacheBundles({ + env, + logger: logger2 +}) { + if (env.getOptional("CODEQL_ACTION_HAS_SET_UP_CODEQL" /* HAS_SET_UP_CODEQL */) !== void 0) { + logger2.debug( + "Not deleting the CodeQL tools from the toolcache since a previous step in this job has already set up CodeQL." + ); + return; + } + if (!isGitHubHostedRunner(env) || !isToolcacheOnWorkspaceFilesystem(logger2)) { + return; + } + const result = await deleteToolcacheBundles({ env, logger: logger2 }); + addNoLanguageDiagnostic( + void 0, + makeTelemetryDiagnostic( + "codeql-action/toolcache-bundle-cleanup", + "Toolcache CodeQL bundle cleanup", + { ...result } + ) + ); } -function getCanonicalToolcacheVersion(cliVersion2, bundleVersion2, logger) { +function getCanonicalToolcacheVersion(cliVersion2, bundleVersion2, logger2) { if (!cliVersion2?.match(/^[0-9]+\.[0-9]+\.[0-9]+$/)) { - return convertToSemVer(bundleVersion2, logger); + return convertToSemVer(bundleVersion2, logger2); } return cliVersion2; } -async function setupCodeQLBundle(toolsInput, apiDetails, tempDir, variant, defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, features, logger) { - if (!await isBinaryAccessible("tar", logger)) { +async function setupCodeQLBundle(toolsInput, apiDetails, tempDir, variant, defaultCliVersion, rawLanguages, otherLanguagePacksReason, useOverlayAwareDefaultCliVersion, features, logger2) { + if (!await isBinaryAccessible("tar", logger2)) { throw new ConfigurationError( "Could not find tar in PATH, so unable to extract CodeQL bundle." ); } - const zstdAvailability = await isZstdAvailable(logger); + const zstdAvailability = await isZstdAvailable(logger2); const source = await getCodeQLSource( toolsInput, defaultCliVersion, rawLanguages, + otherLanguagePacksReason, useOverlayAwareDefaultCliVersion, apiDetails, variant, zstdAvailability.available, features, - logger + logger2 ); let codeqlFolder; - let toolsVersion = source.toolsVersion; let toolsDownloadStatusReport; let toolsSource; switch (source.sourceType) { @@ -152182,28 +185414,24 @@ async function setupCodeQLBundle(toolsInput, apiDetails, tempDir, variant, defau getTempExtractionDir(tempDir), source.compressionMethod, zstdAvailability.version, - logger + logger2 ); toolsSource = "LOCAL" /* Local */; break; } case "toolcache": codeqlFolder = source.codeqlFolder; - logger.debug(`CodeQL found in cache ${codeqlFolder}`); + logger2.debug(`CodeQL found in cache ${codeqlFolder}`); toolsSource = "TOOLCACHE" /* Toolcache */; break; case "download": { - const result = await downloadCodeQL( - source.codeqlURL, - source.compressionMethod, - source.bundleVersion, - source.cliVersion, + const result = await downloadCodeQLBundle( + { env: getEnv(), logger: logger2 }, + source, apiDetails, zstdAvailability.version, - tempDir, - logger + tempDir ); - toolsVersion = result.toolsVersion; codeqlFolder = result.codeqlFolder; toolsDownloadStatusReport = result.statusReport; toolsSource = "DOWNLOAD" /* Download */; @@ -152212,57 +185440,118 @@ async function setupCodeQLBundle(toolsInput, apiDetails, tempDir, variant, defau default: assertNever(source); } + exportEnvVar("CODEQL_ACTION_HAS_SET_UP_CODEQL" /* HAS_SET_UP_CODEQL */, "true"); return { codeqlFolder, toolsDownloadStatusReport, toolsSource, - toolsVersion + toolsVersion: source.toolsVersion }; } +async function downloadCodeQLBundle(action, source, apiDetails, tarVersion, tempDir) { + const { bundle } = source; + const { logger: logger2 } = action; + await tryDeleteToolcacheBundles(action); + const startTime = import_perf_hooks4.performance.now(); + try { + return await downloadCodeQL( + source, + apiDetails, + tarVersion, + tempDir, + logger2 + ); + } catch (e) { + if (bundle.kind !== "per-language" || bundle.combinedBundleURL === void 0 || asHTTPError(e)?.status !== 404) { + throw e; + } + logPerLanguageBundleFallback(action, bundle.language, bundle.url); + const result = await downloadCodeQL( + { + ...source, + bundle: { kind: "combined", url: bundle.combinedBundleURL } + }, + apiDetails, + tarVersion, + tempDir, + logger2 + ); + return { + ...result, + statusReport: { + ...result.statusReport, + totalDurationMs: durationMsSince(startTime), + perLanguage: { tools_per_language_bundle_fallback: true } + } + }; + } +} async function useZstdBundle(cliVersion2, tarSupportsZstd) { return ( // In testing, gzip performs better than zstd on Windows. - process.platform !== "win32" && tarSupportsZstd && semver9.gte(cliVersion2, CODEQL_VERSION_ZSTD_BUNDLE) + process.platform !== "win32" && tarSupportsZstd && semver10.gte(cliVersion2, CODEQL_VERSION_ZSTD_BUNDLE) ); } function getTempExtractionDir(tempDir) { return path13.join(tempDir, v4_default()); } -async function getNightlyToolsUrl(logger) { - const zstdAvailability = await isZstdAvailable(logger); +async function getLatestNightlyBundle(action, rawLanguages, otherLanguagePacksReason, variant) { + const { logger: logger2 } = action; + const zstdAvailability = await isZstdAvailable(logger2); const compressionMethod = await useZstdBundle( CODEQL_VERSION_ZSTD_BUNDLE, zstdAvailability.available ) ? "zstd" : "gzip"; + const platform2 = getBundlePlatform(); + const language = getPerLanguageBundleLanguage(action, { + rawLanguages, + otherLanguagePacksReason, + cliVersion: void 0, + compressionMethod, + platform: platform2, + variant, + isLatestNightly: true + }); try { - const release2 = await getApiClient().rest.repos.listReleases({ + const release3 = await getApiClient().rest.repos.listReleases({ owner: CODEQL_NIGHTLIES_REPOSITORY_OWNER, repo: CODEQL_NIGHTLIES_REPOSITORY_NAME, per_page: 1, page: 1, prerelease: true }); - const latestRelease = release2.data[0]; + const latestRelease = release3.data[0]; if (!latestRelease) { throw new Error("Could not find the latest nightly release."); } - return `https://github.com/${CODEQL_NIGHTLIES_REPOSITORY_OWNER}/${CODEQL_NIGHTLIES_REPOSITORY_NAME}/releases/download/${latestRelease.tag_name}/${getCodeQLBundleName(compressionMethod)}`; + const assetUrl = (name) => `https://github.com/${CODEQL_NIGHTLIES_REPOSITORY_OWNER}/${CODEQL_NIGHTLIES_REPOSITORY_NAME}/releases/download/${latestRelease.tag_name}/${name}`; + const url2 = assetUrl( + getCodeQLBundleName(compressionMethod, platform2, language) + ); + return language === void 0 ? { kind: "combined", url: url2 } : { + kind: "per-language", + url: url2, + language, + combinedBundleURL: assetUrl( + getCodeQLBundleName(compressionMethod, platform2) + ) + }; } catch (e) { throw new Error( `Failed to retrieve the latest nightly release: ${wrapError(e)}` ); } } -function getLatestToolcacheVersion(logger) { - const allVersions = toolcache3.findAllVersions("CodeQL").sort((a, b) => semver9.compare(b, a)); - logger.debug( +function getLatestToolcacheVersion(logger2) { + const allVersions = toolcache3.findAllVersions("CodeQL").sort((a, b) => semver10.compare(b, a)); + logger2.debug( `Found the following versions of the CodeQL tools in the toolcache: ${JSON.stringify( allVersions )}.` ); if (allVersions.length > 0) { const latestToolcacheVersion = allVersions[0]; - logger.info( + logger2.info( `CLI version ${latestToolcacheVersion} is the latest version in the toolcache.` ); return latestToolcacheVersion; @@ -152274,7 +185563,7 @@ function isReservedToolsValue(tools) { } // src/tracer-config.ts -var fs15 = __toESM(require("fs")); +var fs17 = __toESM(require("fs")); var path14 = __toESM(require("path")); async function shouldEnableIndirectTracing(codeql, config) { if (config.buildMode === "none" /* None */) { @@ -152285,23 +185574,23 @@ async function shouldEnableIndirectTracing(codeql, config) { } return asyncSome(config.languages, (l) => codeql.isTracedLanguage(l)); } -async function endTracingForCluster(codeql, config, logger) { +async function endTracingForCluster(codeql, config, logger2) { if (!await shouldEnableIndirectTracing(codeql, config)) return; - logger.info( + logger2.info( "Unsetting build tracing environment variables. Subsequent steps of this job will not be traced." ); const envVariablesFile = path14.resolve( config.dbLocation, "temp/tracingEnvironment/end-tracing.json" ); - if (!fs15.existsSync(envVariablesFile)) { + if (!fs17.existsSync(envVariablesFile)) { throw new Error( `Environment file for ending tracing not found: ${envVariablesFile}` ); } try { const endTracingEnvVariables = JSON.parse( - fs15.readFileSync(envVariablesFile, "utf8") + fs17.readFileSync(envVariablesFile, "utf8") ); for (const [key, value] of Object.entries(endTracingEnvVariables)) { if (value !== null) { @@ -152316,45 +185605,38 @@ async function endTracingForCluster(codeql, config, logger) { ); } } -async function getTracerConfigForCluster(config) { - const tracingEnvVariables = JSON.parse( - fs15.readFileSync( - path14.resolve( - config.dbLocation, - "temp/tracingEnvironment/start-tracing.json" - ), - "utf8" - ) +async function getTracerConfigForCluster(logger2, config) { + const filePath = path14.resolve( + config.dbLocation, + "temp/tracingEnvironment/start-tracing.json" ); - return { - env: tracingEnvVariables - }; + try { + const tracingEnvVariables = JSON.parse(fs17.readFileSync(filePath, "utf8")); + return { + env: tracingEnvVariables + }; + } catch (err) { + logger2.error( + `Failed to parse tracing environment from '${filePath}': ${getErrorMessage(err)}` + ); + throw new Error(`Failed to parse tracing environment from '${filePath}'.`); + } } -async function getCombinedTracerConfig(codeql, config) { +async function getCombinedTracerConfig(logger2, codeql, config) { if (!await shouldEnableIndirectTracing(codeql, config)) { return void 0; } - return await getTracerConfigForCluster(config); + return await getTracerConfigForCluster(logger2, config); } // src/codeql.ts var cachedCodeQL = void 0; -var CODEQL_MINIMUM_VERSION = "2.19.4"; -var CODEQL_NEXT_MINIMUM_VERSION = "2.20.7"; -var GHES_VERSION_MOST_RECENTLY_DEPRECATED = "3.16"; -var GHES_MOST_RECENT_DEPRECATION_DATE = "2026-07-01"; +var CODEQL_MINIMUM_VERSION = "2.20.7"; +var CODEQL_NEXT_MINIMUM_VERSION = "2.22.4"; +var GHES_VERSION_MOST_RECENTLY_DEPRECATED = "3.18"; +var GHES_MOST_RECENT_DEPRECATION_DATE = "2026-10-16"; var EXTRACTION_DEBUG_MODE_VERBOSITY = "progress++"; -function isDiskConfigurationError(e) { - if (!(e instanceof Error)) { - return false; - } - return ( - // out of disk space - e.message.includes("ENOSPC") || // access denied - e.message.includes("EACCES") - ); -} -async function setupCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, features, logger, checkVersion) { +async function setupCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliVersion, rawLanguages, otherLanguagePacksReason, useOverlayAwareDefaultCliVersion, features, logger2, checkVersion) { try { const { codeqlFolder, @@ -152368,9 +185650,10 @@ async function setupCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliV variant, defaultCliVersion, rawLanguages, + otherLanguagePacksReason, useOverlayAwareDefaultCliVersion, features, - logger + logger2 ); let codeqlCmd = path15.join(codeqlFolder, "codeql", "codeql"); if (process.platform === "win32") { @@ -152380,7 +185663,7 @@ async function setupCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliV `Unsupported platform: ${process.platform}` ); } - cachedCodeQL = await getCodeQLForCmd(logger, codeqlCmd, checkVersion); + cachedCodeQL = await getCodeQLForCmd(logger2, codeqlCmd, checkVersion); return { codeql: cachedCodeQL, toolsDownloadStatusReport, @@ -152397,31 +185680,40 @@ Details: ${e.stack}` : ""}` ); } } -async function getCodeQL(logger, cmd) { +async function getCodeQL(logger2, cmd) { if (cachedCodeQL === void 0) { - cachedCodeQL = await getCodeQLForCmd(logger, cmd, true); + cachedCodeQL = await getCodeQLForCmd(logger2, cmd, true); } return cachedCodeQL; } -async function getCodeQLForCmd(logger, cmd, checkVersion) { +async function getCodeQLForCmd(logger2, cmd, checkVersion, env = getEnv()) { const codeql = { getPath() { return cmd; }, async getVersion() { - let result = getCachedCodeQlVersion(logger, getEnv(), cmd); + const cacheFilePath = getCommandCacheFilePath(env); + let result = getCachedCodeQlVersion( + logger2, + cacheFilePath, + cmd + ); if (result === void 0) { result = await runCliJson( + env, cmd, ["version", "--format=json"], { noStreamStdout: true } ); - cacheCodeQlVersion(getEnv(), cmd, result); + cacheCodeQlVersion(cacheFilePath, cmd, result); } return result; }, + async isVersionAtLeast(requiredVersion) { + return semver11.gte((await this.getVersion()).version, requiredVersion); + }, async printVersion() { core12.info(JSON.stringify(await this.getVersion(), null, 2)); }, @@ -152435,7 +185727,7 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { "tools", "tracing-config.lua" ); - return fs16.existsSync(tracingConfigPath); + return fs18.existsSync(tracingConfigPath); }, async isScannedLanguage(language) { return !await this.isTracedLanguage(language); @@ -152451,7 +185743,7 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { } const codeScanningConfigFile = await writeCodeScanningConfigFile( config, - logger + logger2 ); const externalRepositoryToken = getOptionalInput( "external-repository-token" @@ -152471,7 +185763,7 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { const overlayChangesFile = await writeOverlayChangesFile( config, sourceRoot, - logger + logger2 ); extraArgs.push(`--overlay-changes=${overlayChangesFile}`); } else if (overlayDatabaseMode === "overlay-base" /* OverlayBase */) { @@ -152482,6 +185774,7 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { "--sublanguage-file-coverage" ] : ["--no-calculate-baseline"]; await runCli( + env, cmd, [ "database", @@ -152514,19 +185807,22 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { } }, async runAutobuild(config, language) { - applyAutobuildAzurePipelinesTimeoutFix(); + applyAutobuildAzurePipelinesTimeoutFix(env); const autobuildCmd = path15.join( await this.resolveExtractor(language), "tools", process.platform === "win32" ? "autobuild.cmd" : "autobuild.sh" ); if (config.debugMode) { - process.env["CODEQL_VERBOSITY" /* CLI_VERBOSITY */] = process.env["CODEQL_VERBOSITY" /* CLI_VERBOSITY */] || EXTRACTION_DEBUG_MODE_VERBOSITY; + env.set( + "CODEQL_VERBOSITY" /* CLI_VERBOSITY */, + env.getOptional("CODEQL_VERBOSITY" /* CLI_VERBOSITY */) ?? EXTRACTION_DEBUG_MODE_VERBOSITY + ); } - await runCli(autobuildCmd); + await runCli(env, autobuildCmd); }, async extractScannedLanguage(config, language) { - await runCli(cmd, [ + await runCli(env, cmd, [ "database", "trace-command", "--index-traceless-dbs", @@ -152538,10 +185834,10 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { }, async extractUsingBuildMode(config, language) { if (config.buildMode === "autobuild" /* Autobuild */) { - applyAutobuildAzurePipelinesTimeoutFix(); + applyAutobuildAzurePipelinesTimeoutFix(env); } try { - await runCli(cmd, [ + await runCli(env, cmd, [ "database", "trace-command", "--use-build-mode", @@ -152572,12 +185868,12 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { ...getExtraOptionsFromEnv(["database", "finalize"]), databasePath ]; - await runCli(cmd, args); + await runCli(env, cmd, args); }, async resolveLanguages({ filterToLanguagesWithQueries } = { filterToLanguagesWithQueries: false }) { - return runCliJson(cmd, [ + return runCliJson(env, cmd, [ "resolve", "languages", "--format=betterjson", @@ -152601,7 +185897,11 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { if (workingDir !== void 0) { codeqlArgs.push("--working-dir", workingDir); } - return await runCliJson(cmd, codeqlArgs); + return await runCliJson( + env, + cmd, + codeqlArgs + ); }, async databaseRunQueries(databasePath, flags, queries = []) { const codeqlArgs = [ @@ -152617,7 +185917,7 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { ignoringOptions: ["--expect-discarded-cache"] }) ]; - await runCli(cmd, codeqlArgs); + await runCli(env, cmd, codeqlArgs); }, async databaseInterpretResults(databasePath, querySuitePaths, sarifFile, threadsFlag, verbosityFlag, sarifRunPropertyFlag, automationDetailsId, config, features) { const shouldExportDiagnostics = await features.getValue( @@ -152640,7 +185940,7 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { "--sarif-group-rules-by-pack", "--sarif-include-query-help=always", "--sublanguage-file-coverage", - ...await getJobRunUuidSarifOptions(), + ...await getJobRunUuidSarifOptions(env), ...getExtraOptionsFromEnv(["database", "interpret-results"]) ]; if (sarifRunPropertyFlag !== void 0) { @@ -152658,7 +185958,7 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { if (querySuitePaths) { codeqlArgs.push(...querySuitePaths); } - return await runCli(cmd, codeqlArgs, { + return await runCli(env, cmd, codeqlArgs, { noStreamStdout: true }); }, @@ -152672,7 +185972,7 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { `--cache-cleanup=${cleanupLevel}`, ...getExtraOptionsFromEnv(["database", "cleanup"]) ]; - await runCli(cmd, codeqlArgs); + await runCli(env, cmd, codeqlArgs); } }, async databaseBundle(databasePath, outputFilePath, databaseName, includeDiagnostics, alsoIncludeRelativePaths) { @@ -152696,7 +185996,9 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { ]) ); } - await new toolrunner3.ToolRunner(cmd, args).exec(); + await new toolrunner4.ToolRunner(cmd, args, { + env: env.getDefined() + }).exec(); }, async databaseExportDiagnostics(databasePath, sarifFile, automationDetailsId) { const args = [ @@ -152715,27 +186017,42 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { if (automationDetailsId !== void 0) { args.push("--sarif-category", automationDetailsId); } - await new toolrunner3.ToolRunner(cmd, args).exec(); + await new toolrunner4.ToolRunner(cmd, args, { + env: env.getDefined() + }).exec(); }, - async diagnosticsExport(sarifFile, automationDetailsId, config) { + async diagnosticsExport(sarifFile, automationDetailsId, config, diagnosticDir) { + let configPath = getGeneratedCodeScanningConfigPath(config); + if (!fs18.existsSync(configPath)) { + if (config.successfullyInitialised) { + logger2.warning( + [ + `Expected a configuration file at '${configPath}', which does not exist.`, + "Continuing with diagnostics export anyway, without a configuration file." + ].join(" ") + ); + } + configPath = void 0; + } const args = [ "diagnostics", "export", "--format=sarif-latest", `--output=${sarifFile}`, - `--sarif-codescanning-config=${getGeneratedCodeScanningConfigPath( - config - )}`, + ...configPath !== void 0 ? [`--sarif-codescanning-config=${configPath}`] : [], + ...diagnosticDir !== void 0 ? [`--diagnostic-dir=${diagnosticDir}`] : [], ...getExtraOptionsFromEnv(["diagnostics", "export"]) ]; if (automationDetailsId !== void 0) { args.push("--sarif-category", automationDetailsId); } - await new toolrunner3.ToolRunner(cmd, args).exec(); + await new toolrunner4.ToolRunner(cmd, args, { + env: env.getDefined() + }).exec(); }, async resolveExtractor(language) { let extractorPath = ""; - await new toolrunner3.ToolRunner( + await new toolrunner4.ToolRunner( cmd, [ "resolve", @@ -152743,9 +186060,11 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { "--format=json", `--language=${language}`, "--extractor-include-aliases", + "-J-XX:-UsePerfData", ...getExtraOptionsFromEnv(["resolve", "extractor"]) ], { + env: env.getDefined(), silent: true, listeners: { stdout: (data) => { @@ -152757,7 +186076,14 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { } } ).exec(); - return JSON.parse(extractorPath); + try { + return JSON.parse(extractorPath); + } catch (err) { + throw new Error( + `Failed to parse extractor path for '${language}' from CLI: ${getErrorMessage(err)} +Output was: ${extractorPath}` + ); + } }, async resolveQueriesStartingPacks(queries) { const codeqlArgs = [ @@ -152767,7 +186093,7 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { ...getExtraOptionsFromEnv(["resolve", "queries"]), ...queries ]; - return await runCliJson(cmd, codeqlArgs, { + return await runCliJson(env, cmd, codeqlArgs, { noStreamStdout: true }); }, @@ -152779,7 +186105,7 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { "--format=json", ...getExtraOptionsFromEnv(["resolve", "database"]) ]; - return await runCliJson(cmd, codeqlArgs, { + return await runCliJson(env, cmd, codeqlArgs, { noStreamStdout: true }); }, @@ -152799,21 +186125,21 @@ async function getCodeQLForCmd(logger, cmd, checkVersion) { if (mergeRunsFromEqualCategory) { args.push("--sarif-merge-runs-from-equal-category"); } - await runCli(cmd, args); + await runCli(env, cmd, args); } }; - if (checkVersion && !await codeQlVersionAtLeast(codeql, CODEQL_MINIMUM_VERSION)) { + if (checkVersion && !await codeql.isVersionAtLeast(CODEQL_MINIMUM_VERSION)) { throw new ConfigurationError( `Expected a CodeQL CLI with version at least ${CODEQL_MINIMUM_VERSION} but got version ${(await codeql.getVersion()).version}` ); - } else if (checkVersion && process.env["CODEQL_ACTION_SUPPRESS_DEPRECATED_SOON_WARNING" /* SUPPRESS_DEPRECATED_SOON_WARNING */] !== "true" && !await codeQlVersionAtLeast(codeql, CODEQL_NEXT_MINIMUM_VERSION)) { + } else if (checkVersion && env.getOptional("CODEQL_ACTION_SUPPRESS_DEPRECATED_SOON_WARNING" /* SUPPRESS_DEPRECATED_SOON_WARNING */) !== "true" && !await codeql.isVersionAtLeast(CODEQL_NEXT_MINIMUM_VERSION)) { const result = await codeql.getVersion(); core12.warning( `CodeQL CLI version ${result.version} was discontinued on ${GHES_MOST_RECENT_DEPRECATION_DATE} alongside GitHub Enterprise Server ${GHES_VERSION_MOST_RECENTLY_DEPRECATED} and will not be supported by the next minor release of the CodeQL Action. Please update to CodeQL CLI version ${CODEQL_NEXT_MINIMUM_VERSION} or later. For instance, if you have specified a custom version of the CLI using the 'tools' input to the 'init' Action, you can remove this input to use the default version. Alternatively, if you want to continue using CodeQL CLI version ${result.version}, you can replace 'github/codeql-action/*@v${getActionVersion().split(".")[0]}' by 'github/codeql-action/*@v${getActionVersion()}' in your code scanning workflow to continue using this version of the CodeQL Action.` ); - core12.exportVariable("CODEQL_ACTION_SUPPRESS_DEPRECATED_SOON_WARNING" /* SUPPRESS_DEPRECATED_SOON_WARNING */, "true"); + env.export("CODEQL_ACTION_SUPPRESS_DEPRECATED_SOON_WARNING" /* SUPPRESS_DEPRECATED_SOON_WARNING */, "true"); } return codeql; } @@ -152853,9 +186179,9 @@ function getExtraOptions(options, paths, pathInfo) { ); return all.concat(specific); } -async function runCli(cmd, args = [], opts = {}) { +async function runCli(env, cmd, args = [], opts = {}) { try { - return await runTool(cmd, args, opts); + return await runTool(env, cmd, args, opts); } catch (e) { if (e instanceof CommandInvocationError) { throw wrapCliConfigurationError(new CliError(e)); @@ -152863,8 +186189,8 @@ async function runCli(cmd, args = [], opts = {}) { throw e; } } -async function runCliJson(cmd, args = [], opts = {}) { - const output = await runCli(cmd, args, opts); +async function runCliJson(env, cmd, args = [], opts = {}) { + const output = await runCli(env, cmd, args, opts); try { return JSON.parse(output); } catch (e) { @@ -152873,19 +186199,19 @@ async function runCliJson(cmd, args = [], opts = {}) { ); } } -async function writeCodeScanningConfigFile(config, logger) { +async function writeCodeScanningConfigFile(config, logger2) { const codeScanningConfigFile = getGeneratedCodeScanningConfigPath(config); const augmentedConfig = appendExtraQueryExclusions( config.extraQueryExclusions, config.computedConfig ); - logger.info( + logger2.info( `Writing augmented user configuration file to ${codeScanningConfigFile}` ); - logger.startGroup("Augmented user configuration file contents"); - logger.info(dump(augmentedConfig)); - logger.endGroup(); - fs16.writeFileSync(codeScanningConfigFile, dump(augmentedConfig)); + logger2.startGroup("Augmented user configuration file contents"); + logger2.info(dump(augmentedConfig)); + logger2.endGroup(); + fs18.writeFileSync(codeScanningConfigFile, dump(augmentedConfig)); return codeScanningConfigFile; } var TRAP_CACHE_SIZE_MB = 1024; @@ -152900,7 +186226,7 @@ async function getTrapCachingExtractorConfigArgs(config) { async function getTrapCachingExtractorConfigArgsForLang(config, language) { const cacheDir2 = config.trapCaches[language]; if (cacheDir2 === void 0) return []; - const write = await isAnalyzingDefaultBranch(); + const write = await isAnalyzingDefaultBranch(getEnv(), config.repositoryRoot); return [ `-O=${language}.trap.cache.dir=${cacheDir2}`, `-O=${language}.trap.cache.bound=${TRAP_CACHE_SIZE_MB}`, @@ -152913,23 +186239,26 @@ function getGeneratedCodeScanningConfigPath(config) { function getExtractionVerbosityArguments(enableDebugLogging) { return enableDebugLogging ? [`--verbosity=${EXTRACTION_DEBUG_MODE_VERBOSITY}`] : []; } -function applyAutobuildAzurePipelinesTimeoutFix() { - const javaToolOptions = process.env["JAVA_TOOL_OPTIONS"] || ""; - process.env["JAVA_TOOL_OPTIONS"] = [ - ...javaToolOptions.split(/\s+/), - "-Dhttp.keepAlive=false", - "-Dmaven.wagon.http.pool=false" - ].join(" "); +function applyAutobuildAzurePipelinesTimeoutFix(env) { + const javaToolOptions = env.getOptional("JAVA_TOOL_OPTIONS") ?? ""; + env.set( + "JAVA_TOOL_OPTIONS", + [ + ...javaToolOptions.split(/\s+/), + "-Dhttp.keepAlive=false", + "-Dmaven.wagon.http.pool=false" + ].join(" ") + ); } -async function getJobRunUuidSarifOptions() { - const jobRunUuid = process.env["CODEQL_ACTION_JOB_RUN_UUID" /* JOB_RUN_UUID */]; +async function getJobRunUuidSarifOptions(env) { + const jobRunUuid = env.getOptional("CODEQL_ACTION_JOB_RUN_UUID" /* JOB_RUN_UUID */); return jobRunUuid ? [`--sarif-run-property=jobRunUuid=${jobRunUuid}`] : []; } // src/autobuild.ts -async function determineAutobuildLanguages(codeql, config, logger) { +async function determineAutobuildLanguages(codeql, config, logger2) { if (config.buildMode === "none" /* None */ || config.buildMode === "manual" /* Manual */) { - logger.info( + logger2.info( `Using build mode "${config.buildMode}", nothing to autobuild. See ${"https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages#codeql-build-modes" /* CODEQL_BUILD_MODES */} for more information.` ); return void 0; @@ -152939,7 +186268,7 @@ async function determineAutobuildLanguages(codeql, config, logger) { async (language) => await codeql.isTracedLanguage(language) ); if (autobuildLanguages.length === 0) { - logger.info( + logger2.info( "None of the languages in this project require extra build steps" ); return void 0; @@ -152954,9 +186283,9 @@ async function determineAutobuildLanguages(codeql, config, logger) { if (autobuildLanguages.length !== autobuildLanguagesWithoutGo.length) { languages.push("go" /* go */); } - logger.debug(`Will autobuild ${languages.join(" and ")}.`); + logger2.debug(`Will autobuild ${languages.join(" and ")}.`); if (autobuildLanguagesWithoutGo.length > 1) { - logger.warning( + logger2.warning( `We will only automatically build ${languages.join( " and " )} code. If you wish to scan ${autobuildLanguagesWithoutGo.slice(1).join( @@ -152966,7 +186295,7 @@ async function determineAutobuildLanguages(codeql, config, logger) { } return languages; } -async function setupCppAutobuild(codeql, logger) { +async function setupCppAutobuild(logger2) { const envVar = featureConfig["cpp_dependency_installation_enabled" /* CppDependencyInstallation */].envVar; const featureName = "C++ automatic installation of dependencies"; const gitHubVersion = await getGitHubVersion(); @@ -152975,30 +186304,30 @@ async function setupCppAutobuild(codeql, logger) { gitHubVersion, repositoryNwo, getTemporaryDirectory(), - logger + logger2 ); - if (await features.getValue("cpp_dependency_installation_enabled" /* CppDependencyInstallation */, codeql)) { + if (await features.getValue("cpp_dependency_installation_enabled" /* CppDependencyInstallation */)) { if (process.env["RUNNER_ENVIRONMENT" /* RUNNER_ENVIRONMENT */] === "self-hosted" && process.env[envVar] !== "true") { - logger.info( + logger2.info( `Disabling ${featureName} as we are on a self-hosted runner.${getWorkflowEventName() !== "dynamic" ? ` To override this, set the ${envVar} environment variable to 'true' in your workflow. See ${"https://docs.github.com/en/actions/learn-github-actions/variables#defining-environment-variables-for-a-single-workflow" /* DEFINE_ENV_VARIABLES */} for more information.` : ""}` ); - core13.exportVariable(envVar, "false"); + exportEnvVar(envVar, "false"); } else { - logger.info( + logger2.info( `Enabling ${featureName}. This can be disabled by setting the ${envVar} environment variable to 'false'. See ${"https://docs.github.com/en/actions/learn-github-actions/variables#defining-environment-variables-for-a-single-workflow" /* DEFINE_ENV_VARIABLES */} for more information.` ); - core13.exportVariable(envVar, "true"); + exportEnvVar(envVar, "true"); } } else { - logger.info(`Disabling ${featureName}.`); - core13.exportVariable(envVar, "false"); + logger2.info(`Disabling ${featureName}.`); + exportEnvVar(envVar, "false"); } } -async function runAutobuild(config, language, logger) { - logger.startGroup(`Attempting to automatically build ${language} code`); - const codeQL = await getCodeQL(logger, config.codeQLCmd); +async function runAutobuild(config, language, logger2) { + logger2.startGroup(`Attempting to automatically build ${language} code`); + const codeQL = await getCodeQL(logger2, config.codeQLCmd); if (language === "cpp" /* cpp */) { - await setupCppAutobuild(codeQL, logger); + await setupCppAutobuild(logger2); } if (config.buildMode) { await codeQL.extractUsingBuildMode(config, language); @@ -153006,15 +186335,15 @@ async function runAutobuild(config, language, logger) { await codeQL.runAutobuild(config, language); } if (language === "go" /* go */) { - core13.exportVariable("CODEQL_ACTION_DID_AUTOBUILD_GOLANG" /* DID_AUTOBUILD_GOLANG */, "true"); + exportEnvVar("CODEQL_ACTION_DID_AUTOBUILD_GOLANG" /* DID_AUTOBUILD_GOLANG */, "true"); } - logger.endGroup(); + logger2.endGroup(); } // src/dependency-caching.ts -var os5 = __toESM(require("os")); +var os6 = __toESM(require("os")); var import_path3 = require("path"); -var actionsCache4 = __toESM(require_cache4()); +var actionsCache4 = __toESM(require_cache6()); var glob = __toESM(require_glob()); var CODEQL_DEPENDENCY_CACHE_PREFIX = "codeql-dependencies"; var CODEQL_DEPENDENCY_CACHE_VERSION = 1; @@ -153024,9 +186353,9 @@ function getJavaTempDependencyDir() { async function getJavaDependencyDirs() { return [ // Maven - (0, import_path3.join)(os5.homedir(), ".m2", "repository"), + (0, import_path3.join)(os6.homedir(), ".m2", "repository"), // Gradle - (0, import_path3.join)(os5.homedir(), ".gradle", "caches"), + (0, import_path3.join)(os6.homedir(), ".gradle", "caches"), // CodeQL Java build-mode: none getJavaTempDependencyDir() ]; @@ -153037,7 +186366,7 @@ function getCsharpTempDependencyDir() { async function getCsharpDependencyDirs(codeql, features) { const dirs = [ // Nuget - (0, import_path3.join)(os5.homedir(), ".nuget", "packages") + (0, import_path3.join)(os6.homedir(), ".nuget", "packages") ]; if (await features.getValue("csharp_cache_bmn" /* CsharpCacheBuildModeNone */, codeql)) { dirs.push(getCsharpTempDependencyDir()); @@ -153092,29 +186421,29 @@ var defaultCacheConfigs = { getHashPatterns: getCsharpHashPatterns }, go: { - getDependencyPaths: async () => [(0, import_path3.join)(os5.homedir(), "go", "pkg", "mod")], + getDependencyPaths: async () => [(0, import_path3.join)(os6.homedir(), "go", "pkg", "mod")], getHashPatterns: async () => internal.makePatternCheck(["**/go.sum"]) } }; async function makeGlobber(patterns) { return glob.create(patterns.join("\n")); } -async function checkHashPatterns(codeql, features, language, cacheConfig, checkType, logger) { +async function checkHashPatterns(codeql, features, language, cacheConfig, checkType, logger2) { const patterns = await cacheConfig.getHashPatterns(codeql, features); if (patterns === void 0) { - logger.info( + logger2.info( `Skipping ${checkType} of dependency cache for ${language} as we cannot calculate a hash for the cache key.` ); } return patterns; } -async function downloadDependencyCaches(codeql, features, languages, logger) { +async function downloadDependencyCaches(codeql, features, languages, logger2) { const status = []; const restoredKeys = []; for (const language of languages) { const cacheConfig = defaultCacheConfigs[language]; if (cacheConfig === void 0) { - logger.info( + logger2.info( `Skipping download of dependency cache for ${language} as we have no caching configuration for it.` ); continue; @@ -153125,7 +186454,7 @@ async function downloadDependencyCaches(codeql, features, languages, logger) { language, cacheConfig, "download", - logger + logger2 ); if (patterns === void 0) { status.push({ language, hit_kind: "no-hash" /* NoHash */ }); @@ -153133,9 +186462,10 @@ async function downloadDependencyCaches(codeql, features, languages, logger) { } const primaryKey = await cacheKey2(codeql, features, language, patterns); const restoreKeys = [ + primaryKey, await cachePrefix2(codeql, features, language) ]; - logger.info( + logger2.info( `Downloading cache for ${language} with key ${primaryKey} and restore keys ${restoreKeys.join( ", " )}` @@ -153148,7 +186478,7 @@ async function downloadDependencyCaches(codeql, features, languages, logger) { ); const download_duration_ms = Math.round(performance.now() - start); if (hitKey !== void 0) { - logger.info(`Cache hit on key ${hitKey} for ${language}.`); + logger2.info(`Cache hit on key ${hitKey} for ${language}.`); let hit_kind = "partial" /* Partial */; if (hitKey === primaryKey) { hit_kind = "exact" /* Exact */; @@ -153161,17 +186491,17 @@ async function downloadDependencyCaches(codeql, features, languages, logger) { restoredKeys.push(hitKey); } else { status.push({ language, hit_kind: "miss" /* Miss */ }); - logger.info(`No suitable cache found for ${language}.`); + logger2.info(`No suitable cache found for ${language}.`); } } return { statusReport: status, restoredKeys }; } -async function uploadDependencyCaches(codeql, features, config, logger) { +async function uploadDependencyCaches(codeql, features, config, logger2) { const status = []; for (const language of config.languages) { const cacheConfig = defaultCacheConfigs[language]; if (cacheConfig === void 0) { - logger.info( + logger2.info( `Skipping upload of dependency cache for ${language} as we have no caching configuration for it.` ); continue; @@ -153182,7 +186512,7 @@ async function uploadDependencyCaches(codeql, features, config, logger) { language, cacheConfig, "upload", - logger + logger2 ); if (patterns === void 0) { status.push({ language, result: "no-hash" /* NoHash */ }); @@ -153195,17 +186525,17 @@ async function uploadDependencyCaches(codeql, features, config, logger) { } const size = await getTotalCacheSize( await cacheConfig.getDependencyPaths(codeql, features), - logger, + logger2, true ); if (size === 0) { status.push({ language, result: "empty" /* Empty */ }); - logger.info( + logger2.info( `Skipping upload of dependency cache for ${language} since it is empty.` ); continue; } - logger.info( + logger2.info( `Uploading cache of size ${size} for ${language} with key ${key}...` ); try { @@ -153223,10 +186553,10 @@ async function uploadDependencyCaches(codeql, features, config, logger) { }); } catch (error3) { if (error3 instanceof actionsCache4.ReserveCacheError) { - logger.info( + logger2.info( `Not uploading cache for ${language}, because ${key} is already in use.` ); - logger.debug(error3.message); + logger2.debug(error3.message); status.push({ language, result: "duplicate" /* Duplicate */ }); } else { throw error3; @@ -153265,7 +186595,7 @@ async function cachePrefix2(codeql, features, language) { const featurePrefix = await getFeaturePrefix(codeql, features, language); return `${prefix}-${featurePrefix}${CODEQL_DEPENDENCY_CACHE_VERSION}-${runnerOs}-${language}-`; } -async function getDependencyCacheUsage(logger) { +async function getDependencyCacheUsage(logger2) { try { const caches = await listActionsCaches(CODEQL_DEPENDENCY_CACHE_PREFIX); const totalSize = caches.reduce( @@ -153274,7 +186604,7 @@ async function getDependencyCacheUsage(logger) { ); return { count: caches.length, size_bytes: totalSize }; } catch (err) { - logger.warning( + logger2.warning( `Unable to retrieve information about dependency cache usage: ${getErrorMessage(err)}` ); } @@ -153297,32 +186627,64 @@ var CodeQLAnalysisError = class extends Error { message; error; }; -async function setupPythonExtractor(logger) { +async function determineCheckoutPath(action, config) { + const checkoutPathInput = action.actions.getRequiredInput("checkout_path"); + const absCheckoutPathInput = path16.resolve(checkoutPathInput); + const repositoryRoot = await getGitRoot(absCheckoutPathInput); + if (repositoryRoot === void 0) { + action.logger.warning( + [ + `The directory at '${absCheckoutPathInput}' is not in the work tree of a git repository.`, + "If the repository being analyzed is checked out elsewhere,", + "you must explicitly set the 'checkout_path' input for the 'codeql-action/analyze' step to", + "the checkout path." + ].join(" ") + ); + } else if (repositoryRoot !== absCheckoutPathInput) { + action.logger.warning( + [ + `The directory at '${absCheckoutPathInput}' is not the root of the repository ('${repositoryRoot}').`, + "Set the 'checkout_path' input for the 'codeql-action/analyze' step to the root path of the checkout." + ].join(" ") + ); + } else if (config.repositoryRoot !== void 0 && repositoryRoot !== config.repositoryRoot) { + action.logger.warning( + [ + `The repository path at '${repositoryRoot}' does not match that found by the 'codeql-action/init' step: '${config.repositoryRoot}'.`, + "Ensure that the 'checkout_path' input for the 'codeql-action/analyze' step is set to the path of the same repository that", + "the 'codeql-action/init' step determined. This is either the GitHub Actions workspace or the repository root corresponding to", + "the 'source-root' input if that was provided." + ].join(" ") + ); + } + return absCheckoutPathInput; +} +async function setupPythonExtractor(logger2) { const codeqlPython = process.env["CODEQL_PYTHON"]; if (codeqlPython === void 0 || codeqlPython.length === 0) { return; } - logger.warning( + logger2.warning( "The CODEQL_PYTHON environment variable is no longer supported. Please remove it from your workflow. This environment variable was originally used to specify a Python executable that included the dependencies of your Python code, however Python analysis no longer uses these dependencies.\nIf you used CODEQL_PYTHON to force the version of Python to analyze as, please use CODEQL_EXTRACTOR_PYTHON_ANALYSIS_VERSION instead, such as 'CODEQL_EXTRACTOR_PYTHON_ANALYSIS_VERSION=2.7' or 'CODEQL_EXTRACTOR_PYTHON_ANALYSIS_VERSION=3.11'." ); return; } -async function runExtraction(codeql, features, config, logger) { +async function runExtraction(codeql, features, config, logger2) { for (const language of config.languages) { - if (dbIsFinalized(config, language, logger)) { - logger.debug( + if (dbIsFinalized(config, language, logger2)) { + logger2.debug( `Database for ${language} has already been finalized, skipping extraction.` ); continue; } if (await shouldExtractLanguage(codeql, config, language)) { - logger.startGroup(`Extracting ${language}`); + logger2.startGroup(`Extracting ${language}`); if (language === "python" /* python */) { - await setupPythonExtractor(logger); + await setupPythonExtractor(logger2); } if (config.buildMode) { if (language === "cpp" /* cpp */ && config.buildMode === "autobuild" /* Autobuild */) { - await setupCppAutobuild(codeql, logger); + await setupCppAutobuild(logger2); } if (language === "java" /* java */ && config.buildMode === "none" /* None */) { process.env["CODEQL_EXTRACTOR_JAVA_OPTION_BUILDLESS_DEPENDENCY_DIR"] = getJavaTempDependencyDir(); @@ -153334,72 +186696,71 @@ async function runExtraction(codeql, features, config, logger) { } else { await codeql.extractScannedLanguage(config, language); } - logger.endGroup(); + logger2.endGroup(); } } } async function shouldExtractLanguage(codeql, config, language) { return config.buildMode === "none" /* None */ || config.buildMode === "autobuild" /* Autobuild */ && process.env["CODEQL_ACTION_AUTOBUILD_DID_COMPLETE_SUCCESSFULLY" /* AUTOBUILD_DID_COMPLETE_SUCCESSFULLY */] !== "true" || !config.buildMode && await codeql.isScannedLanguage(language); } -function dbIsFinalized(config, language, logger) { +function dbIsFinalized(config, language, logger2) { const dbPath = getCodeQLDatabasePath(config, language); try { const dbInfo = load( - fs17.readFileSync(path16.resolve(dbPath, "codeql-database.yml"), "utf8") + fs19.readFileSync(path16.resolve(dbPath, "codeql-database.yml"), "utf8") ); return !("inProgress" in dbInfo); } catch { - logger.warning( + logger2.warning( `Could not check whether database for ${language} was finalized. Assuming it is not.` ); return false; } } -async function finalizeDatabaseCreation(codeql, features, config, threadsFlag, memoryFlag, logger) { - const extractionStart = import_perf_hooks3.performance.now(); - await runExtraction(codeql, features, config, logger); - const extractionTime = import_perf_hooks3.performance.now() - extractionStart; - const trapImportStart = import_perf_hooks3.performance.now(); +async function finalizeDatabaseCreation(codeql, features, config, threadsFlag, memoryFlag, logger2) { + const extractionStart = import_perf_hooks5.performance.now(); + await runExtraction(codeql, features, config, logger2); + const extractionTime = import_perf_hooks5.performance.now() - extractionStart; + const trapImportStart = import_perf_hooks5.performance.now(); for (const language of config.languages) { - if (dbIsFinalized(config, language, logger)) { - logger.info( + if (dbIsFinalized(config, language, logger2)) { + logger2.info( `There is already a finalized database for ${language} at the location where the CodeQL Action places databases, so we did not create one.` ); } else { - logger.startGroup(`Finalizing ${language}`); + logger2.startGroup(`Finalizing ${language}`); await codeql.finalizeDatabase( getCodeQLDatabasePath(config, language), threadsFlag, memoryFlag, config.debugMode ); - logger.endGroup(); + logger2.endGroup(); } } - const trapImportTime = import_perf_hooks3.performance.now() - trapImportStart; + const trapImportTime = import_perf_hooks5.performance.now() - trapImportStart; return { scanned_language_extraction_duration_ms: Math.round(extractionTime), trap_import_duration_ms: Math.round(trapImportTime) }; } -async function setupDiffInformedQueryRun(logger) { +async function setupDiffInformedQueryRun(logger2, checkoutPath) { return await withGroupAsync( "Generating diff range extension pack", async () => { - const diffRanges = readDiffRangesJsonFile(logger); + const diffRanges = readDiffRangesJsonFile(logger2); if (diffRanges === void 0) { - logger.info( + logger2.info( "No precomputed diff ranges found; skipping diff-informed analysis stage." ); return void 0; } - const checkoutPath = getRequiredInput("checkout_path"); const packDir = writeDiffRangeDataExtensionPack( - logger, + logger2, diffRanges, checkoutPath ); - logger.info( + logger2.info( `Successfully created diff range extension pack at ${packDir}.` ); return packDir; @@ -153407,8 +186768,7 @@ async function setupDiffInformedQueryRun(logger) { ); } function diffRangeExtensionPackContents(ranges, checkoutPath) { - const header = ` -extensions: + const header = `extensions: - addsTo: pack: codeql/util extensible: restrictAlertsTo @@ -153417,7 +186777,7 @@ extensions: `; let data = ranges.map((range2) => { const filename = path16.join(checkoutPath, range2.path).replaceAll(path16.sep, "/"); - return ` - [${dump(filename, { forceQuotes: true, quoteStyle: "single" }).trim()}, ${range2.startLine}, ${range2.endLine}] + return ` - [${dump(filename, { forceQuotes: true, quoteStyle: "double" }).trim()}, ${range2.startLine}, ${range2.endLine}] `; }).join(""); if (!data) { @@ -153425,13 +186785,13 @@ extensions: } return header + data; } -function writeDiffRangeDataExtensionPack(logger, ranges, checkoutPath) { +function writeDiffRangeDataExtensionPack(logger2, ranges, checkoutPath) { if (ranges.length === 0) { ranges = [{ path: "", startLine: 0, endLine: 0 }]; } const diffRangeDir = path16.join(getTemporaryDirectory(), "pr-diff-range"); - fs17.mkdirSync(diffRangeDir, { recursive: true }); - fs17.writeFileSync( + fs19.mkdirSync(diffRangeDir, { recursive: true }); + fs19.writeFileSync( path16.join(diffRangeDir, "qlpack.yml"), ` name: codeql-action/pr-diff-range @@ -153448,20 +186808,13 @@ dataExtensions: checkoutPath ); const extensionFilePath = path16.join(diffRangeDir, "pr-diff-range.yml"); - fs17.writeFileSync(extensionFilePath, extensionContents); - logger.debug( + fs19.writeFileSync(extensionFilePath, extensionContents); + logger2.debug( `Wrote pr-diff-range extension pack to ${extensionFilePath}: ${extensionContents}` ); return diffRangeDir; } -var defaultSuites = /* @__PURE__ */ new Set([ - "security-experimental", - "security-extended", - "security-and-quality", - "code-quality", - "code-scanning" -]); function resolveQuerySuiteAlias(language, maybeSuite) { if (defaultSuites.has(maybeSuite)) { return `${language}-${maybeSuite}.qls`; @@ -153471,7 +186824,7 @@ function resolveQuerySuiteAlias(language, maybeSuite) { function addSarifExtension(analysis, base) { return `${base}${analysis.sarifExtension}`; } -async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir, automationDetailsId, codeql, config, logger, features) { +async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir, automationDetailsId, codeql, config, logger2, features) { const statusReport = {}; const queryFlags = [memoryFlag, threadsFlag]; const incrementalMode = []; @@ -153502,11 +186855,11 @@ async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir } } } - logger.startGroup(`Running queries for ${language}`); + logger2.startGroup(`Running queries for ${language}`); const startTimeRunQueries = (/* @__PURE__ */ new Date()).getTime(); const databasePath = getCodeQLDatabasePath(config, language); await codeql.databaseRunQueries(databasePath, queryFlags, queries); - logger.debug(`Finished running queries for ${language}.`); + logger2.debug(`Finished running queries for ${language}.`); statusReport[`analyze_builtin_queries_${language}_duration_ms`] = (/* @__PURE__ */ new Date()).getTime() - startTimeRunQueries; const startTimeInterpretResults = /* @__PURE__ */ new Date(); const { summary: analysisSummary, sarifFile } = await runInterpretResultsFor( @@ -153529,15 +186882,15 @@ async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir } const endTimeInterpretResults = /* @__PURE__ */ new Date(); statusReport[`interpret_results_${language}_duration_ms`] = endTimeInterpretResults.getTime() - startTimeInterpretResults.getTime(); - logger.endGroup(); + logger2.endGroup(); if (analysisSummary.trim()) { - logger.info(analysisSummary); + logger2.info(analysisSummary); } if (qualityAnalysisSummary?.trim()) { - logger.info(qualityAnalysisSummary); + logger2.info(qualityAnalysisSummary); } if (!config.enableFileCoverageInformation) { - logger.info( + logger2.info( "To speed up pull request analysis, file coverage information is only enabled when analyzing the default branch and protected branches." ); } @@ -153569,8 +186922,8 @@ async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir } return statusReport; async function runInterpretResultsFor(analysis, language, queries, enableDebugLogging) { - logger.info(`Interpreting ${analysis.name} results for ${language}`); - const category = analysis.fixCategory(logger, automationDetailsId); + logger2.info(`Interpreting ${analysis.name} results for ${language}`); + const category = analysis.fixCategory(logger2, automationDetailsId); const sarifFile = path16.join( sarifFolder, addSarifExtension(analysis, language) @@ -153600,7 +186953,7 @@ async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir } function getPerQueryAlertCounts(sarifPath) { const sarifObject = JSON.parse( - fs17.readFileSync(sarifPath, "utf8") + fs19.readFileSync(sarifPath, "utf8") ); const perQueryAlertCounts = {}; for (const sarifRun of sarifObject.runs) { @@ -153616,34 +186969,34 @@ async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir return perQueryAlertCounts; } } -async function runFinalize(features, outputDir, threadsFlag, memoryFlag, codeql, config, logger) { +async function runFinalize(features, outputDir, threadsFlag, memoryFlag, codeql, config, logger2) { try { - await fs17.promises.rm(outputDir, { force: true, recursive: true }); + await fs19.promises.rm(outputDir, { force: true, recursive: true }); } catch (error3) { if (error3?.code !== "ENOENT") { throw error3; } } - await fs17.promises.mkdir(outputDir, { recursive: true }); + await fs19.promises.mkdir(outputDir, { recursive: true }); const timings = await finalizeDatabaseCreation( codeql, features, config, threadsFlag, memoryFlag, - logger + logger2 ); if (process.env["CODEQL_ACTION_AUTOBUILD_DID_COMPLETE_SUCCESSFULLY" /* AUTOBUILD_DID_COMPLETE_SUCCESSFULLY */] !== "true") { - await endTracingForCluster(codeql, config, logger); + await endTracingForCluster(codeql, config, logger2); } return timings; } -async function warnIfGoInstalledAfterInit(config, logger) { +async function warnIfGoInstalledAfterInit(config, logger2) { const goInitPath = process.env["CODEQL_ACTION_GO_BINARY" /* GO_BINARY_LOCATION */]; if (process.env["CODEQL_ACTION_DID_AUTOBUILD_GOLANG" /* DID_AUTOBUILD_GOLANG */] !== "true" && goInitPath !== void 0) { - const goBinaryPath = await io5.which("go", true); + const goBinaryPath = await io6.which("go", true); if (goInitPath !== goBinaryPath) { - logger.warning( + logger2.warning( `Expected \`which go\` to return ${goInitPath}, but got ${goBinaryPath}: please ensure that the correct version of Go is installed before the \`codeql-action/init\` Action is used.` ); addDiagnostic( @@ -153668,31 +187021,32 @@ async function warnIfGoInstalledAfterInit(config, logger) { } // src/database-upload.ts -var fs18 = __toESM(require("fs")); -async function cleanupAndUploadDatabases(repositoryNwo, codeql, config, apiDetails, features, logger) { +var fs20 = __toESM(require("fs")); +async function cleanupAndUploadDatabases(action, repositoryNwo, codeql, config, apiDetails, checkoutPath) { + const logger2 = action.logger; if (getRequiredInput("upload-database") !== "true") { - logger.debug("Database upload disabled in workflow. Skipping upload."); + logger2.debug("Database upload disabled in workflow. Skipping upload."); return []; } if (!config.analysisKinds.includes("code-scanning" /* CodeScanning */)) { - logger.debug( + logger2.debug( `Not uploading database because 'analysis-kinds: ${"code-scanning" /* CodeScanning */}' is not enabled.` ); return []; } if (isInTestMode()) { - logger.debug("In test mode. Skipping database upload."); + logger2.debug("In test mode. Skipping database upload."); return []; } if (config.gitHubVersion.type !== "GitHub.com" /* DOTCOM */ && config.gitHubVersion.type !== "GitHub Enterprise Cloud with data residency" /* GHEC_DR */) { - logger.debug("Not running against github.com or GHEC-DR. Skipping upload."); + logger2.debug("Not running against github.com or GHEC-DR. Skipping upload."); return []; } - if (!await isAnalyzingDefaultBranch()) { - logger.debug("Not analyzing default branch. Skipping upload."); + if (!await isAnalyzingDefaultBranch(action.env, checkoutPath)) { + logger2.debug("Not analyzing default branch. Skipping upload."); return []; } - const shouldUploadOverlayBase = config.overlayDatabaseMode === "overlay-base" /* OverlayBase */ && await features.getValue("upload_overlay_db_to_api" /* UploadOverlayDbToApi */, codeql); + const shouldUploadOverlayBase = config.overlayDatabaseMode === "overlay-base" /* OverlayBase */ && await action.features.getValue("upload_overlay_db_to_api" /* UploadOverlayDbToApi */, codeql); const cleanupLevel = shouldUploadOverlayBase ? "overlay" /* Overlay */ : "clear" /* Clear */; await withGroupAsync("Cleaning up databases", async () => { await codeql.databaseCleanupCluster(config, cleanupLevel); @@ -153704,10 +187058,8 @@ async function cleanupAndUploadDatabases(repositoryNwo, codeql, config, apiDetai const bundledDb = await bundleDb(config, language, codeql, language, { includeDiagnostics: false }); - bundledDbSize = fs18.statSync(bundledDb).size; - const commitOid = await getCommitOid( - getRequiredInput("checkout_path") - ); + bundledDbSize = fs20.statSync(bundledDb).size; + const commitOid = await getCommitOid(action.env, checkoutPath); const maxAttempts = 4; let uploadDurationMs; for (let attempt = 1; attempt <= maxAttempts; attempt++) { @@ -153727,16 +187079,16 @@ async function cleanupAndUploadDatabases(repositoryNwo, codeql, config, apiDetai if (!isRetryable) { throw e; } else if (attempt === maxAttempts) { - logger.error( + logger2.error( `Maximum retry attempts exhausted (${attempt}), aborting database upload` ); throw e; } const backoffMs = 15e3 * Math.pow(2, attempt - 1); - logger.debug( + logger2.debug( `Database upload attempt ${attempt} of ${maxAttempts} failed for ${language}: ${getErrorMessage(e)}. Retrying in ${backoffMs / 1e3}s...` ); - await new Promise((resolve14) => setTimeout(resolve14, backoffMs)); + await new Promise((resolve15) => setTimeout(resolve15, backoffMs)); } } reports.push({ @@ -153745,9 +187097,9 @@ async function cleanupAndUploadDatabases(repositoryNwo, codeql, config, apiDetai is_overlay_base: shouldUploadOverlayBase, upload_duration_ms: uploadDurationMs }); - logger.debug(`Successfully uploaded database for ${language}`); + logger2.debug(`Successfully uploaded database for ${language}`); } catch (e) { - logger.warning( + logger2.warning( `Failed to upload database for ${language}: ${getErrorMessage(e)}` ); reports.push({ @@ -153760,17 +187112,17 @@ async function cleanupAndUploadDatabases(repositoryNwo, codeql, config, apiDetai if (shouldUploadOverlayBase && !config.debugMode) { await withGroupAsync( "Measuring database size at the clear cleanup level", - () => recordClearCleanupSizes(codeql, config, reports, logger) + () => recordClearCleanupSizes(codeql, config, reports, logger2) ); } return reports; } -async function recordClearCleanupSizes(codeql, config, reports, logger) { +async function recordClearCleanupSizes(codeql, config, reports, logger2) { const startTime = performance.now(); try { await codeql.databaseCleanupCluster(config, "clear" /* Clear */); } catch (e) { - logger.warning( + logger2.warning( `Failed to clean up databases at the '${"clear" /* Clear */}' level for size measurement: ${getErrorMessage(e)}` ); return; @@ -153784,12 +187136,12 @@ async function recordClearCleanupSizes(codeql, config, reports, logger) { const bundledDb = await bundleDb(config, language, codeql, language, { includeDiagnostics: false }); - report.clear_cleanup_zipped_size_bytes = fs18.statSync(bundledDb).size; - logger.debug( + report.clear_cleanup_zipped_size_bytes = fs20.statSync(bundledDb).size; + logger2.debug( `Database for ${language} is ${report.clear_cleanup_zipped_size_bytes} bytes zipped at the '${"clear" /* Clear */}' cleanup level (vs. ${report.zipped_upload_size_bytes ?? "unknown"} bytes at the '${"overlay" /* Overlay */}' level).` ); } catch (e) { - logger.warning( + logger2.warning( `Failed to measure the '${"clear" /* Clear */}' cleanup database size for ${language}: ${getErrorMessage(e)}` ); } @@ -153800,14 +187152,14 @@ async function recordClearCleanupSizes(codeql, config, reports, logger) { } } async function uploadBundledDatabase(repositoryNwo, language, commitOid, bundledDb, bundledDbSize, apiDetails) { - const client = getApiClient(); + const client = getApiClient(getEnv(), apiDetails); const uploadsUrl = new URL(parseGitHubUrl(apiDetails.url)); uploadsUrl.hostname = `uploads.${uploadsUrl.hostname}`; let uploadsBaseUrl = uploadsUrl.toString(); if (uploadsBaseUrl.endsWith("/")) { uploadsBaseUrl = uploadsBaseUrl.slice(0, -1); } - const bundledDbReadStream = fs18.createReadStream(bundledDb); + const bundledDbReadStream = fs20.createReadStream(bundledDb); try { const startTime = performance.now(); await client.request( @@ -153821,7 +187173,6 @@ async function uploadBundledDatabase(repositoryNwo, language, commitOid, bundled commit_oid: commitOid, data: bundledDbReadStream, headers: { - authorization: `token ${apiDetails.auth}`, "Content-Type": "application/zip", "Content-Length": bundledDbSize }, @@ -153844,6 +187195,7 @@ __export(upload_lib_exports, { filterAlertsByDiffRange: () => filterAlertsByDiffRange, findSarifFilesInDir: () => findSarifFilesInDir, getGroupedSarifFilePaths: () => getGroupedSarifFilePaths, + getSavedPayloadPath: () => getSavedPayloadPath, populateRunAutomationDetails: () => populateRunAutomationDetails, postProcessSarifFiles: () => postProcessSarifFiles, readSarifFileOrThrow: () => readSarifFileOrThrow, @@ -153859,15 +187211,15 @@ __export(upload_lib_exports, { waitForProcessing: () => waitForProcessing, writePostProcessedFiles: () => writePostProcessedFiles }); -var fs22 = __toESM(require("fs")); +var fs24 = __toESM(require("fs")); var path19 = __toESM(require("path")); var url = __toESM(require("url")); var import_zlib = __toESM(require("zlib")); -var core15 = __toESM(require_core()); +var core13 = __toESM(require_core()); var jsonschema2 = __toESM(require_lib2()); // src/fingerprints.ts -var fs19 = __toESM(require("fs")); +var fs21 = __toESM(require("fs")); var import_path4 = __toESM(require("path")); // node_modules/long/index.js @@ -154855,7 +188207,7 @@ async function hash(callback, filepath) { } updateHash(current); }; - const readStream = fs19.createReadStream(filepath, "utf8"); + const readStream = fs21.createReadStream(filepath, "utf8"); for await (const data of readStream) { for (let i = 0; i < data.length; ++i) { processCharacter(data.charCodeAt(i)); @@ -154869,7 +188221,7 @@ async function hash(callback, filepath) { updateHash(0); } } -function locationUpdateCallback(result, location, logger) { +function locationUpdateCallback(result, location, logger2) { let locationStartLine = location.physicalLocation?.region?.startLine; if (locationStartLine === void 0) { locationStartLine = 1; @@ -154885,29 +188237,29 @@ function locationUpdateCallback(result, location, logger) { if (!existingFingerprint) { result.partialFingerprints.primaryLocationLineHash = hashValue; } else if (existingFingerprint !== hashValue) { - logger.warning( + logger2.warning( `Calculated fingerprint of ${hashValue} for file ${location.physicalLocation.artifactLocation.uri} line ${lineNumber}, but found existing inconsistent fingerprint value ${existingFingerprint}` ); } }; } -function resolveUriToFile(location, artifacts, sourceRoot, logger) { +function resolveUriToFile(location, artifacts, sourceRoot, logger2) { if (!location.uri && location.index !== void 0) { - if (typeof location.index !== "number" || location.index < 0 || location.index >= artifacts.length || !isObject(artifacts[location.index].location)) { - logger.debug(`Ignoring location as index "${location.index}" is invalid`); + if (typeof location.index !== "number" || location.index < 0 || location.index >= artifacts.length || !isObject2(artifacts[location.index].location)) { + logger2.debug(`Ignoring location as index "${location.index}" is invalid`); return void 0; } location = artifacts[location.index].location; } if (typeof location.uri !== "string") { - logger.debug(`Ignoring location as URI "${location.uri}" is invalid`); + logger2.debug(`Ignoring location as URI "${location.uri}" is invalid`); return void 0; } let uri; try { uri = decodeURIComponent(location.uri); } catch { - logger.debug(`Ignoring location as URI "${location.uri}" is invalid`); + logger2.debug(`Ignoring location as URI "${location.uri}" is invalid`); return void 0; } const fileUriPrefix = "file://"; @@ -154915,14 +188267,14 @@ function resolveUriToFile(location, artifacts, sourceRoot, logger) { uri = uri.substring(fileUriPrefix.length); } if (uri.indexOf("://") !== -1) { - logger.debug( + logger2.debug( `Ignoring location URI "${uri}" as the scheme is not recognised` ); return void 0; } const srcRootPrefix = `${sourceRoot}/`; if (uri.startsWith("/") && !uri.startsWith(srcRootPrefix)) { - logger.debug( + logger2.debug( `Ignoring location URI "${uri}" as it is outside of the src root` ); return void 0; @@ -154930,18 +188282,18 @@ function resolveUriToFile(location, artifacts, sourceRoot, logger) { if (!import_path4.default.isAbsolute(uri)) { uri = srcRootPrefix + uri; } - if (!fs19.existsSync(uri)) { - logger.debug(`Unable to compute fingerprint for non-existent file: ${uri}`); + if (!fs21.existsSync(uri)) { + logger2.debug(`Unable to compute fingerprint for non-existent file: ${uri}`); return void 0; } - if (fs19.statSync(uri).isDirectory()) { - logger.debug(`Unable to compute fingerprint for directory: ${uri}`); + if (fs21.statSync(uri).isDirectory()) { + logger2.debug(`Unable to compute fingerprint for directory: ${uri}`); return void 0; } return uri; } -async function addFingerprints(sarifLog, sourceRoot, logger) { - logger.info( +async function addFingerprints(sarifLog, sourceRoot, logger2) { + logger2.info( `Adding fingerprints to SARIF file. See ${"https://docs.github.com/en/code-security/reference/code-scanning/sarif-support-for-code-scanning#data-for-preventing-duplicated-alerts" /* TRACK_CODE_SCANNING_ALERTS_ACROSS_RUNS */} for more information.` ); const callbacksByFile = {}; @@ -154950,7 +188302,7 @@ async function addFingerprints(sarifLog, sourceRoot, logger) { for (const result of run9.results || []) { const primaryLocation = (result.locations || [])[0]; if (!primaryLocation?.physicalLocation?.artifactLocation) { - logger.debug( + logger2.debug( `Unable to compute fingerprint for invalid location: ${JSON.stringify( primaryLocation )}` @@ -154964,7 +188316,7 @@ async function addFingerprints(sarifLog, sourceRoot, logger) { primaryLocation.physicalLocation.artifactLocation, artifacts, sourceRoot, - logger + logger2 ); if (!filepath) { continue; @@ -154973,7 +188325,7 @@ async function addFingerprints(sarifLog, sourceRoot, logger) { callbacksByFile[filepath] = []; } callbacksByFile[filepath].push( - locationUpdateCallback(result, primaryLocation, logger) + locationUpdateCallback(result, primaryLocation, logger2) ); } } @@ -154989,14 +188341,13 @@ async function addFingerprints(sarifLog, sourceRoot, logger) { } // src/init.ts -var fs20 = __toESM(require("fs")); +var fs22 = __toESM(require("fs")); var path18 = __toESM(require("path")); -var core14 = __toESM(require_core()); -var toolrunner4 = __toESM(require_toolrunner()); +var toolrunner5 = __toESM(require_toolrunner()); var github3 = __toESM(require_github()); -var io6 = __toESM(require_io()); -async function initCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, features, logger) { - logger.startGroup("Setup CodeQL tools"); +var io7 = __toESM(require_io()); +async function initCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliVersion, rawLanguages, otherLanguagePacksReason, useOverlayAwareDefaultCliVersion, features, logger2) { + logger2.startGroup("Setup CodeQL tools"); const { codeql, toolsDownloadStatusReport, toolsSource, toolsVersion } = await setupCodeQL( toolsInput, apiDetails, @@ -155004,13 +188355,14 @@ async function initCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliVe variant, defaultCliVersion, rawLanguages, + otherLanguagePacksReason, useOverlayAwareDefaultCliVersion, features, - logger, + logger2, true ); await codeql.printVersion(); - logger.endGroup(); + logger2.endGroup(); return { codeql, toolsDownloadStatusReport, @@ -155024,7 +188376,7 @@ async function initConfig2(actionState, inputs) { }); } async function runDatabaseInitCluster(databaseInitEnvironment, codeql, config, sourceRoot, processName, qlconfigFile) { - fs20.mkdirSync(config.dbLocation, { recursive: true }); + fs22.mkdirSync(config.dbLocation, { recursive: true }); await wrapEnvironment( databaseInitEnvironment, async () => await codeql.databaseInitCluster( @@ -155035,10 +188387,10 @@ async function runDatabaseInitCluster(databaseInitEnvironment, codeql, config, s ) ); } -async function checkPacksForOverlayCompatibility(codeql, config, logger) { +async function checkPacksForOverlayCompatibility(codeql, config, logger2) { const codeQlOverlayVersion = (await codeql.getVersion()).overlayVersion; if (codeQlOverlayVersion === void 0) { - logger.warning("The CodeQL CLI does not support overlay analysis."); + logger2.warning("The CodeQL CLI does not support overlay analysis."); return false; } for (const language of config.languages) { @@ -155048,7 +188400,7 @@ async function checkPacksForOverlayCompatibility(codeql, config, logger) { (packDir) => !checkPackForOverlayCompatibility( packDir, codeQlOverlayVersion, - logger + logger2 ) )) { return false; @@ -155056,43 +188408,43 @@ async function checkPacksForOverlayCompatibility(codeql, config, logger) { } return true; } -function checkPackForOverlayCompatibility(packDir, codeQlOverlayVersion, logger) { +function checkPackForOverlayCompatibility(packDir, codeQlOverlayVersion, logger2) { try { let qlpackPath = path18.join(packDir, "qlpack.yml"); - if (!fs20.existsSync(qlpackPath)) { + if (!fs22.existsSync(qlpackPath)) { qlpackPath = path18.join(packDir, "codeql-pack.yml"); } const qlpackContents = load( - fs20.readFileSync(qlpackPath, "utf8") + fs22.readFileSync(qlpackPath, "utf8") ); if (!qlpackContents.buildMetadata) { return true; } const packInfoPath = path18.join(packDir, ".packinfo"); - if (!fs20.existsSync(packInfoPath)) { - logger.warning( + if (!fs22.existsSync(packInfoPath)) { + logger2.warning( `The query pack at ${packDir} does not have a .packinfo file, so it cannot support overlay analysis. Recompiling the query pack with the latest CodeQL CLI should solve this problem.` ); return false; } const packInfoFileContents = JSON.parse( - fs20.readFileSync(packInfoPath, "utf8") + fs22.readFileSync(packInfoPath, "utf8") ); const packOverlayVersion = packInfoFileContents.overlayVersion; if (typeof packOverlayVersion !== "number") { - logger.warning( + logger2.warning( `The .packinfo file for the query pack at ${packDir} does not have the overlayVersion field, which indicates that the pack is not compatible with overlay analysis.` ); return false; } if (packOverlayVersion !== codeQlOverlayVersion) { - logger.warning( + logger2.warning( `The query pack at ${packDir} was compiled with overlay version ${packOverlayVersion}, but the CodeQL CLI supports overlay version ${codeQlOverlayVersion}. The query pack needs to be recompiled to support overlay analysis.` ); return false; } } catch (e) { - logger.warning( + logger2.warning( `Error while checking pack at ${packDir} for overlay compatibility: ${getErrorMessage(e)}` ); return false; @@ -155106,15 +188458,15 @@ async function checkInstallPython311(languages, codeql) { "../python-setup", "check_python12.ps1" ); - await new toolrunner4.ToolRunner(await io6.which("powershell", true), [ + await new toolrunner5.ToolRunner(await io7.which("powershell", true), [ script ]).exec(); } } -function cleanupDatabaseClusterDirectory(config, logger, options = {}, rmSync5 = fs20.rmSync) { - if (fs20.existsSync(config.dbLocation) && (fs20.statSync(config.dbLocation).isFile() || fs20.readdirSync(config.dbLocation).length > 0)) { +function cleanupDatabaseClusterDirectory(config, logger2, options = {}, rmSync5 = fs22.rmSync) { + if (fs22.existsSync(config.dbLocation) && (fs22.statSync(config.dbLocation).isFile() || fs22.readdirSync(config.dbLocation).length > 0)) { if (!options.disableExistingDirectoryWarning) { - logger.warning( + logger2.warning( `The database cluster directory ${config.dbLocation} must be empty. Attempting to clean it up.` ); } @@ -155124,7 +188476,7 @@ function cleanupDatabaseClusterDirectory(config, logger, options = {}, rmSync5 = maxRetries: 3, recursive: true }); - logger.info( + logger2.info( `Cleaned up database cluster directory ${config.dbLocation}.` ); } catch (e) { @@ -155185,7 +188537,7 @@ async function getFileCoverageInformationEnabled(debugMode, codeql, features, re showDeprecationWarning: false }; } -function logFileCoverageOnPrsDeprecationWarning(logger) { +function logFileCoverageOnPrsDeprecationWarning(logger2) { if (process.env["CODEQL_ACTION_DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION" /* DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION */]) { return; } @@ -155212,12 +188564,12 @@ To opt out of this change, switch to an advanced setup workflow and ${envVarOptO To opt out of this change, ${envVarOptOut}`; } - logger.warning(message); - core14.exportVariable("CODEQL_ACTION_DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION" /* DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION */, "true"); + logger2.warning(message); + exportEnvVar("CODEQL_ACTION_DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION" /* DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION */, "true"); } // src/sarif/index.ts -var fs21 = __toESM(require("fs")); +var fs23 = __toESM(require("fs")); var InvalidSarifUploadError = class extends Error { }; function getToolNames(sarifFile) { @@ -155232,14 +188584,20 @@ function getToolNames(sarifFile) { return Object.keys(toolNames); } function readSarifFile(sarifFilePath) { - return JSON.parse(fs21.readFileSync(sarifFilePath, "utf8")); + try { + return JSON.parse(fs23.readFileSync(sarifFilePath, "utf8")); + } catch (err) { + throw new Error( + `Parsing SARIF file at '${sarifFilePath}' failed: ${getErrorMessage(err)}` + ); + } } -function combineSarifFiles(sarifFiles, logger) { - logger.info(`Loading SARIF file(s)`); +function combineSarifFiles(sarifFiles, logger2) { + logger2.info(`Loading SARIF file(s)`); const runs = []; let version = void 0; for (const sarifFile of sarifFiles) { - logger.debug(`Loading SARIF file: ${sarifFile}`); + logger2.debug(`Loading SARIF file: ${sarifFile}`); const sarifLog = readSarifFile(sarifFile); if (version === void 0) { version = sarifLog.version; @@ -155313,32 +188671,32 @@ async function shouldDisableCombineSarifFiles(sarifObjects, githubVersion) { } return true; } -async function combineSarifFilesUsingCLI(sarifFiles, gitHubVersion, features, logger) { - logger.info("Combining SARIF files using the CodeQL CLI"); +async function combineSarifFilesUsingCLI(sarifFiles, gitHubVersion, features, logger2, config) { + const env = getEnv(); + logger2.info("Combining SARIF files using the CodeQL CLI"); const sarifObjects = sarifFiles.map(readSarifFile); const deprecationWarningMessage = gitHubVersion.type === "GitHub Enterprise Server" /* GHES */ ? "and will be removed in GitHub Enterprise Server 3.18" : "and will be removed in July 2025"; const deprecationMoreInformationMessage = "For more information, see https://github.blog/changelog/2024-05-06-code-scanning-will-stop-combining-runs-from-a-single-upload"; if (!areAllRunsProducedByCodeQL(sarifObjects)) { await throwIfCombineSarifFilesDisabled(sarifObjects, gitHubVersion); - logger.debug( + logger2.debug( "Not all SARIF files were produced by CodeQL. Merging files in the action." ); if (await shouldShowCombineSarifFilesDeprecationWarning(sarifObjects)) { - logger.warning( + logger2.warning( `Uploading multiple SARIF runs with the same category is deprecated ${deprecationWarningMessage}. Please update your workflow to upload a single run per category. ${deprecationMoreInformationMessage}` ); - core15.exportVariable("CODEQL_MERGE_SARIF_DEPRECATION_WARNING", "true"); + exportEnvVar("CODEQL_MERGE_SARIF_DEPRECATION_WARNING", "true"); } - return combineSarifFiles(sarifFiles, logger); + return combineSarifFiles(sarifFiles, logger2); } let codeQL; let tempDir = getTemporaryDirectory(); - const config = await getConfig(tempDir, logger); if (config !== void 0) { - codeQL = await getCodeQL(logger, config.codeQLCmd); + codeQL = await getCodeQL(logger2, config.codeQLCmd); tempDir = config.tempDir; } else { - logger.info( + logger2.info( "Initializing CodeQL since the 'init' Action was not called before this step." ); const apiDetails = { @@ -155346,8 +188704,7 @@ async function combineSarifFilesUsingCLI(sarifFiles, gitHubVersion, features, lo externalRepoAuth: getOptionalInput( "external-repository-token" ), - url: getRequiredEnvParam("GITHUB_SERVER_URL"), - apiURL: getRequiredEnvParam("GITHUB_API_URL") + ...getCurrentInstance(env) }; const codeQLDefaultVersionInfo = await features.getEnabledDefaultCliVersions(gitHubVersion.type); const initCodeQLResult = await initCodeQL( @@ -155359,16 +188716,18 @@ async function combineSarifFilesUsingCLI(sarifFiles, gitHubVersion, features, lo codeQLDefaultVersionInfo, void 0, // rawLanguages: upload-lib does not run analysis + void 0, + // otherLanguagePacksReason: upload-lib does not run analysis false, // useOverlayAwareDefaultCliVersion: upload-lib does not run analysis features, - logger + logger2 ); codeQL = initCodeQLResult.codeql; } const baseTempDir = path19.resolve(tempDir, "combined-sarif"); - fs22.mkdirSync(baseTempDir, { recursive: true }); - const outputDirectory = fs22.mkdtempSync(path19.resolve(baseTempDir, "output-")); + fs24.mkdirSync(baseTempDir, { recursive: true }); + const outputDirectory = fs24.mkdtempSync(path19.resolve(baseTempDir, "output-")); const outputFile = path19.resolve(outputDirectory, "combined-sarif.sarif"); await codeQL.mergeResults(sarifFiles, outputFile, { mergeRunsFromEqualCategory: true @@ -155399,18 +188758,21 @@ function getAutomationID2(category, analysis_key, environment) { } return computeAutomationID(analysis_key, environment); } -async function uploadPayload(payload, repositoryNwo, logger, analysis) { - logger.info("Uploading results"); +function getSavedPayloadPath(analysisKind) { + return path19.join( + getTemporaryDirectory(), + `payload-${analysisKind}.json` + ); +} +async function uploadPayload(payload, repositoryNwo, logger2, analysis) { + logger2.info("Uploading results"); if (shouldSkipSarifUpload()) { - const payloadSaveFile = path19.join( - getTemporaryDirectory(), - `payload-${analysis.kind}.json` - ); - logger.info( + const payloadSaveFile = getSavedPayloadPath(analysis.kind); + logger2.info( `SARIF upload disabled by an environment variable. Saving to ${payloadSaveFile}` ); - logger.info(`Payload: ${JSON.stringify(payload, null, 2)}`); - fs22.writeFileSync(payloadSaveFile, JSON.stringify(payload, null, 2)); + logger2.info(`Payload: ${JSON.stringify(payload, null, 2)}`); + fs24.writeFileSync(payloadSaveFile, JSON.stringify(payload, null, 2)); return "dummy-sarif-id"; } const client = getApiClient(); @@ -155420,21 +188782,21 @@ async function uploadPayload(payload, repositoryNwo, logger, analysis) { repo: repositoryNwo.repo, data: payload }); - logger.debug(`response status: ${response.status}`); - logger.info("Successfully uploaded results"); + logger2.debug(`response status: ${response.status}`); + logger2.info("Successfully uploaded results"); return response.data.id; } catch (e) { const httpError = asHTTPError(e); if (httpError !== void 0) { switch (httpError.status) { case 403: - core15.warning(httpError.message || GENERIC_403_MSG); + core13.warning(httpError.message || GENERIC_403_MSG); break; case 404: - core15.warning(httpError.message || GENERIC_404_MSG); + core13.warning(httpError.message || GENERIC_404_MSG); break; default: - core15.warning(httpError.message); + core13.warning(httpError.message); break; } } @@ -155444,7 +188806,7 @@ async function uploadPayload(payload, repositoryNwo, logger, analysis) { function findSarifFilesInDir(sarifPath, isSarif) { const sarifFiles = []; const walkSarifFiles = (dir) => { - const entries = fs22.readdirSync(dir, { withFileTypes: true }); + const entries = fs24.readdirSync(dir, { withFileTypes: true }); for (const entry of entries) { if (entry.isFile() && isSarif(entry.name)) { sarifFiles.push(path19.resolve(dir, entry.name)); @@ -155457,11 +188819,11 @@ function findSarifFilesInDir(sarifPath, isSarif) { return sarifFiles; } function getSarifFilePaths(sarifPath, isSarif) { - if (!fs22.existsSync(sarifPath)) { + if (!fs24.existsSync(sarifPath)) { throw new ConfigurationError(`Path does not exist: ${sarifPath}`); } let sarifFiles; - if (fs22.lstatSync(sarifPath).isDirectory()) { + if (fs24.lstatSync(sarifPath).isDirectory()) { sarifFiles = findSarifFilesInDir(sarifPath, isSarif); if (sarifFiles.length === 0) { throw new ConfigurationError( @@ -155473,8 +188835,8 @@ function getSarifFilePaths(sarifPath, isSarif) { } return sarifFiles; } -async function getGroupedSarifFilePaths(logger, sarifPath) { - const stats = fs22.statSync(sarifPath, { throwIfNoEntry: false }); +async function getGroupedSarifFilePaths(logger2, sarifPath) { + const stats = fs24.statSync(sarifPath, { throwIfNoEntry: false }); if (stats === void 0) { throw new ConfigurationError(`Path does not exist: ${sarifPath}`); } @@ -155484,7 +188846,7 @@ async function getGroupedSarifFilePaths(logger, sarifPath) { sarifPath, (name) => path19.extname(name) === ".sarif" ); - logger.debug( + logger2.debug( `Found the following .sarif files in ${sarifPath}: ${unassignedSarifFiles.join(", ")}` ); for (const analysisConfig of SarifScanOrder) { @@ -155492,7 +188854,7 @@ async function getGroupedSarifFilePaths(logger, sarifPath) { analysisConfig.sarifPredicate ); if (filesForCurrentAnalysis.length > 0) { - logger.debug( + logger2.debug( `The following SARIF files are for ${analysisConfig.name}: ${filesForCurrentAnalysis.join(", ")}` ); unassignedSarifFiles = unassignedSarifFiles.filter( @@ -155500,18 +188862,18 @@ async function getGroupedSarifFilePaths(logger, sarifPath) { ); results[analysisConfig.kind] = filesForCurrentAnalysis; } else { - logger.debug(`Found no SARIF files for ${analysisConfig.name}`); + logger2.debug(`Found no SARIF files for ${analysisConfig.name}`); } } if (unassignedSarifFiles.length !== 0) { - logger.warning( + logger2.warning( `Found files in ${sarifPath} which do not belong to any analysis: ${unassignedSarifFiles.join(", ")}` ); } } else { for (const analysisConfig of SarifScanOrder) { if (analysisConfig.kind === "code-scanning" /* CodeScanning */ || analysisConfig.sarifPredicate(sarifPath)) { - logger.debug( + logger2.debug( `Using '${sarifPath}' as a SARIF file for ${analysisConfig.name}.` ); results[analysisConfig.kind] = [sarifPath]; @@ -155546,15 +188908,15 @@ function readSarifFileOrThrow(sarifFilePath) { ); } } -function validateSarifFileSchema(sarifLog, sarifFilePath, logger) { +function validateSarifFileSchema(sarifLog, sarifFilePath, logger2) { if (areAllRunsProducedByCodeQL([sarifLog]) && // We want to validate CodeQL SARIF in testing environments. !getTestingEnvironment()) { - logger.debug( + logger2.debug( `Skipping SARIF schema validation for ${sarifFilePath} as all runs are produced by CodeQL.` ); return true; } - logger.info(`Validating ${sarifFilePath}`); + logger2.info(`Validating ${sarifFilePath}`); const schema = require_sarif_schema_2_1_0(); const result = new jsonschema2.Validator().validate(sarifLog, schema); const warningAttributes = ["uri-reference", "uri"]; @@ -155565,15 +188927,15 @@ function validateSarifFileSchema(sarifLog, sarifFilePath, logger) { (err) => err.name === "format" && typeof err.argument === "string" && warningAttributes.includes(err.argument) ); for (const warning14 of warnings) { - logger.info( + logger2.info( `Warning: '${warning14.instance}' is not a valid URI in '${warning14.property}'.` ); } if (errors.length > 0) { for (const error3 of errors) { - logger.startGroup(`Error details: ${error3.stack}`); - logger.info(JSON.stringify(error3, null, 2)); - logger.endGroup(); + logger2.startGroup(`Error details: ${error3.stack}`); + logger2.info(JSON.stringify(error3, null, 2)); + logger2.endGroup(); } const sarifErrors = errors.map((e) => `- ${e.stack}`); throw new InvalidSarifUploadError( @@ -155609,7 +188971,7 @@ function buildPayload(commitOid, ref, analysisKey, analysisName, zippedSarif, wo payloadObj.base_sha = mergeBaseCommitOid; } else if (process.env.GITHUB_EVENT_PATH) { const githubEvent = JSON.parse( - fs22.readFileSync(process.env.GITHUB_EVENT_PATH, "utf8") + fs24.readFileSync(process.env.GITHUB_EVENT_PATH, "utf8") ); payloadObj.base_ref = `refs/heads/${githubEvent.pull_request.base.ref}`; payloadObj.base_sha = githubEvent.pull_request.base.sha; @@ -155617,30 +188979,31 @@ function buildPayload(commitOid, ref, analysisKey, analysisName, zippedSarif, wo } return payloadObj; } -async function postProcessSarifFiles(logger, features, checkoutPath, sarifPaths, category, analysis) { - logger.info(`Post-processing sarif files: ${JSON.stringify(sarifPaths)}`); +async function postProcessSarifFiles(logger2, features, config, checkoutPath, sarifPaths, category, analysis) { + logger2.info(`Post-processing sarif files: ${JSON.stringify(sarifPaths)}`); const gitHubVersion = await getGitHubVersion(); let sarifLog; - category = analysis.fixCategory(logger, category); + category = analysis.fixCategory(logger2, category); if (sarifPaths.length > 1) { for (const sarifPath of sarifPaths) { const parsedSarif = readSarifFileOrThrow(sarifPath); - validateSarifFileSchema(parsedSarif, sarifPath, logger); + validateSarifFileSchema(parsedSarif, sarifPath, logger2); } sarifLog = await combineSarifFilesUsingCLI( sarifPaths, gitHubVersion, features, - logger + logger2, + config ); } else { const sarifPath = sarifPaths[0]; sarifLog = readSarifFileOrThrow(sarifPath); - validateSarifFileSchema(sarifLog, sarifPath, logger); + validateSarifFileSchema(sarifLog, sarifPath, logger2); await throwIfCombineSarifFilesDisabled([sarifLog], gitHubVersion); } - sarifLog = filterAlertsByDiffRange(logger, sarifLog); - sarifLog = await addFingerprints(sarifLog, checkoutPath, logger); + sarifLog = filterAlertsByDiffRange(logger2, sarifLog); + sarifLog = await addFingerprints(sarifLog, checkoutPath, logger2); const analysisKey = await getAnalysisKey(); const environment = getRequiredInput("matrix"); sarifLog = populateRunAutomationDetails( @@ -155651,66 +189014,69 @@ async function postProcessSarifFiles(logger, features, checkoutPath, sarifPaths, ); return { sarif: sarifLog, analysisKey, environment }; } -async function writePostProcessedFiles(logger, pathInput, uploadTarget, postProcessingResults) { +async function writePostProcessedFiles(logger2, pathInput, uploadTarget, postProcessingResults) { const outputPath = pathInput || getOptionalEnvVar("CODEQL_ACTION_SARIF_DUMP_DIR" /* SARIF_DUMP_DIR */); if (outputPath !== void 0) { dumpSarifFile( JSON.stringify(postProcessingResults.sarif), outputPath, - logger, + logger2, uploadTarget ); } else { - logger.debug(`Not writing post-processed SARIF files.`); + logger2.debug(`Not writing post-processed SARIF files.`); } } -async function uploadFiles(inputSarifPath, checkoutPath, category, features, logger, uploadTarget) { +async function uploadFiles(config, inputSarifPath, checkoutPath, category, features, logger2, uploadTarget) { const sarifPaths = getSarifFilePaths( inputSarifPath, uploadTarget.sarifPredicate ); return uploadSpecifiedFiles( sarifPaths, + config, checkoutPath, category, features, - logger, + logger2, uploadTarget ); } -async function uploadSpecifiedFiles(sarifPaths, checkoutPath, category, features, logger, uploadTarget) { +async function uploadSpecifiedFiles(sarifPaths, config, checkoutPath, category, features, logger2, uploadTarget) { const processingResults = await postProcessSarifFiles( - logger, + logger2, features, + config, checkoutPath, sarifPaths, category, uploadTarget ); return uploadPostProcessedFiles( - logger, + logger2, checkoutPath, uploadTarget, processingResults ); } -async function uploadPostProcessedFiles(logger, checkoutPath, uploadTarget, postProcessingResults) { - logger.startGroup(`Uploading ${uploadTarget.name} results`); +async function uploadPostProcessedFiles(logger2, checkoutPath, uploadTarget, postProcessingResults) { + logger2.startGroup(`Uploading ${uploadTarget.name} results`); const sarifLog = postProcessingResults.sarif; const toolNames = getToolNames(sarifLog); - logger.debug(`Validating that each SARIF run has a unique category`); + logger2.debug(`Validating that each SARIF run has a unique category`); validateUniqueCategory(sarifLog, uploadTarget.sentinelPrefix); - logger.debug(`Serializing SARIF for upload`); + logger2.debug(`Serializing SARIF for upload`); const sarifPayload = JSON.stringify(sarifLog); - logger.debug(`Compressing serialized SARIF`); + logger2.debug(`Compressing serialized SARIF`); const zippedSarif = import_zlib.default.gzipSync(sarifPayload).toString("base64"); const checkoutURI = url.pathToFileURL(checkoutPath).href; + const env = getEnv(); const payload = uploadTarget.transformPayload( buildPayload( - await getCommitOid(checkoutPath), - await getRef(), + await getCommitOid(env, checkoutPath), + await getRef(env, checkoutPath), postProcessingResults.analysisKey, - getRequiredEnvParam("GITHUB_WORKFLOW"), + env.getRequired("GITHUB_WORKFLOW" /* GITHUB_WORKFLOW */), zippedSarif, getWorkflowRunID(), getWorkflowRunAttempt(), @@ -155721,18 +189087,18 @@ async function uploadPostProcessedFiles(logger, checkoutPath, uploadTarget, post ) ); const rawUploadSizeBytes = sarifPayload.length; - logger.debug(`Raw upload size: ${rawUploadSizeBytes} bytes`); + logger2.debug(`Raw upload size: ${rawUploadSizeBytes} bytes`); const zippedUploadSizeBytes = zippedSarif.length; - logger.debug(`Base64 zipped upload size: ${zippedUploadSizeBytes} bytes`); + logger2.debug(`Base64 zipped upload size: ${zippedUploadSizeBytes} bytes`); const numResultInSarif = countResultsInSarif(sarifPayload); - logger.debug(`Number of results in upload: ${numResultInSarif}`); + logger2.debug(`Number of results in upload: ${numResultInSarif}`); const sarifID = await uploadPayload( payload, getRepositoryNwo(), - logger, + logger2, uploadTarget ); - logger.endGroup(); + logger2.endGroup(); return { statusReport: { raw_upload_size_bytes: rawUploadSizeBytes, @@ -155742,10 +189108,10 @@ async function uploadPostProcessedFiles(logger, checkoutPath, uploadTarget, post sarifID }; } -function dumpSarifFile(sarifPayload, outputDir, logger, uploadTarget) { - if (!fs22.existsSync(outputDir)) { - fs22.mkdirSync(outputDir, { recursive: true }); - } else if (!fs22.lstatSync(outputDir).isDirectory()) { +function dumpSarifFile(sarifPayload, outputDir, logger2, uploadTarget) { + if (!fs24.existsSync(outputDir)) { + fs24.mkdirSync(outputDir, { recursive: true }); + } else if (!fs24.lstatSync(outputDir).isDirectory()) { throw new ConfigurationError( `The path that processed SARIF files should be written to exists, but is not a directory: ${outputDir}` ); @@ -155754,17 +189120,23 @@ function dumpSarifFile(sarifPayload, outputDir, logger, uploadTarget) { outputDir, `upload${uploadTarget.sarifExtension}` ); - logger.info(`Writing processed SARIF file to ${outputFile}`); - fs22.writeFileSync(outputFile, sarifPayload); + logger2.info(`Writing processed SARIF file to ${outputFile}`); + fs24.writeFileSync(outputFile, sarifPayload); } var STATUS_CHECK_INITIAL_BACKOFF_MILLISECONDS = 5 * 1e3; var STATUS_CHECK_BACKOFF_MULTIPLIER = 2; var STATUS_CHECK_MAX_TRIES = 5; -async function waitForProcessing(repositoryNwo, sarifID, logger, options = { +async function waitForProcessing(repositoryNwo, sarifID, logger2, options = { isUnsuccessfulExecution: false }) { - logger.startGroup("Waiting for processing to finish"); + logger2.startGroup("Waiting for processing to finish"); try { + if (shouldSkipSarifUpload()) { + logger2.info( + "Nothing to wait for, because SARIF upload is disabled by an environment variable and the SARIF was saved to disk." + ); + return; + } const client = getApiClient(); let statusCheckBackoff = STATUS_CHECK_INITIAL_BACKOFF_MILLISECONDS; if (process.env["NODE_ENV"] !== "test") { @@ -155782,20 +189154,20 @@ async function waitForProcessing(repositoryNwo, sarifID, logger, options = { } ); } catch (e) { - logger.warning( + logger2.warning( `An error occurred checking the status of the delivery. ${e} It should still be processed in the background, but errors that occur during processing may not be reported.` ); break; } const status = response.data.processing_status; - logger.info(`Analysis upload status is ${status}.`); + logger2.info(`Analysis upload status is ${status}.`); if (status === "pending") { - logger.debug("Analysis processing is still pending..."); + logger2.debug("Analysis processing is still pending..."); } else if (options.isUnsuccessfulExecution) { handleProcessingResultForUnsuccessfulExecution( response, status, - logger + logger2 ); break; } else if (status === "complete") { @@ -155809,7 +189181,7 @@ ${response.data.errors}`; assertNever(status); } if (statusCheckCount === STATUS_CHECK_MAX_TRIES) { - logger.warning( + logger2.warning( "Timed out waiting for analysis to finish processing. Continuing." ); break; @@ -155819,7 +189191,7 @@ ${response.data.errors}`; } } } finally { - logger.endGroup(); + logger2.endGroup(); } } function shouldConsiderConfigurationError(processingErrors) { @@ -155839,18 +189211,18 @@ function shouldConsiderInvalidRequest(processingErrors) { ) ); } -function handleProcessingResultForUnsuccessfulExecution(response, status, logger) { +function handleProcessingResultForUnsuccessfulExecution(response, status, logger2) { if (status === "failed" && Array.isArray(response.data.errors) && response.data.errors.length === 1 && // eslint-disable-next-line @typescript-eslint/no-unsafe-call response.data.errors[0].toString().startsWith("unsuccessful execution")) { - logger.info( + logger2.info( 'Successfully uploaded a SARIF file for the unsuccessful execution. Received expected "unsuccessful execution" processing error, and no other errors.' ); } else if (status === "failed") { - logger.warning( + logger2.warning( `Failed to upload a SARIF file for the unsuccessful execution. Code scanning status information for the repository may be out of date as a result. Processing errors: ${response.data.errors}` ); } else if (status === "complete") { - logger.debug( + logger2.debug( 'Uploaded a SARIF file for the unsuccessful execution, but did not receive the expected "unsuccessful execution" processing error. This is a known transient issue with the code scanning API, and does not cause out of date code scanning status information.' ); } else { @@ -155872,14 +189244,14 @@ function validateUniqueCategory(sarifLog, sentinelPrefix) { `Aborting upload: only one run of the codeql/analyze or codeql/upload-sarif actions is allowed per job per tool/category. The easiest fix is to specify a unique value for the \`category\` input. If .runs[].automationDetails.id is specified in the sarif file, that will take precedence over your configured \`category\`. Category: (${id ? id : "none"}) Tool: (${tool ? tool : "none"})` ); } - core15.exportVariable(sentinelEnvVar, sentinelEnvVar); + exportEnvVar(sentinelEnvVar, sentinelEnvVar); } } function sanitize(str) { return (str ?? "_").replace(/[^a-zA-Z0-9_]/g, "_").toLocaleUpperCase(); } -function filterAlertsByDiffRange(logger, sarifLog) { - const diffRanges = readDiffRangesJsonFile(logger); +function filterAlertsByDiffRange(logger2, sarifLog) { + const diffRanges = readDiffRangesJsonFile(logger2); if (!diffRanges?.length) { return sarifLog; } @@ -155896,11 +189268,19 @@ function filterAlertsByDiffRange(logger, sarifLog) { return locations.some((physicalLocation) => { const locationUri = physicalLocation?.artifactLocation?.uri; const locationStartLine = physicalLocation?.region?.startLine; - if (!locationUri || locationStartLine === void 0) { + if (typeof locationUri !== "string" || !locationUri || locationStartLine === void 0) { return false; } + let decodedLocationUri = locationUri; + try { + decodedLocationUri = decodeURIComponent(locationUri); + } catch { + logger2.debug( + `Failed to decode location URI "${locationUri}", comparing it as a raw path` + ); + } return diffRanges.some( - (range2) => range2.path === locationUri && (range2.startLine <= locationStartLine && range2.endLine >= locationStartLine || range2.startLine === 0 && range2.endLine === 0) + (range2) => (range2.path === decodedLocationUri || range2.path === locationUri) && (range2.startLine <= locationStartLine && range2.endLine >= locationStartLine || range2.startLine === 0 && range2.endLine === 0) ); }); }); @@ -155910,9 +189290,9 @@ function filterAlertsByDiffRange(logger, sarifLog) { } // src/upload-sarif.ts -async function postProcessAndUploadSarif(logger, features, uploadKind, checkoutPath, sarifPath, category, postProcessedOutputPath) { +async function postProcessAndUploadSarif(logger2, features, config, uploadKind, checkoutPath, sarifPath, category, postProcessedOutputPath) { const sarifGroups = await getGroupedSarifFilePaths( - logger, + logger2, sarifPath ); const uploadResults = {}; @@ -155921,22 +189301,23 @@ async function postProcessAndUploadSarif(logger, features, uploadKind, checkoutP )) { const analysisConfig = getAnalysisConfig(analysisKind); const postProcessingResults = await postProcessSarifFiles( - logger, + logger2, features, + config, checkoutPath, sarifFiles, category, analysisConfig ); await writePostProcessedFiles( - logger, + logger2, postProcessedOutputPath, analysisConfig, postProcessingResults ); if (uploadKind === "always") { uploadResults[analysisKind] = await uploadPostProcessedFiles( - logger, + logger2, checkoutPath, analysisConfig, postProcessingResults @@ -155947,15 +189328,15 @@ async function postProcessAndUploadSarif(logger, features, uploadKind, checkoutP } // src/analyze-action.ts -async function sendStatusReport2(startedAt, config, stats, error3, trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, trapCacheCleanup, dependencyCacheResults, databaseUploadResults, logger) { +async function sendStatusReport2(startedAt, config, stats, error3, trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, dependencyCacheResults, databaseUploadResults, logger2) { const status = getActionsStatus(error3, stats?.analyze_failure_language); const statusReportBase = await createStatusReportBase( "finish" /* Analyze */, status, startedAt, config, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3?.message, error3?.stack ); @@ -155964,7 +189345,6 @@ async function sendStatusReport2(startedAt, config, stats, error3, trapCacheUplo ...statusReportBase, ...stats || {}, ...dbCreationTimings || {}, - ...trapCacheCleanup || {}, dependency_caching_upload_results: dependencyCacheResults, database_upload_results: databaseUploadResults }; @@ -155973,7 +189353,7 @@ async function sendStatusReport2(startedAt, config, stats, error3, trapCacheUplo ...report, trap_cache_upload_duration_ms: Math.round(trapCacheUploadTime || 0), trap_cache_upload_size_bytes: Math.round( - await getTotalCacheSize(Object.values(config.trapCaches), logger) + await getTotalCacheSize(Object.values(config.trapCaches), logger2) ) }; await sendStatusReport(trapCacheUploadStatusReport); @@ -155995,7 +189375,7 @@ function doesGoExtractionOutputExist(config) { "trap", "go" /* go */ ); - return fs23.existsSync(trapDirectory) && fs23.readdirSync(trapDirectory).some( + return fs25.existsSync(trapDirectory) && fs25.readdirSync(trapDirectory).some( (fileName) => [ ".trap", ".trap.gz", @@ -156006,94 +189386,91 @@ function doesGoExtractionOutputExist(config) { ].some((ext2) => fileName.endsWith(ext2)) ); } -async function runAutobuildIfLegacyGoWorkflow(config, logger) { +async function runAutobuildIfLegacyGoWorkflow(config, logger2) { if (!config.languages.includes("go" /* go */)) { return; } if (config.buildMode) { - logger.debug( + logger2.debug( "Skipping legacy Go autobuild since a build mode has been specified." ); return; } if (process.env["CODEQL_ACTION_DID_AUTOBUILD_GOLANG" /* DID_AUTOBUILD_GOLANG */] === "true") { - logger.debug("Won't run Go autobuild since it has already been run."); + logger2.debug("Won't run Go autobuild since it has already been run."); return; } - if (dbIsFinalized(config, "go" /* go */, logger)) { - logger.debug( + if (dbIsFinalized(config, "go" /* go */, logger2)) { + logger2.debug( "Won't run Go autobuild since there is already a finalized database for Go." ); return; } if (doesGoExtractionOutputExist(config)) { - logger.debug( + logger2.debug( "Won't run Go autobuild since at least one file of Go code has already been extracted." ); if ("CODEQL_EXTRACTOR_GO_BUILD_TRACING" in process.env) { - logger.warning( + logger2.warning( `The CODEQL_EXTRACTOR_GO_BUILD_TRACING environment variable has no effect on workflows with manual build steps, so we recommend that you remove it from your workflow.` ); } return; } - logger.debug( + logger2.debug( "Running Go autobuild because extraction output (TRAP files) for Go code has not been found." ); - await runAutobuild(config, "go" /* go */, logger); + await runAutobuild(config, "go" /* go */, logger2); } -async function run({ startedAt, logger }) { +async function run(action) { + const startedAt = action.startedAt; + const logger2 = action.logger; let uploadResults = void 0; let runStats = void 0; let config = void 0; - let trapCacheCleanupTelemetry = void 0; let trapCacheUploadTime = void 0; let dbCreationTimings = void 0; let didUploadTrapCaches = false; let dependencyCacheResults; let databaseUploadResults = []; try { - initializeEnvironment(getActionVersion()); + action.env.initialise(getActionVersion()); persistInputs(); const statusReportBase = await createStatusReportBase( "finish" /* Analyze */, "starting", startedAt, config, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { await sendStatusReport(statusReportBase); } - config = await getConfig(getTemporaryDirectory(), logger); + config = await getConfig(getTemporaryDirectory(), logger2); if (config === void 0) { throw new ConfigurationError( "Config file could not be found at expected location. Has the 'init' action been called?" ); } - const codeql = await getCodeQL(logger, config.codeQLCmd); + const codeql = await getCodeQL(logger2, config.codeQLCmd); if (hasBadExpectErrorInput()) { throw new ConfigurationError( "`expect-error` input parameter is for internal use only. It should only be set by codeql-action or a fork." ); } - if (process.env.CODEQL_PROXY_HOST === "" && !await codeQlVersionAtLeast(codeql, "2.20.7")) { - delete process.env.CODEQL_PROXY_HOST; - delete process.env.CODEQL_PROXY_PORT; - delete process.env.CODEQL_PROXY_CA_CERTIFICATE; - } if (getOptionalInput("cleanup-level")) { - logger.info( + logger2.info( "The 'cleanup-level' input is ignored since the CodeQL Action now automatically manages database cleanup. This input can safely be removed from your workflow." ); } + warnIfTrapCacheCleanupEnvVarIsSet(action); const apiDetails = getApiDetails(); const outputDir = getRequiredInput("output"); - core16.exportVariable("CODEQL_ACTION_SARIF_RESULTS_OUTPUT_DIR" /* SARIF_RESULTS_OUTPUT_DIR */, outputDir); + action.env.export("CODEQL_ACTION_SARIF_RESULTS_OUTPUT_DIR" /* SARIF_RESULTS_OUTPUT_DIR */, outputDir); const threads = getThreadsFlag( getOptionalInput("threads") || process.env["CODEQL_THREADS"], - logger + logger2 ); const repositoryNwo = getRepositoryNwo(); const gitHubVersion = await getGitHubVersion(); @@ -156102,15 +189479,19 @@ async function run({ startedAt, logger }) { gitHubVersion, repositoryNwo, getTemporaryDirectory(), - logger + logger2 ); const memory = getMemoryFlag( getOptionalInput("ram") || process.env["CODEQL_RAM"], - logger + logger2 + ); + const checkoutPath = await determineCheckoutPath(action, config); + const diffRangePackDir = await setupDiffInformedQueryRun( + logger2, + checkoutPath ); - const diffRangePackDir = await setupDiffInformedQueryRun(logger); - await warnIfGoInstalledAfterInit(config, logger); - await runAutobuildIfLegacyGoWorkflow(config, logger); + await warnIfGoInstalledAfterInit(config, logger2); + await runAutobuildIfLegacyGoWorkflow(config, logger2); dbCreationTimings = await runFinalize( features, outputDir, @@ -156118,11 +189499,11 @@ async function run({ startedAt, logger }) { memory, codeql, config, - logger + logger2 ); if (getRequiredInput("skip-queries") !== "true") { if (getOptionalInput("add-snippets") !== void 0) { - logger.warning( + logger2.warning( "The `add-snippets` input has been removed and no longer has any effect." ); } @@ -156134,7 +189515,7 @@ async function run({ startedAt, logger }) { getOptionalInput("category"), codeql, config, - logger, + logger2, features ); } @@ -156142,17 +189523,17 @@ async function run({ startedAt, logger }) { for (const language of config.languages) { dbLocations[language] = getCodeQLDatabasePath(config, language); } - core16.setOutput("db-locations", dbLocations); - core16.setOutput("sarif-output", import_path5.default.resolve(outputDir)); + core14.setOutput("db-locations", dbLocations); + core14.setOutput("sarif-output", import_path5.default.resolve(outputDir)); const uploadKind = getUploadValue( getOptionalInput("upload") ); if (runStats) { - const checkoutPath = getRequiredInput("checkout_path"); const category = getOptionalInput("category"); uploadResults = await postProcessAndUploadSarif( - logger, + logger2, features, + config, uploadKind, checkoutPath, outputDir, @@ -156160,47 +189541,50 @@ async function run({ startedAt, logger }) { getOptionalInput("post-processed-sarif-path") ); if (uploadResults["code-scanning" /* CodeScanning */] !== void 0) { - core16.setOutput( + core14.setOutput( "sarif-id", uploadResults["code-scanning" /* CodeScanning */].sarifID ); } if (uploadResults["code-quality" /* CodeQuality */] !== void 0) { - core16.setOutput( + core14.setOutput( "quality-sarif-id", uploadResults["code-quality" /* CodeQuality */].sarifID ); } } else { - logger.info("Not uploading results"); + logger2.info("Not uploading results"); } - await cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger); + await cleanupAndUploadOverlayBaseDatabaseToCache( + codeql, + config, + logger2, + checkoutPath + ); + const actionWithFeatures = extendActionState(action, { features }); databaseUploadResults = await cleanupAndUploadDatabases( + actionWithFeatures, repositoryNwo, codeql, config, apiDetails, - features, - logger - ); - const trapCacheUploadStartTime = import_perf_hooks4.performance.now(); - didUploadTrapCaches = await uploadTrapCaches(codeql, config, logger); - trapCacheUploadTime = import_perf_hooks4.performance.now() - trapCacheUploadStartTime; - trapCacheCleanupTelemetry = await cleanupTrapCaches( - config, - features, - logger + checkoutPath ); + const trapCacheUploadStartTime = import_perf_hooks6.performance.now(); + didUploadTrapCaches = await uploadTrapCaches(codeql, config, logger2); + trapCacheUploadTime = import_perf_hooks6.performance.now() - trapCacheUploadStartTime; if (shouldStoreCache(config.dependencyCachingEnabled)) { dependencyCacheResults = await uploadDependencyCaches( codeql, features, config, - logger + logger2 ); } - if (isInTestMode()) { - logger.debug("In test mode. Waiting for processing is disabled."); + if (shouldSkipSarifUpload()) { + logger2.debug( + "SARIF upload is disabled and nothing was uploaded, so we do not need to wait for processing to finish." + ); } else if (uploadResults?.["code-scanning" /* CodeScanning */] !== void 0 && getRequiredInput("wait-for-processing") === "true") { await waitForProcessing( getRepositoryNwo(), @@ -156209,15 +189593,15 @@ async function run({ startedAt, logger }) { ); } if (getOptionalInput("expect-error") === "true") { - core16.setFailed( + core14.setFailed( `expect-error input was set to true but no error was thrown.` ); } - core16.exportVariable("CODEQL_ACTION_ANALYZE_DID_COMPLETE_SUCCESSFULLY" /* ANALYZE_DID_COMPLETE_SUCCESSFULLY */, "true"); + action.env.export("CODEQL_ACTION_ANALYZE_DID_COMPLETE_SUCCESSFULLY" /* ANALYZE_DID_COMPLETE_SUCCESSFULLY */, "true"); } catch (unwrappedError) { const error3 = wrapError(unwrappedError); if (getOptionalInput("expect-error") !== "true" || hasBadExpectErrorInput()) { - core16.setFailed(error3.message); + core14.setFailed(error3.message); } await sendStatusReport2( startedAt, @@ -156227,10 +189611,9 @@ async function run({ startedAt, logger }) { trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, - trapCacheCleanupTelemetry, dependencyCacheResults, databaseUploadResults, - logger + logger2 ); return; } @@ -156246,10 +189629,9 @@ async function run({ startedAt, logger }) { trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, - trapCacheCleanupTelemetry, dependencyCacheResults, databaseUploadResults, - logger + logger2 ); } else if (runStats !== void 0) { await sendStatusReport2( @@ -156260,10 +189642,9 @@ async function run({ startedAt, logger }) { trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, - trapCacheCleanupTelemetry, dependencyCacheResults, databaseUploadResults, - logger + logger2 ); } else { await sendStatusReport2( @@ -156274,10 +189655,9 @@ async function run({ startedAt, logger }) { trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, - trapCacheCleanupTelemetry, dependencyCacheResults, databaseUploadResults, - logger + logger2 ); } } @@ -156291,15 +189671,15 @@ async function runWrapper() { } // src/analyze-action-post.ts -var fs27 = __toESM(require("fs")); -var core18 = __toESM(require_core()); +var fs29 = __toESM(require("fs")); +var core16 = __toESM(require_core()); // src/debug-artifacts.ts -var fs26 = __toESM(require("fs")); +var fs28 = __toESM(require("fs")); var path23 = __toESM(require("path")); var artifact = __toESM(require_artifact2()); var artifactLegacy = __toESM(require_artifact_client2()); -var core17 = __toESM(require_core()); +var core15 = __toESM(require_core()); // node_modules/archiver/lib/core.js var import_fs2 = require("fs"); @@ -156310,7 +189690,7 @@ function isStream(stream2, { checkOpen = true } = {}) { } // node_modules/readdir-glob/dist/index.mjs -var fs24 = __toESM(require("fs"), 1); +var fs26 = __toESM(require("fs"), 1); var import_events = require("events"); // node_modules/readdir-glob/node_modules/balanced-match/dist/esm/index.js @@ -156384,6 +189764,8 @@ var commaPattern = /\\,/g; var periodPattern = /\\\./g; var EXPANSION_MAX = 1e5; var EXPANSION_MAX_LENGTH = 4e6; +var EXPANSION_MAX_DEPTH = 1e3; +var EXPANSION_MAX_REWRITES = 1e3; function numeric(str) { return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0); } @@ -156393,36 +189775,44 @@ function escapeBraces(str) { function unescapeBraces(str) { return str.replace(escSlashPattern, "\\").replace(escOpenPattern, "{").replace(escClosePattern, "}").replace(escCommaPattern, ",").replace(escPeriodPattern, "."); } -function parseCommaParts(str) { - if (!str) { - return [""]; +function pushAll(target, items) { + for (let i = 0; i < items.length; i++) { + target.push(items[i]); } +} +function parseCommaParts(str) { 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; + let carry = ""; + for (; ; ) { + const m = balanced("{", "}", str); + if (!m) { + const tail = str.split(","); + tail[0] = carry + tail[0]; + pushAll(parts, tail); + return parts; + } + const { pre, body, post } = m; + const p = pre.split(","); + p[0] = carry + p[0]; + p[p.length - 1] += "{" + body + "}"; + if (!post.length) { + pushAll(parts, p); + return parts; + } + carry = p.pop(); + pushAll(parts, p); + str = post; + } } function expand2(str, options = {}) { if (!str) { return []; } - const { max = EXPANSION_MAX, maxLength = EXPANSION_MAX_LENGTH } = options; + const { max = EXPANSION_MAX, maxLength = EXPANSION_MAX_LENGTH, maxDepth = EXPANSION_MAX_DEPTH, maxRewrites = EXPANSION_MAX_REWRITES } = options; if (str.slice(0, 2) === "{}") { str = "\\{\\}" + str.slice(2); } - return expand_(escapeBraces(str), max, maxLength, true).map(unescapeBraces); + return expand_(escapeBraces(str), max, maxLength, maxDepth, 0, maxRewrites, true).map(unescapeBraces); } function embrace(str) { return "{" + str + "}"; @@ -156500,8 +189890,12 @@ function expandSequence(body, isAlphaSequence, max, maxLength) { } return N; } -function expand_(str, max, maxLength, isTop) { +function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { + if (depth > maxDepth) { + return [str]; + } let acc = [""]; + let rewrites = 0; let dropEmpties = false; let firstGroup = true; for (; ; ) { @@ -156523,7 +189917,8 @@ function expand_(str, max, maxLength, isTop) { const isSequence = isNumericSequence || isAlphaSequence; const isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { - if (m.post.match(/,(?!,).*\}/)) { + if (rewrites < maxRewrites && m.post.match(/,(?!,).*\}/)) { + rewrites++; str = m.pre + "{" + m.body + escClose + m.post; isTop = true; continue; @@ -156540,7 +189935,7 @@ function expand_(str, max, maxLength, isTop) { } else { let n = parseCommaParts(m.body); if (n.length === 1 && n[0] !== void 0) { - n = expand_(n[0], max, maxLength, false).map(embrace); + n = expand_(n[0], max, maxLength, maxDepth, depth + 1, maxRewrites, false).map(embrace); if (n.length === 1) { acc = combine(acc, pre + n[0], [""], max, maxLength, dropEmpties && !m.post.length); if (!m.post.length) @@ -156558,7 +189953,7 @@ function expand_(str, max, maxLength, isTop) { values = []; let valuesLength = 0; outer: for (let j = 0; j < n.length; j++) { - const expanded = expand_(n[j], max, maxLength, false); + const expanded = expand_(n[j], max, maxLength, maxDepth, depth + 1, maxRewrites, false); for (let k = 0; k < expanded.length; k++) { const v = expanded[k]; if (dropsEmpties && !v) @@ -156708,7 +190103,7 @@ var unescape2 = (s, { windowsPathsNoEscape = false, magicalBraces = true } = {}) }; // node_modules/readdir-glob/node_modules/minimatch/dist/esm/ast.js -var _a; +var _a5; var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]); var isExtglobType = (c) => types.has(c); var isExtglobAST = (c) => isExtglobType(c.type); @@ -156858,7 +190253,7 @@ var AST = class { for (const p of parts) { if (p === "") continue; - if (typeof p !== "string" && !(p instanceof _a && p.#parent === this)) { + if (typeof p !== "string" && !(p instanceof _a5 && p.#parent === this)) { throw new Error("invalid part: " + p); } this.#parts.push(p); @@ -156883,7 +190278,7 @@ var AST = class { const p = this.#parent; for (let i = 0; i < this.#parentIndex; i++) { const pp = p.#parts[i]; - if (!(pp instanceof _a && pp.type === "!")) { + if (!(pp instanceof _a5 && pp.type === "!")) { return false; } } @@ -156908,7 +190303,7 @@ var AST = class { this.push(part.clone(this)); } clone(parent) { - const c = new _a(this.type, parent); + const c = new _a5(this.type, parent); for (const p of this.#parts) { c.copyIn(p); } @@ -156951,8 +190346,8 @@ var AST = class { if (doRecurse) { ast.push(acc2); acc2 = ""; - const ext2 = new _a(c, ast); - i2 = _a.#parseAST(str, ext2, i2, opt, extDepth + 1); + const ext2 = new _a5(c, ast); + i2 = _a5.#parseAST(str, ext2, i2, opt, extDepth + 1); ast.push(ext2); continue; } @@ -156962,7 +190357,7 @@ var AST = class { return i2; } let i = pos + 1; - let part = new _a(null, ast); + let part = new _a5(null, ast); const parts = []; let acc = ""; while (i < str.length) { @@ -156995,16 +190390,16 @@ var AST = class { const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1; part.push(acc); acc = ""; - const ext2 = new _a(c, part); + const ext2 = new _a5(c, part); part.push(ext2); - i = _a.#parseAST(str, ext2, i, opt, extDepth + depthAdd); + i = _a5.#parseAST(str, ext2, i, opt, extDepth + depthAdd); continue; } if (c === "|") { part.push(acc); acc = ""; parts.push(part); - part = new _a(null, ast); + part = new _a5(null, ast); continue; } if (c === ")") { @@ -157041,7 +190436,7 @@ var AST = class { } #adoptWithSpace(child, index2) { const gc = child.#parts[0]; - const blank = new _a(null, gc, this.options); + const blank = new _a5(null, gc, this.options); blank.#parts.push(""); gc.push(blank); this.#adopt(child, index2); @@ -157086,8 +190481,8 @@ var AST = class { this.#emptyExt = false; } static fromGlob(pattern, options = {}) { - const ast = new _a(null, void 0, options); - _a.#parseAST(pattern, ast, 0, options, 0); + const ast = new _a5(null, void 0, options); + _a5.#parseAST(pattern, ast, 0, options, 0); return ast; } // returns the regular expression if there's magic, or the unescaped @@ -157188,7 +190583,7 @@ var AST = class { if (!isExtglobAST(this)) { const noEmpty = this.isStart() && this.isEnd() && !this.#parts.some((s) => typeof s !== "string"); const src = this.#parts.map((p) => { - const [re, _2, hasMagic, uflag] = typeof p === "string" ? _a.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot); + const [re, _2, hasMagic, uflag] = typeof p === "string" ? _a5.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot); this.#hasMagic = this.#hasMagic || hasMagic; this.#uflag = this.#uflag || uflag; return re; @@ -157349,7 +190744,7 @@ var AST = class { return [re, unescape2(glob2), !!hasMagic, uflag]; } }; -_a = AST; +_a5 = AST; // node_modules/readdir-glob/node_modules/minimatch/dist/esm/escape.js var escape2 = (s, { windowsPathsNoEscape = false, magicalBraces = false } = {}) => { @@ -157799,10 +191194,10 @@ var Minimatch = class { let ai = 0; let bi = 0; let result = []; - let which9 = ""; + let which10 = ""; while (ai < a.length && bi < b.length) { if (a[ai] === b[bi]) { - result.push(which9 === "b" ? b[bi] : a[ai]); + result.push(which10 === "b" ? b[bi] : a[ai]); ai++; bi++; } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) { @@ -157812,16 +191207,16 @@ var Minimatch = class { result.push(b[bi]); bi++; } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") { - if (which9 === "b") + if (which10 === "b") return false; - which9 = "a"; + which10 = "a"; result.push(a[ai]); ai++; bi++; } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") { - if (which9 === "a") + if (which10 === "a") return false; - which9 = "b"; + which10 = "b"; result.push(b[bi]); ai++; bi++; @@ -158172,7 +191567,7 @@ minimatch.unescape = unescape2; var import_path6 = require("path"); function readdir2(dir, strict) { return new Promise((resolve$1, reject) => { - fs24.readdir(dir, { withFileTypes: true }, (err, files) => { + fs26.readdir(dir, { withFileTypes: true }, (err, files) => { if (err) switch (err.code) { case "ENOTDIR": if (strict) reject(err); @@ -158195,7 +191590,7 @@ function readdir2(dir, strict) { } function getStat(file, followSymlinks) { return new Promise((resolve$1) => { - const statFunc = followSymlinks ? fs24.stat : fs24.lstat; + const statFunc = followSymlinks ? fs26.stat : fs26.lstat; statFunc(file, (err, stats) => { if (err) switch (err.code) { case "ENOENT": @@ -158365,7 +191760,7 @@ var import_async = __toESM(require_async(), 1); var import_path7 = require("path"); // node_modules/archiver/lib/error.js -var import_util34 = __toESM(require("util"), 1); +var import_util37 = __toESM(require("util"), 1); var ERROR_CODES = { ABORTED: "archive was aborted", DIRECTORYDIRPATHREQUIRED: "diretory dirpath argument must be a non-empty string value", @@ -158390,7 +191785,7 @@ function ArchiverError(code, data) { this.code = code; this.data = data; } -import_util34.default.inherits(ArchiverError, Error); +import_util37.default.inherits(ArchiverError, Error); // node_modules/archiver/lib/core.js var import_readable_stream2 = __toESM(require_ours(), 1); @@ -159081,11 +192476,11 @@ var Archiver = class extends import_readable_stream2.Transform { this._finalize(); } var self2 = this; - return new Promise(function(resolve14, reject) { + return new Promise(function(resolve15, reject) { var errored; self2._module.on("end", function() { if (!errored) { - resolve14(); + resolve15(); } }); self2._module.on("error", function(err) { @@ -160627,9 +194022,9 @@ function ensureBuffer(input) { } } function bufferizeInt(num) { - const tmp = ensureBuffer(4); - tmp.writeInt32BE(num, 0); - return tmp; + const tmp2 = ensureBuffer(4); + tmp2.writeInt32BE(num, 0); + return tmp2; } function _crc32(buf, previous) { buf = ensureBuffer(buf); @@ -160665,8 +194060,8 @@ var ZipArchive = class extends Archiver { }; // src/artifact-scanner.ts -var fs25 = __toESM(require("fs")); -var os6 = __toESM(require("os")); +var fs27 = __toESM(require("fs")); +var os7 = __toESM(require("os")); var path22 = __toESM(require("path")); var exec = __toESM(require_exec()); var GITHUB_PAT_CLASSIC_PATTERN = { @@ -160709,28 +194104,28 @@ function isAuthToken(value, patterns = GITHUB_TOKEN_PATTERNS) { } return void 0; } -function scanFileForTokens(filePath, relativePath2, logger) { +function scanFileForTokens(filePath, relativePath2, logger2) { const findings = []; try { - const content = fs25.readFileSync(filePath, "utf8"); + const content = fs27.readFileSync(filePath, "utf8"); for (const { type, pattern } of GITHUB_TOKEN_PATTERNS) { const matches = content.match(pattern); if (matches) { for (let i = 0; i < matches.length; i++) { findings.push({ tokenType: type, filePath: relativePath2 }); } - logger.debug(`Found ${matches.length} ${type}(s) in ${relativePath2}`); + logger2.debug(`Found ${matches.length} ${type}(s) in ${relativePath2}`); } } return findings; } catch (e) { - logger.debug( + logger2.debug( `Could not scan file ${filePath} for tokens: ${getErrorMessage(e)}` ); return []; } } -async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, logger, depth = 0) { +async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, logger2, depth = 0) { const MAX_DEPTH = 10; if (depth > MAX_DEPTH) { throw new Error( @@ -160745,17 +194140,17 @@ async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, log findings: [] }; try { - const tempExtractDir = fs25.mkdtempSync( + const tempExtractDir = fs27.mkdtempSync( path22.join(extractDir, `extract-${depth}-`) ); const fileName = path22.basename(archivePath).toLowerCase(); if (fileName.endsWith(".tar.gz") || fileName.endsWith(".tgz")) { - logger.debug(`Extracting tar.gz file: ${archivePath}`); + logger2.debug(`Extracting tar.gz file: ${archivePath}`); await exec.exec("tar", ["-xzf", archivePath, "-C", tempExtractDir], { silent: true }); } else if (fileName.endsWith(".tar.zst")) { - logger.debug(`Extracting tar.zst file: ${archivePath}`); + logger2.debug(`Extracting tar.zst file: ${archivePath}`); await exec.exec( "tar", ["--zstd", "-xf", archivePath, "-C", tempExtractDir], @@ -160764,7 +194159,7 @@ async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, log } ); } else if (fileName.endsWith(".zst")) { - logger.debug(`Extracting zst file: ${archivePath}`); + logger2.debug(`Extracting zst file: ${archivePath}`); const outputFile = path22.join( tempExtractDir, path22.basename(archivePath, ".zst") @@ -160773,17 +194168,17 @@ async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, log silent: true }); } else if (fileName.endsWith(".gz")) { - logger.debug(`Extracting gz file: ${archivePath}`); + logger2.debug(`Extracting gz file: ${archivePath}`); const outputFile = path22.join( tempExtractDir, path22.basename(archivePath, ".gz") ); await exec.exec("gunzip", ["-c", archivePath], { - outStream: fs25.createWriteStream(outputFile), + outStream: fs27.createWriteStream(outputFile), silent: true }); } else if (fileName.endsWith(".zip")) { - logger.debug(`Extracting zip file: ${archivePath}`); + logger2.debug(`Extracting zip file: ${archivePath}`); await exec.exec( "unzip", ["-q", "-o", archivePath, "-d", tempExtractDir], @@ -160795,20 +194190,20 @@ async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, log const scanResult = await scanDirectory( tempExtractDir, relativeArchivePath, - logger, + logger2, depth + 1 ); result.scannedFiles += scanResult.scannedFiles; result.findings.push(...scanResult.findings); - fs25.rmSync(tempExtractDir, { recursive: true, force: true }); + fs27.rmSync(tempExtractDir, { recursive: true, force: true }); } catch (e) { - logger.debug( + logger2.debug( `Could not extract or scan archive file ${archivePath}: ${getErrorMessage(e)}` ); } return result; } -async function scanFile(fullPath, relativePath2, extractDir, logger, depth = 0) { +async function scanFile(fullPath, relativePath2, extractDir, logger2, depth = 0) { const result = { scannedFiles: 1, findings: [] @@ -160820,22 +194215,22 @@ async function scanFile(fullPath, relativePath2, extractDir, logger, depth = 0) fullPath, relativePath2, extractDir, - logger, + logger2, depth ); result.scannedFiles += archiveResult.scannedFiles; result.findings.push(...archiveResult.findings); } - const fileFindings = scanFileForTokens(fullPath, relativePath2, logger); + const fileFindings = scanFileForTokens(fullPath, relativePath2, logger2); result.findings.push(...fileFindings); return result; } -async function scanDirectory(dirPath, baseRelativePath, logger, depth = 0) { +async function scanDirectory(dirPath, baseRelativePath, logger2, depth = 0) { const result = { scannedFiles: 0, findings: [] }; - const entries = fs25.readdirSync(dirPath, { withFileTypes: true }); + const entries = fs27.readdirSync(dirPath, { withFileTypes: true }); for (const entry of entries) { const fullPath = path22.join(dirPath, entry.name); const relativePath2 = path22.join(baseRelativePath, entry.name); @@ -160843,7 +194238,7 @@ async function scanDirectory(dirPath, baseRelativePath, logger, depth = 0) { const subResult = await scanDirectory( fullPath, relativePath2, - logger, + logger2, depth ); result.scannedFiles += subResult.scannedFiles; @@ -160853,7 +194248,7 @@ async function scanDirectory(dirPath, baseRelativePath, logger, depth = 0) { fullPath, relativePath2, path22.dirname(fullPath), - logger, + logger2, depth ); result.scannedFiles += fileResult.scannedFiles; @@ -160862,21 +194257,21 @@ async function scanDirectory(dirPath, baseRelativePath, logger, depth = 0) { } return result; } -async function scanArtifactsForTokens(filesToScan, logger) { - logger.info( +async function scanArtifactsForTokens(filesToScan, logger2) { + logger2.info( "Starting best-effort check for potential GitHub tokens in debug artifacts (for testing purposes only)..." ); const result = { scannedFiles: 0, findings: [] }; - const tempScanDir = fs25.mkdtempSync(path22.join(os6.tmpdir(), "artifact-scan-")); + const tempScanDir = fs27.mkdtempSync(path22.join(os7.tmpdir(), "artifact-scan-")); try { for (const filePath of filesToScan) { - const stats = fs25.statSync(filePath); + const stats = fs27.statSync(filePath); const fileName = path22.basename(filePath); if (stats.isDirectory()) { - const dirResult = await scanDirectory(filePath, fileName, logger); + const dirResult = await scanDirectory(filePath, fileName, logger2); result.scannedFiles += dirResult.scannedFiles; result.findings.push(...dirResult.findings); } else if (stats.isFile()) { @@ -160884,7 +194279,7 @@ async function scanArtifactsForTokens(filesToScan, logger) { filePath, fileName, tempScanDir, - logger + logger2 ); result.scannedFiles += fileResult.scannedFiles; result.findings.push(...fileResult.findings); @@ -160902,7 +194297,7 @@ async function scanArtifactsForTokens(filesToScan, logger) { const tokenTypesSummary = Array.from(tokenTypesCounts.entries()).map(([type, count]) => `${count} ${type}${count > 1 ? "s" : ""}`).join(", "); const baseSummary = `scanned ${result.scannedFiles} files, found ${result.findings.length} potential token(s) in ${filesWithTokens.size} file(s)`; const summaryWithTypes = tokenTypesSummary ? `${baseSummary} (${tokenTypesSummary})` : baseSummary; - logger.info(`Artifact check complete: ${summaryWithTypes}`); + logger2.info(`Artifact check complete: ${summaryWithTypes}`); if (result.findings.length > 0) { const fileList = Array.from(filesWithTokens).join(", "); throw new Error( @@ -160911,9 +194306,9 @@ async function scanArtifactsForTokens(filesToScan, logger) { } } finally { try { - fs25.rmSync(tempScanDir, { recursive: true, force: true }); + fs27.rmSync(tempScanDir, { recursive: true, force: true }); } catch (e) { - logger.debug( + logger2.debug( `Could not clean up temporary scan directory: ${getErrorMessage(e)}` ); } @@ -160924,35 +194319,34 @@ async function scanArtifactsForTokens(filesToScan, logger) { function sanitizeArtifactName(name) { return name.replace(/[^a-zA-Z0-9_-]+/g, ""); } -async function uploadCombinedSarifArtifacts(logger, gitHubVariant, codeQlVersion) { +async function uploadCombinedSarifArtifacts(logger2, gitHubVariant) { const tempDir = getTemporaryDirectory(); if (process.env["CODEQL_ACTION_DEBUG_COMBINED_SARIF"] === "true") { await withGroup("Uploading combined SARIF debug artifact", async () => { - logger.info( + logger2.info( "Uploading available combined SARIF files as Actions debugging artifact..." ); const baseTempDir = path23.resolve(tempDir, "combined-sarif"); const toUpload = []; - if (fs26.existsSync(baseTempDir)) { - const outputDirs = fs26.readdirSync(baseTempDir); + if (fs28.existsSync(baseTempDir)) { + const outputDirs = fs28.readdirSync(baseTempDir); for (const outputDir of outputDirs) { - const sarifFiles = fs26.readdirSync(path23.resolve(baseTempDir, outputDir)).filter((f) => path23.extname(f) === ".sarif"); + const sarifFiles = fs28.readdirSync(path23.resolve(baseTempDir, outputDir)).filter((f) => path23.extname(f) === ".sarif"); for (const sarifFile of sarifFiles) { toUpload.push(path23.resolve(baseTempDir, outputDir, sarifFile)); } } } try { - await uploadDebugArtifacts( - logger, + await uploadArtifacts( + logger2, toUpload, baseTempDir, "combined-sarif-artifacts", - gitHubVariant, - codeQlVersion + gitHubVariant ); } catch (e) { - logger.warning( + logger2.warning( `Failed to upload combined SARIF files as Actions debugging artifact. Reason: ${getErrorMessage( e )}` @@ -160961,25 +194355,25 @@ async function uploadCombinedSarifArtifacts(logger, gitHubVariant, codeQlVersion }); } } -function tryPrepareSarifDebugArtifact(config, language, logger) { +function tryPrepareSarifDebugArtifact(config, language, logger2) { try { const analyzeActionOutputDir = process.env["CODEQL_ACTION_SARIF_RESULTS_OUTPUT_DIR" /* SARIF_RESULTS_OUTPUT_DIR */]; - if (analyzeActionOutputDir !== void 0 && fs26.existsSync(analyzeActionOutputDir) && fs26.lstatSync(analyzeActionOutputDir).isDirectory()) { + if (analyzeActionOutputDir !== void 0 && fs28.existsSync(analyzeActionOutputDir) && fs28.lstatSync(analyzeActionOutputDir).isDirectory()) { const sarifFile = path23.resolve( analyzeActionOutputDir, `${language}.sarif` ); - if (fs26.existsSync(sarifFile)) { + if (fs28.existsSync(sarifFile)) { const sarifInDbLocation = path23.resolve( config.dbLocation, `${language}.sarif` ); - fs26.copyFileSync(sarifFile, sarifInDbLocation); + fs28.copyFileSync(sarifFile, sarifInDbLocation); return sarifInDbLocation; } } } catch (e) { - logger.warning( + logger2.warning( `Failed to find SARIF results path for ${language}. Reason: ${getErrorMessage( e )}` @@ -160987,20 +194381,20 @@ function tryPrepareSarifDebugArtifact(config, language, logger) { } return void 0; } -async function tryBundleDatabase(codeql, config, language, logger) { +async function tryBundleDatabase(codeql, config, language, logger2) { try { - if (dbIsFinalized(config, language, logger)) { + if (dbIsFinalized(config, language, logger2)) { try { return await createDatabaseBundleCli(codeql, config, language); } catch (e) { - logger.warning( + logger2.warning( `Failed to bundle database for ${language} using the CLI. Falling back to a partial bundle. Reason: ${getErrorMessage(e)}` ); } } return await createPartialDatabaseBundle(config, language); } catch (e) { - logger.warning( + logger2.warning( `Failed to bundle database for ${language}. Reason: ${getErrorMessage( e )}` @@ -161008,52 +194402,52 @@ async function tryBundleDatabase(codeql, config, language, logger) { return void 0; } } -async function tryUploadAllAvailableDebugArtifacts(codeql, config, logger, codeQlVersion) { +async function tryUploadAllAvailableDebugArtifacts(codeql, config, logger2) { const filesToUpload = []; try { for (const language of config.languages) { await withGroup(`Uploading debug artifacts for ${language}`, async () => { - logger.info("Preparing SARIF result debug artifact..."); + logger2.info("Preparing SARIF result debug artifact..."); const sarifResultDebugArtifact = tryPrepareSarifDebugArtifact( config, language, - logger + logger2 ); if (sarifResultDebugArtifact) { filesToUpload.push(sarifResultDebugArtifact); - logger.info("SARIF result debug artifact ready for upload."); + logger2.info("SARIF result debug artifact ready for upload."); } - logger.info("Preparing database logs debug artifact..."); + logger2.info("Preparing database logs debug artifact..."); const databaseDirectory = getCodeQLDatabasePath(config, language); const logsDirectory = path23.resolve(databaseDirectory, "log"); if (doesDirectoryExist(logsDirectory)) { filesToUpload.push(...listFolder(logsDirectory)); - logger.info("Database logs debug artifact ready for upload."); + logger2.info("Database logs debug artifact ready for upload."); } - logger.info("Preparing database cluster logs debug artifact..."); + logger2.info("Preparing database cluster logs debug artifact..."); const multiLanguageTracingLogsDirectory = path23.resolve( config.dbLocation, "log" ); if (doesDirectoryExist(multiLanguageTracingLogsDirectory)) { filesToUpload.push(...listFolder(multiLanguageTracingLogsDirectory)); - logger.info("Database cluster logs debug artifact ready for upload."); + logger2.info("Database cluster logs debug artifact ready for upload."); } - logger.info("Preparing database bundle debug artifact..."); + logger2.info("Preparing database bundle debug artifact..."); const databaseBundle = await tryBundleDatabase( codeql, config, language, - logger + logger2 ); if (databaseBundle) { filesToUpload.push(databaseBundle); - logger.info("Database bundle debug artifact ready for upload."); + logger2.info("Database bundle debug artifact ready for upload."); } }); } } catch (e) { - logger.warning( + logger2.warning( `Failed to prepare debug artifacts. Reason: ${getErrorMessage(e)}` ); return; @@ -161061,17 +194455,16 @@ async function tryUploadAllAvailableDebugArtifacts(codeql, config, logger, codeQ try { await withGroup( "Uploading debug artifacts", - async () => uploadDebugArtifacts( - logger, + async () => uploadArtifacts( + logger2, filesToUpload, config.dbLocation, config.debugArtifactName, - config.gitHubVersion.type, - codeQlVersion + config.gitHubVersion.type ) ); } catch (e) { - logger.warning( + logger2.warning( `Failed to upload debug artifacts. Reason: ${getErrorMessage(e)}` ); } @@ -161081,40 +194474,30 @@ function getArtifactSuffix(matrix) { if (matrix) { try { const matrixObject = JSON.parse(matrix); - if (isObject(matrixObject)) { + if (isObject2(matrixObject)) { for (const matrixKey of Object.keys(matrixObject).sort()) suffix += `-${matrixObject[matrixKey]}`; } else { - core17.warning("User-specified `matrix` input is not an object."); + core15.warning("User-specified `matrix` input is not an object."); } } catch { - core17.warning( + core15.warning( "Could not parse user-specified `matrix` input into JSON. The debug artifact will not be named with the user's `matrix` input." ); } } return suffix; } -async function uploadDebugArtifacts(logger, toUpload, rootDir, artifactName, ghVariant, codeQlVersion) { - const uploadSupported = isSafeArtifactUpload(codeQlVersion); - if (!uploadSupported) { - core17.info( - `Skipping debug artifact upload because the current CLI does not support safe upload. Please upgrade to CLI v${SafeArtifactUploadVersion} or later.` - ); - return "upload-not-supported"; - } - return uploadArtifacts(logger, toUpload, rootDir, artifactName, ghVariant); -} -async function uploadArtifacts(logger, toUpload, rootDir, artifactName, ghVariant) { +async function uploadArtifacts(logger2, toUpload, rootDir, artifactName, ghVariant) { if (toUpload.length === 0) { return "no-artifacts-to-upload"; } if (isInTestMode()) { - await scanArtifactsForTokens(toUpload, logger); - core17.exportVariable("CODEQL_ACTION_ARTIFACT_SCAN_FINISHED", "true"); + await scanArtifactsForTokens(toUpload, logger2); + exportEnvVar("CODEQL_ACTION_ARTIFACT_SCAN_FINISHED", "true"); } const suffix = getArtifactSuffix(getOptionalInput("matrix")); - const artifactUploader = await getArtifactUploaderClient(logger, ghVariant); + const artifactUploader = await getArtifactUploaderClient(logger2, ghVariant); try { await artifactUploader.uploadArtifact( sanitizeArtifactName(`${artifactName}${suffix}`), @@ -161127,18 +194510,18 @@ async function uploadArtifacts(logger, toUpload, rootDir, artifactName, ghVarian ); return "upload-successful"; } catch (e) { - core17.warning(`Failed to upload debug artifacts: ${e}`); + core15.warning(`Failed to upload debug artifacts: ${e}`); return "upload-failed"; } } -async function getArtifactUploaderClient(logger, ghVariant) { +async function getArtifactUploaderClient(logger2, ghVariant) { if (ghVariant === "GitHub Enterprise Server" /* GHES */) { - logger.info( + logger2.info( "Debug artifacts can be consumed with `actions/download-artifact@v3` because the `v4` version is not yet compatible on GHES." ); return artifactLegacy.create(); } else { - logger.info( + logger2.info( "Debug artifacts can be consumed with `actions/download-artifact@v4`." ); return new artifact.DefaultArtifactClient(); @@ -161150,13 +194533,13 @@ async function createPartialDatabaseBundle(config, language) { config.dbLocation, `${config.debugDatabaseName}-${language}-partial.zip` ); - core17.info( + core15.info( `${config.debugDatabaseName}-${language} is not finalized. Uploading partial database bundle at ${databaseBundlePath}...` ); - if (fs26.existsSync(databaseBundlePath)) { - await fs26.promises.rm(databaseBundlePath, { force: true }); + if (fs28.existsSync(databaseBundlePath)) { + await fs28.promises.rm(databaseBundlePath, { force: true }); } - const output = fs26.createWriteStream(databaseBundlePath); + const output = fs28.createWriteStream(databaseBundlePath); const zip = new ZipArchive(); zip.on("error", (err) => { throw err; @@ -161185,22 +194568,19 @@ async function createDatabaseBundleCli(codeql, config, language) { // src/analyze-action-post.ts async function runWrapper2() { try { - restoreInputs(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); + restoreInputs(logger2); const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); if (process.env["CODEQL_ACTION_INIT_HAS_RUN" /* INIT_ACTION_HAS_RUN */] === "true") { const config = await getConfig( getTemporaryDirectory(), - logger + logger2 ); if (config !== void 0) { - const codeql = await getCodeQL(logger, config.codeQLCmd); - const version = await codeql.getVersion(); await uploadCombinedSarifArtifacts( - logger, - config.gitHubVersion.type, - version.version + logger2, + config.gitHubVersion.type ); } } @@ -161209,35 +194589,35 @@ async function runWrapper2() { getCsharpTempDependencyDir() ]; for (const tempDependencyDir of tempDependencyDirs) { - if (fs27.existsSync(tempDependencyDir)) { + if (fs29.existsSync(tempDependencyDir)) { try { - fs27.rmSync(tempDependencyDir, { recursive: true }); + fs29.rmSync(tempDependencyDir, { recursive: true }); } catch (error3) { - logger.info( + logger2.info( `Failed to remove temporary dependencies directory: ${getErrorMessage(error3)}` ); } } } } catch (error3) { - core18.setFailed( + core16.setFailed( `analyze post-action step failed: ${getErrorMessage(error3)}` ); } } // src/autobuild-action.ts -var core19 = __toESM(require_core()); -async function sendCompletedStatusReport(config, logger, startedAt, allLanguages, failingLanguage, cause) { - initializeEnvironment(getActionVersion()); +var core17 = __toESM(require_core()); +async function sendCompletedStatusReport(env, config, logger2, startedAt, allLanguages, failingLanguage, cause) { + env.initialise(getActionVersion()); const status = getActionsStatus(cause, failingLanguage); const statusReportBase = await createStatusReportBase( "autobuild" /* Autobuild */, status, startedAt, config, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, cause?.message, cause?.stack ); @@ -161250,7 +194630,11 @@ async function sendCompletedStatusReport(config, logger, startedAt, allLanguages await sendStatusReport(statusReport); } } -async function run2({ startedAt, logger }) { +async function run2({ + startedAt, + env, + logger: logger2 +}) { let config; let currentLanguage; let languages; @@ -161260,45 +194644,46 @@ async function run2({ startedAt, logger }) { "starting", startedAt, config, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { await sendStatusReport(statusReportBase); } const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); checkActionVersion(getActionVersion(), gitHubVersion); - config = await getConfig(getTemporaryDirectory(), logger); + config = await getConfig(getTemporaryDirectory(), logger2); if (config === void 0) { throw new ConfigurationError( "Config file could not be found at expected location. Has the 'init' action been called?" ); } - const codeql = await getCodeQL(logger, config.codeQLCmd); - languages = await determineAutobuildLanguages(codeql, config, logger); + const codeql = await getCodeQL(logger2, config.codeQLCmd); + languages = await determineAutobuildLanguages(codeql, config, logger2); if (languages !== void 0) { const workingDirectory = getOptionalInput("working-directory"); if (workingDirectory) { - logger.info( + logger2.info( `Changing autobuilder working directory to ${workingDirectory}` ); process.chdir(workingDirectory); } for (const language of languages) { currentLanguage = language; - await runAutobuild(config, language, logger); + await runAutobuild(config, language, logger2); } } - await endTracingForCluster(codeql, config, logger); + await endTracingForCluster(codeql, config, logger2); } catch (unwrappedError) { const error3 = wrapError(unwrappedError); - core19.setFailed( + core17.setFailed( `We were unable to automatically build your code. Please replace the call to the autobuild action with your custom build steps. ${error3.message}` ); await sendCompletedStatusReport( + env, config, - logger, + logger2, startedAt, languages ?? [], currentLanguage, @@ -161306,8 +194691,14 @@ async function run2({ startedAt, logger }) { ); return; } - core19.exportVariable("CODEQL_ACTION_AUTOBUILD_DID_COMPLETE_SUCCESSFULLY" /* AUTOBUILD_DID_COMPLETE_SUCCESSFULLY */, "true"); - await sendCompletedStatusReport(config, logger, startedAt, languages ?? []); + env.export("CODEQL_ACTION_AUTOBUILD_DID_COMPLETE_SUCCESSFULLY" /* AUTOBUILD_DID_COMPLETE_SUCCESSFULLY */, "true"); + await sendCompletedStatusReport( + env, + config, + logger2, + startedAt, + languages ?? [] + ); } var autobuild = { name: "autobuild" /* Autobuild */, @@ -161318,11 +194709,11 @@ async function runWrapper3() { } // src/init-action.ts -var fs29 = __toESM(require("fs")); +var fs31 = __toESM(require("fs")); var path25 = __toESM(require("path")); -var core21 = __toESM(require_core()); -var io7 = __toESM(require_io()); -var semver10 = __toESM(require_semver2()); +var core19 = __toESM(require_core()); +var io8 = __toESM(require_io()); +var semver12 = __toESM(require_semver2()); // src/config/inputs.ts async function getToolsInput(action, repositoryProperties) { @@ -161358,11 +194749,183 @@ async function getToolsInput(action, repositoryProperties) { return void 0; } +// src/languages/swift.ts +async function checkSwiftCompatibility(config, codeql, darwinVersion2) { + if (!config.languages.includes("swift" /* swift */)) { + return; + } + if (await codeql.supportsFeature("swiftSupportsAllPlatforms" /* SwiftSupportsAllPlatforms */)) { + return; + } + if (darwinVersion2 === void 0) { + throw new ConfigurationError( + `Swift analysis is only supported on macOS runner images. Please migrate to a macOS runner.` + ); + } +} + +// src/languages/traced.ts +var UNSUPPORTED_DARWIN_FOR_TRACED = 27; +var UNSUPPORTED_XCODE_FOR_TRACED = 27; +function diagnosticAttributeName(product) { + switch (product) { + case "macOS": + return "darwinVersion"; + case "Xcode": + return "xcodeVersion"; + case "Xcode SDK": + return "xcodeSdkVersion"; + } +} +function handleUnsupportedVersion(logger2, config, tracedLanguages, abortUnsupportedTracedAnalysis, productVersion) { + const { product, version } = productVersion; + const unsupportedVersion = product === "macOS" ? UNSUPPORTED_DARWIN_FOR_TRACED : ( + // We use the same constant for both Xcode and the Xcode SDK since we treat them + // as equivalent indicators for whether traced analysis is unsupported. + UNSUPPORTED_XCODE_FOR_TRACED + ); + const baseMessage = [ + `Traced analysis is not supported on ${product} ${unsupportedVersion} or above.`, + `Configure your analysis to run on macOS ${UNSUPPORTED_DARWIN_FOR_TRACED - 1} or below`, + `and Xcode ${UNSUPPORTED_XCODE_FOR_TRACED - 1} or below.` + ].join(" "); + const attributeName = diagnosticAttributeName(product); + for (const language of tracedLanguages) { + addDiagnostic( + config, + language, + makeDiagnostic( + `codeql-action/unsupported-traced-analysis-${product.toLowerCase().replaceAll(" ", "-")}`, + `Traced analysis is not supported on this version of ${product}`, + { + attributes: { + languages: config.languages, + [attributeName]: version.toString() + }, + markdownMessage: [ + baseMessage, + `For more information, see [this announcement](${"https://github.blog/changelog/2026-10-19-codeql-changes-for-macos-27-xcode-27-and-swift-6-4/" /* UNSUPPORTED_TRACED_ANALYSIS_MACOS27 */}).` + ].join(" "), + severity: abortUnsupportedTracedAnalysis ? "error" : "warning", + visibility: { + cliSummaryTable: true, + statusPage: true, + telemetry: true + } + } + ) + ); + } + const logMessage = [ + baseMessage, + `For more information, see ${"https://github.blog/changelog/2026-10-19-codeql-changes-for-macos-27-xcode-27-and-swift-6-4/" /* UNSUPPORTED_TRACED_ANALYSIS_MACOS27 */}` + ].join(" "); + if (abortUnsupportedTracedAnalysis) { + throw new ConfigurationError(logMessage); + } else { + logger2.warning(logMessage); + } +} +async function hasTracedLanguages(config, codeql) { + const tracedLanguages = []; + for (const language of config.languages) { + if (await codeql.isTracedLanguage(language)) { + tracedLanguages.push(language); + } + } + return tracedLanguages; +} +async function checkRunnerSupportsTracedAnalysis(action, config, codeql) { + const version = darwinVersion(action); + await checkSwiftCompatibility(config, codeql, version); + if (!await action.features.getValue("check_unsupported_traced_analysis" /* CheckUnsupportedTracedAnalysis */)) { + action.logger.debug( + "Skipping traced analysis compatibility checks because the feature is not enabled." + ); + return; + } + if (config.buildMode !== void 0 && config.buildMode === "none") { + action.logger.debug( + "Skipping traced analysis compatibility checks because the build mode is 'none'." + ); + return; + } + if (version === void 0) { + action.logger.debug( + "Skipping traced analysis compatibility checks because we are not on macOS." + ); + return; + } + const tracedLanguages = await hasTracedLanguages(config, codeql); + if (tracedLanguages.length === 0) { + action.logger.debug( + "Skipping traced analysis compatibility checks because no traced languages are being analyzed." + ); + return; + } + const abortUnsupportedTracedAnalysis = await action.features.getValue( + "abort_unsupported_traced_analysis" /* AbortUnsupportedTracedAnalysis */ + ); + if (typeof version === "string") { + action.logger.warning( + `Unable to parse Darwin kernel version, got: ${version}. Skipping macOS compatibility check.` + ); + } else if (version.major >= UNSUPPORTED_DARWIN_FOR_TRACED) { + handleUnsupportedVersion( + action.logger, + config, + tracedLanguages, + abortUnsupportedTracedAnalysis, + { product: "macOS", version } + ); + return; + } + const xcodeVer = xcodeVersionFromLink(action.logger) ?? await xcodeVersionFromXcodeBuild(action.logger); + let xcodeProduct = void 0; + if (xcodeVer !== void 0) { + xcodeProduct = { product: "Xcode", version: xcodeVer }; + } else { + const xcodeSdkVer = await xcodeSdkVersion(action.logger); + xcodeProduct = xcodeSdkVer !== void 0 ? { product: "Xcode SDK", version: xcodeSdkVer } : void 0; + } + if (xcodeProduct !== void 0 && xcodeProduct.version.major >= UNSUPPORTED_XCODE_FOR_TRACED) { + handleUnsupportedVersion( + action.logger, + config, + tracedLanguages, + abortUnsupportedTracedAnalysis, + xcodeProduct + ); + } else if (xcodeProduct === void 0) { + action.logger.info( + "Unable to determine Xcode version. Skipping Xcode compatibility check." + ); + } +} + +// src/status-report/tools-download.ts +function createInitToolsDownloadFields(report, toolsFeatureFlagsValid) { + const fields = { ...report?.perLanguage }; + if (report?.downloadDurationMs !== void 0) { + fields.tools_download_duration_ms = report.downloadDurationMs; + } + if (report?.extractionDurationMs !== void 0) { + fields.tools_extraction_duration_ms = report.extractionDurationMs; + } + if (report?.totalDurationMs !== void 0) { + fields.tools_total_duration_ms = report.totalDurationMs; + } + if (toolsFeatureFlagsValid !== void 0) { + fields.tools_feature_flags_valid = toolsFeatureFlagsValid; + } + return fields; +} + // src/workflow.ts -var fs28 = __toESM(require("fs")); +var fs30 = __toESM(require("fs")); var path24 = __toESM(require("path")); var import_zlib3 = __toESM(require("zlib")); -var core20 = __toESM(require_core()); +var core18 = __toESM(require_core()); function toCodedErrors(errors) { return Object.entries(errors).reduce( (acc, [code, message]) => { @@ -161465,10 +195028,10 @@ function hasWorkflowTrigger(triggerName, doc) { } return Object.prototype.hasOwnProperty.call(doc.on, triggerName); } -async function validateWorkflow(codeql, logger) { +async function validateWorkflow(codeql, logger2) { let workflow; try { - workflow = await getWorkflow(logger); + workflow = await getWorkflow(logger2); } catch (e) { return `error: getWorkflow() failed: ${String(e)}`; } @@ -161485,7 +195048,7 @@ async function validateWorkflow(codeql, logger) { } catch (e) { return `error: formatWorkflowErrors() failed: ${String(e)}`; } - core20.warning(message); + core18.warning(message); } return formatWorkflowCause(workflowErrors); } @@ -161500,27 +195063,27 @@ function formatWorkflowCause(errors) { } return errors.map((e) => e.code).join(","); } -async function getWorkflow(logger) { +async function getWorkflow(logger2) { const maybeWorkflow = process.env["CODE_SCANNING_WORKFLOW_FILE"]; if (maybeWorkflow) { - logger.debug( + logger2.debug( "Using the workflow specified by the CODE_SCANNING_WORKFLOW_FILE environment variable." ); return load( import_zlib3.default.gunzipSync(Buffer.from(maybeWorkflow, "base64")).toString() ); } - const workflowPath = await getWorkflowAbsolutePath(logger); - return load(fs28.readFileSync(workflowPath, "utf-8")); + const workflowPath = await getWorkflowAbsolutePath(logger2); + return load(fs30.readFileSync(workflowPath, "utf-8")); } -async function getWorkflowAbsolutePath(logger) { +async function getWorkflowAbsolutePath(logger2) { const relativePath2 = await getWorkflowRelativePath(); const absolutePath = path24.join( getRequiredEnvParam("GITHUB_WORKSPACE"), relativePath2 ); - if (fs28.existsSync(absolutePath)) { - logger.debug( + if (fs30.existsSync(absolutePath)) { + logger2.debug( `Derived the following absolute path for the currently executing workflow: ${absolutePath}.` ); return absolutePath; @@ -161603,30 +195166,36 @@ function getUploadInputOrThrow(workflow, jobName, matrixVars) { matrixVars ); } -function getCheckoutPathInputOrThrow(workflow, jobName, matrixVars) { - return getInputOrThrow( - workflow, - jobName, - getAnalyzeActionName(), - "checkout_path", - matrixVars - ) || getRequiredEnvParam("GITHUB_WORKSPACE"); +function getRepositoryRootOrThrow(workflow, jobName, matrixVars, config, env = getEnv()) { + return ( + // If the CodeQL Action already has a persisted repository root, then we can just use that. + config.repositoryRoot ?? // Otherwise, try to retrieve it from a `checkout_path` input in the workflow specification. + getInputOrThrow( + workflow, + jobName, + getAnalyzeActionName(), + "checkout_path", + matrixVars + ) ?? // Finally, if all of the above fail, just use the value of `GITHUB_WORKSPACE` since that + // is what is used by default. + env.getRequired("GITHUB_WORKSPACE" /* GITHUB_WORKSPACE */) + ); } -async function checkWorkflow(logger, codeql) { +async function checkWorkflow(logger2, codeql) { if (!isDynamicWorkflow() && process.env["CODEQL_ACTION_SKIP_WORKFLOW_VALIDATION" /* SKIP_WORKFLOW_VALIDATION */] !== "true") { - core20.startGroup("Validating workflow"); + core18.startGroup("Validating workflow"); const validateWorkflowResult = await internal2.validateWorkflow( codeql, - logger + logger2 ); if (validateWorkflowResult === void 0) { - logger.info("Detected no issues with the code scanning workflow."); + logger2.info("Detected no issues with the code scanning workflow."); } else { - logger.debug( + logger2.debug( `Unable to validate code scanning workflow: ${validateWorkflowResult}` ); } - core20.endGroup(); + core18.endGroup(); } } var internal2 = { @@ -161635,27 +195204,27 @@ var internal2 = { // src/init-action.ts var CODEQL_VERSION_JAR_MINIMIZATION = "2.23.0"; -async function sendStartingStatusReport(startedAt, config, logger) { +async function sendStartingStatusReport(startedAt, config, logger2) { const statusReportBase = await createStatusReportBase( "init" /* Init */, "starting", startedAt, config, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { await sendStatusReport(statusReportBase); } } -async function sendCompletedStatusReport2(startedAt, config, configFile, toolsInput, toolsDownloadStatusReport, toolsFeatureFlagsValid, toolsSource, toolsVersion, overlayBaseDatabaseStats, dependencyCachingResults, logger, error3) { +async function sendCompletedStatusReport2(startedAt, config, configFile, toolsInput, toolsDownloadStatusReport, toolsFeatureFlagsValid, toolsSource, toolsVersion, overlayBaseDatabaseStats, dependencyCachingResults, logger2, error3) { const statusReportBase = await createStatusReportBase( "init" /* Init */, getActionsStatus(error3), startedAt, config, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3?.message, error3?.stack ); @@ -161673,20 +195242,17 @@ async function sendCompletedStatusReport2(startedAt, config, configFile, toolsIn if (toolsInput !== void 0) { initStatusReport.computed_inputs.tools = toolsInput; } - const initToolsDownloadFields = {}; - if (toolsDownloadStatusReport?.downloadDurationMs !== void 0) { - initToolsDownloadFields.tools_download_duration_ms = toolsDownloadStatusReport.downloadDurationMs; - } - if (toolsFeatureFlagsValid !== void 0) { - initToolsDownloadFields.tools_feature_flags_valid = toolsFeatureFlagsValid; - } + const initToolsDownloadFields = createInitToolsDownloadFields( + toolsDownloadStatusReport, + toolsFeatureFlagsValid + ); if (config !== void 0) { const initWithConfigStatusReport = await createInitWithConfigStatusReport( config, initStatusReport, configFile, Math.round( - await getTotalCacheSize(Object.values(config.trapCaches), logger) + await getTotalCacheSize(Object.values(config.trapCaches), logger2) ), overlayBaseDatabaseStats, dependencyCachingResults @@ -161701,7 +195267,7 @@ async function sendCompletedStatusReport2(startedAt, config, configFile, toolsIn } async function run3(actionState) { const startedAt = actionState.startedAt; - const logger = actionState.logger; + const logger2 = actionState.logger; let apiDetails; let config; let configFile; @@ -161714,49 +195280,50 @@ async function run3(actionState) { let toolsSource; let toolsVersion; try { - initializeEnvironment(getActionVersion()); + actionState.env.initialise(getActionVersion()); persistInputs(); apiDetails = { auth: getRequiredInput("token"), externalRepoAuth: getOptionalInput("external-repository-token"), - url: getRequiredEnvParam("GITHUB_SERVER_URL"), - apiURL: getRequiredEnvParam("GITHUB_API_URL") + ...getCurrentInstance(actionState.env) }; const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); checkActionVersion(getActionVersion(), gitHubVersion); const repositoryNwo = getRepositoryNwo(); features = initFeatures( gitHubVersion, repositoryNwo, getTemporaryDirectory(), - logger + logger2 ); const repositoryPropertiesResult = await loadRepositoryProperties( repositoryNwo, - logger + logger2 ); const repositoryProperties = repositoryPropertiesResult.orElse({}); - core21.exportVariable("CODEQL_ACTION_INIT_HAS_RUN" /* INIT_ACTION_HAS_RUN */, "true"); + actionState.env.export("CODEQL_ACTION_INIT_HAS_RUN" /* INIT_ACTION_HAS_RUN */, "true"); sourceRoot = path25.resolve( - getRequiredEnvParam("GITHUB_WORKSPACE"), + actionState.env.getRequired("GITHUB_WORKSPACE" /* GITHUB_WORKSPACE */), getOptionalInput("source-root") || "" ); let analysisKinds; try { - analysisKinds = await getAnalysisKinds(logger, features); + analysisKinds = await getAnalysisKinds(logger2, features); } catch (err) { - logger.debug( + logger2.debug( `Failed to parse analysis kinds for 'starting' status report: ${getErrorMessage(err)}` ); } - const actionStateWithFeatures = { ...actionState, features }; + const actionStateWithFeatures = extendActionState(actionState, { + features + }); configFile = await getConfigFileInput( actionStateWithFeatures, repositoryProperties, analysisKinds ); - await sendStartingStatusReport(startedAt, { analysisKinds }, logger); + await sendStartingStatusReport(startedAt, { analysisKinds }, logger2); if (process.env["CODEQL_ACTION_SETUP_CODEQL_HAS_RUN" /* SETUP_CODEQL_ACTION_HAS_RUN */] === "true") { throw new ConfigurationError( `The 'init' action should not be run in the same workflow as 'setup-codeql'.` @@ -161771,6 +195338,20 @@ async function run3(actionState) { const rawLanguages = getRawLanguagesNoAutodetect( getOptionalInput("languages") ); + const rawConfigInput = getOptionalInput("config"); + const configInput = rawConfigInput === void 0 ? void 0 : parseUserConfig( + logger2, + "`config` input", + rawConfigInput, + await features.getValue("validate_db_config" /* ValidateDbConfig */) + ); + const queriesInput = getOptionalInput("queries"); + const otherLanguagePacksReason = getOtherLanguagePacksReason({ + configFile, + configInput, + queriesInput, + extraQueriesProperty: repositoryProperties["github-codeql-extra-queries" /* EXTRA_QUERIES */] + }); const useOverlayAwareDefaultCliVersion = analysisKinds?.length === 1 && analysisKinds[0] === "code-scanning" /* CodeScanning */; const initCodeQLResult = await initCodeQL( toolsInput?.value, @@ -161779,35 +195360,30 @@ async function run3(actionState) { gitHubVersion.type, codeQLDefaultVersionInfo, rawLanguages, + otherLanguagePacksReason, useOverlayAwareDefaultCliVersion, features, - logger + logger2 ); codeql = initCodeQLResult.codeql; toolsDownloadStatusReport = initCodeQLResult.toolsDownloadStatusReport; toolsVersion = initCodeQLResult.toolsVersion; toolsSource = initCodeQLResult.toolsSource; - await checkWorkflow(logger, codeql); + await checkWorkflow(logger2, codeql); if ( // Only enable the experimental features env variable for Rust analysis if the user has explicitly // requested rust - don't enable it via language autodetection. getRawLanguagesNoAutodetect(getOptionalInput("languages")).includes("rust" /* rust */) ) { - const experimental = "2.19.3"; const publicPreview = "2.22.1"; const actualVer = (await codeql.getVersion()).version; - if (semver10.lt(actualVer, experimental)) { - throw new ConfigurationError( - `Rust analysis is supported by CodeQL CLI version ${experimental} or higher, but found version ${actualVer}` - ); - } - if (semver10.lt(actualVer, publicPreview)) { - core21.exportVariable("CODEQL_ENABLE_EXPERIMENTAL_FEATURES" /* EXPERIMENTAL_FEATURES */, "true"); - logger.info("Experimental Rust analysis enabled"); + if (semver12.lt(actualVer, publicPreview)) { + actionState.env.export("CODEQL_ENABLE_EXPERIMENTAL_FEATURES" /* EXPERIMENTAL_FEATURES */, "true"); + logger2.info("Experimental Rust analysis enabled"); } } - analysisKinds = await getAnalysisKinds(logger, features); - const debugMode = getOptionalInput("debug") === "true" || core21.isDebug(); + analysisKinds = await getAnalysisKinds(logger2, features); + const debugMode = getOptionalInput("debug") === "true" || core19.isDebug(); const fileCoverageResult = await getFileCoverageInformationEnabled( debugMode, codeql, @@ -161817,13 +195393,13 @@ async function run3(actionState) { config = await initConfig2(actionStateWithFeatures, { analysisKinds, languagesInput: getOptionalInput("languages"), - queriesInput: getOptionalInput("queries"), + queriesInput, packsInput: getOptionalInput("packs"), buildModeInput: getOptionalInput("build-mode"), ramInput: getOptionalInput("ram"), configFile, dbLocation: getOptionalInput("db-location"), - configInput: getOptionalInput("config"), + configInput, dependencyCachingEnabled: getDependencyCachingEnabled(), // Debug mode is enabled if: // - The `init` Action is passed `debug: true`. @@ -161835,20 +195411,22 @@ async function run3(actionState) { repository: repositoryNwo, tempDir: getTemporaryDirectory(), codeql, - workspacePath: getRequiredEnvParam("GITHUB_WORKSPACE"), + workspacePath: actionState.env.getRequired( + "GITHUB_WORKSPACE" /* GITHUB_WORKSPACE */ + ), sourceRoot, githubVersion: gitHubVersion, apiDetails, features, repositoryProperties, enableFileCoverageInformation: fileCoverageResult.enabled, - logger + logger: logger2 }); - if (config.languages.includes("swift" /* swift */) && process.platform !== "darwin") { - throw new ConfigurationError( - `Swift analysis is only supported on macOS runner images. Please migrate to a macOS runner.` - ); - } + await checkRunnerSupportsTracedAnalysis( + actionStateWithFeatures, + config, + codeql + ); if (repositoryPropertiesResult.isFailure()) { addNoLanguageDiagnostic( config, @@ -161872,25 +195450,35 @@ async function run3(actionState) { ); } if (fileCoverageResult.showDeprecationWarning) { - logFileCoverageOnPrsDeprecationWarning(logger); + logFileCoverageOnPrsDeprecationWarning(logger2); } await checkInstallPython311(config.languages, codeql); } catch (unwrappedError) { + if (config !== void 0) { + try { + saveAbortedInitConfig(actionState, config); + } catch (configSaveError) { + logger2.warning( + `Unable to save configuration for '${"init-post" /* InitPost */}' step: ${getErrorMessage(configSaveError)}` + ); + } + } const error3 = wrapError(unwrappedError); - core21.setFailed(error3.message); + core19.setFailed(error3.message); const statusReportBase = await createStatusReportBase( "init" /* Init */, error3 instanceof ConfigurationError ? "user-error" : "aborted", startedAt, config, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3.message, error3.stack ); if (statusReportBase !== void 0) { await sendStatusReport(statusReportBase); } + logTemporaryDiagnostics(actionState); return; } let overlayBaseDatabaseStats; @@ -161903,11 +195491,11 @@ async function run3(actionState) { overlayBaseDatabaseStats = await downloadOverlayBaseDatabaseFromCache( codeql, config, - logger + logger2 ); if (!overlayBaseDatabaseStats) { config.overlayDatabaseMode = "none" /* None */; - logger.info( + logger2.info( `No overlay-base database found in cache, reverting overlay database mode to ${"none" /* None */}.` ); } @@ -161915,50 +195503,50 @@ async function run3(actionState) { ); } if (config.overlayDatabaseMode !== "overlay" /* Overlay */) { - cleanupDatabaseClusterDirectory(config, logger); + cleanupDatabaseClusterDirectory(config, logger2); } - const goFlags = process.env["GOFLAGS"]; + const goFlags = actionState.env.getOptional("GOFLAGS"); if (goFlags) { - core21.exportVariable("GOFLAGS", goFlags); - core21.warning( + actionState.env.export("GOFLAGS", goFlags); + core19.warning( "Passing the GOFLAGS env parameter to the init action is deprecated. Please move this to the analyze action." ); } if (config.languages.includes("go" /* go */) && process.platform === "linux") { try { - const goBinaryPath = await io7.which("go", true); + const goBinaryPath = await io8.which("go", true); const fileOutput = await getFileType(goBinaryPath); if (fileOutput.includes("statically linked") && !await codeql.supportsFeature( "indirectTracingSupportsStaticBinaries" /* IndirectTracingSupportsStaticBinaries */ )) { try { - logger.debug(`Applying static binary workaround for Go`); + logger2.debug(`Applying static binary workaround for Go`); const tempBinPath = path25.resolve( getTemporaryDirectory(), "codeql-action-go-tracing", "bin" ); - fs29.mkdirSync(tempBinPath, { recursive: true }); - core21.addPath(tempBinPath); + fs31.mkdirSync(tempBinPath, { recursive: true }); + core19.addPath(tempBinPath); const goWrapperPath = path25.resolve(tempBinPath, "go"); - fs29.writeFileSync( + fs31.writeFileSync( goWrapperPath, `#!/bin/bash exec ${goBinaryPath} "$@"` ); - fs29.chmodSync(goWrapperPath, "755"); - core21.exportVariable("CODEQL_ACTION_GO_BINARY" /* GO_BINARY_LOCATION */, goWrapperPath); + fs31.chmodSync(goWrapperPath, "755"); + actionState.env.export("CODEQL_ACTION_GO_BINARY" /* GO_BINARY_LOCATION */, goWrapperPath); } catch (e) { - logger.warning( + logger2.warning( `Analyzing Go on Linux, but failed to install wrapper script. Tracing custom builds may fail: ${e}` ); } } else { - core21.exportVariable("CODEQL_ACTION_GO_BINARY" /* GO_BINARY_LOCATION */, goBinaryPath); + actionState.env.export("CODEQL_ACTION_GO_BINARY" /* GO_BINARY_LOCATION */, goBinaryPath); } } catch (e) { - logger.warning( + logger2.warning( `Failed to determine the location of the Go binary: ${e}` ); if (e instanceof FileCmdNotFoundError) { @@ -161982,50 +195570,49 @@ exec ${goBinaryPath} "$@"` } } } - core21.exportVariable( + actionState.env.export( "CODEQL_RAM", - process.env["CODEQL_RAM"] || getCodeQLMemoryLimit(getOptionalInput("ram"), logger).toString() + process.env["CODEQL_RAM"] || getCodeQLMemoryLimit(getOptionalInput("ram"), logger2).toString() ); - core21.exportVariable( + actionState.env.export( "CODEQL_THREADS", - process.env["CODEQL_THREADS"] || getThreadsFlagValue(getOptionalInput("threads"), logger).toString() + process.env["CODEQL_THREADS"] || getThreadsFlagValue(getOptionalInput("threads"), logger2).toString() ); if (await features.getValue("disable_kotlin_analysis_enabled" /* DisableKotlinAnalysisEnabled */)) { - core21.exportVariable("CODEQL_EXTRACTOR_JAVA_AGENT_DISABLE_KOTLIN", "true"); + actionState.env.export( + "CODEQL_EXTRACTOR_JAVA_AGENT_DISABLE_KOTLIN", + "true" + ); } if (await features.getValue("force_jgit" /* ForceJGit */)) { - core21.exportVariable("CODEQL_GIT_BACKEND", "jgit"); - } - const kotlinLimitVar = "CODEQL_EXTRACTOR_KOTLIN_OVERRIDE_MAXIMUM_VERSION_LIMIT"; - if (await codeQlVersionAtLeast(codeql, "2.20.3") && !await codeQlVersionAtLeast(codeql, "2.20.4")) { - core21.exportVariable(kotlinLimitVar, "2.1.20"); + actionState.env.export("CODEQL_GIT_BACKEND", "jgit"); } if (shouldRestoreCache(config.dependencyCachingEnabled)) { const dependencyCachingResult = await downloadDependencyCaches( codeql, features, config.languages, - logger + logger2 ); dependencyCachingStatus = dependencyCachingResult.statusReport; config.dependencyCachingRestoredKeys = dependencyCachingResult.restoredKeys; } if (getOptionalInput("setup-python-dependencies") !== void 0) { - logger.warning( + logger2.warning( "The setup-python-dependencies input is deprecated and no longer has any effect. We recommend removing any references from your workflows. See https://github.blog/changelog/2024-01-23-codeql-2-16-python-dependency-installation-disabled-new-queries-and-bug-fixes/ for more information." ); } if (process.env["CODEQL_ACTION_DISABLE_PYTHON_DEPENDENCY_INSTALLATION"] !== void 0) { - logger.warning( + logger2.warning( "The CODEQL_ACTION_DISABLE_PYTHON_DEPENDENCY_INSTALLATION environment variable is deprecated and no longer has any effect. We recommend removing any references from your workflows. See https://github.blog/changelog/2024-01-23-codeql-2-16-python-dependency-installation-disabled-new-queries-and-bug-fixes/ for more information." ); } if (process.env["CODEQL_EXTRACTOR_JAVA_OPTION_MINIMIZE_DEPENDENCY_JARS" /* JAVA_EXTRACTOR_MINIMIZE_DEPENDENCY_JARS */]) { - logger.debug( + logger2.debug( `${"CODEQL_EXTRACTOR_JAVA_OPTION_MINIMIZE_DEPENDENCY_JARS" /* JAVA_EXTRACTOR_MINIMIZE_DEPENDENCY_JARS */} is already set to '${process.env["CODEQL_EXTRACTOR_JAVA_OPTION_MINIMIZE_DEPENDENCY_JARS" /* JAVA_EXTRACTOR_MINIMIZE_DEPENDENCY_JARS */]}', so the Action will not override it.` ); - } else if (await codeQlVersionAtLeast(codeql, CODEQL_VERSION_JAR_MINIMIZATION) && config.dependencyCachingEnabled && config.buildMode === "none" /* None */ && config.languages.includes("java" /* java */)) { - core21.exportVariable( + } else if (await codeql.isVersionAtLeast(CODEQL_VERSION_JAR_MINIMIZATION) && config.dependencyCachingEnabled && config.buildMode === "none" /* None */ && config.languages.includes("java" /* java */)) { + actionState.env.export( "CODEQL_EXTRACTOR_JAVA_OPTION_MINIMIZE_DEPENDENCY_JARS" /* JAVA_EXTRACTOR_MINIMIZE_DEPENDENCY_JARS */, "true" ); @@ -162033,7 +195620,7 @@ exec ${goBinaryPath} "$@"` const { registriesAuthTokens, qlconfigFile } = await generateRegistries( getOptionalInput("registries"), config.tempDir, - logger + logger2 ); const databaseInitEnvironment = { GITHUB_TOKEN: apiDetails.auth, @@ -162047,12 +195634,12 @@ exec ${goBinaryPath} "$@"` "Runner.Worker.exe", qlconfigFile ); - if (config.overlayDatabaseMode !== "none" /* None */ && !await checkPacksForOverlayCompatibility(codeql, config, logger)) { - logger.info( + if (config.overlayDatabaseMode !== "none" /* None */ && !await checkPacksForOverlayCompatibility(codeql, config, logger2)) { + logger2.info( "Reverting overlay database mode to None due to incompatible packs." ); config.overlayDatabaseMode = "none" /* None */; - cleanupDatabaseClusterDirectory(config, logger, { + cleanupDatabaseClusterDirectory(config, logger2, { disableExistingDirectoryWarning: true }); await runDatabaseInitCluster( @@ -162064,26 +195651,27 @@ exec ${goBinaryPath} "$@"` qlconfigFile ); } - const tracerConfig = await getCombinedTracerConfig(codeql, config); + const tracerConfig = await getCombinedTracerConfig(logger2, codeql, config); if (tracerConfig !== void 0) { for (const [key, value] of Object.entries(tracerConfig.env)) { - core21.exportVariable(key, value); + actionState.env.export(key, value); } } if (await features.getValue("java_network_debugging" /* JavaNetworkDebugging */)) { - const existingJavaToolOptions = getOptionalEnvVar("JAVA_TOOL_OPTIONS" /* JAVA_TOOL_OPTIONS */) || ""; - core21.exportVariable( + const existingJavaToolOptions = actionState.env.getOptional("JAVA_TOOL_OPTIONS" /* JAVA_TOOL_OPTIONS */) ?? ""; + actionState.env.export( "JAVA_TOOL_OPTIONS" /* JAVA_TOOL_OPTIONS */, `${existingJavaToolOptions} -Djavax.net.debug=all` ); } - flushDiagnostics(config); - await saveConfig(config, logger); - core21.setOutput("codeql-path", config.codeQLCmd); - core21.setOutput("codeql-version", (await codeql.getVersion()).version); + flushDiagnostics(actionState, config); + config.successfullyInitialised = true; + await saveConfig(config, logger2); + core19.setOutput("codeql-path", config.codeQLCmd); + core19.setOutput("codeql-version", (await codeql.getVersion()).version); } catch (unwrappedError) { const error3 = wrapError(unwrappedError); - core21.setFailed(error3.message); + core19.setFailed(error3.message); await sendCompletedStatusReport2( startedAt, config, @@ -162096,12 +195684,12 @@ exec ${goBinaryPath} "$@"` toolsVersion, overlayBaseDatabaseStats, dependencyCachingStatus, - logger, + logger2, error3 ); return; } finally { - logUnwrittenDiagnostics(); + logTemporaryDiagnostics(actionState); } await sendCompletedStatusReport2( startedAt, @@ -162114,7 +195702,7 @@ exec ${goBinaryPath} "$@"` toolsVersion, overlayBaseDatabaseStats, dependencyCachingStatus, - logger + logger2 ); } var init = { @@ -162127,10 +195715,10 @@ async function runWrapper4() { } // src/init-action-post.ts -var core22 = __toESM(require_core()); +var core20 = __toESM(require_core()); // src/init-action-post-helper.ts -var fs30 = __toESM(require("fs")); +var fs32 = __toESM(require("fs")); var import_path8 = __toESM(require("path")); var github4 = __toESM(require_github()); function createFailedUploadFailedSarifResult(error3) { @@ -162140,7 +195728,7 @@ function createFailedUploadFailedSarifResult(error3) { upload_failed_run_stack_trace: wrappedError.stack }; } -async function prepareFailedSarif(logger, features, config) { +async function prepareFailedSarif(logger2, features, config) { if (!config.codeQLCmd) { return new Failure({ upload_failed_run_skipped_because: "CodeQL command not found" @@ -162148,7 +195736,7 @@ async function prepareFailedSarif(logger, features, config) { } const jobName = getRequiredEnvParam("GITHUB_JOB"); const matrix = parseMatrixInput(getRequiredInput("matrix")); - if (shouldSkipSarifUpload()) { + if (shouldSkipGenerateFailedSarif()) { return new Failure({ upload_failed_run_skipped_because: "SARIF upload is disabled" }); @@ -162163,7 +195751,7 @@ async function prepareFailedSarif(logger, features, config) { const category = `/language:${language}`; const checkoutPath = "."; const result = await generateFailedSarif( - logger, + logger2, features, config, category, @@ -162172,7 +195760,7 @@ async function prepareFailedSarif(logger, features, config) { ); return new Success(result); } else { - const workflow = await getWorkflow(logger); + const workflow = await getWorkflow(logger2); const shouldUpload = getUploadInputOrThrow(workflow, jobName, matrix); if (!["always", "failure-only"].includes( getUploadValue(shouldUpload) @@ -162182,9 +195770,14 @@ async function prepareFailedSarif(logger, features, config) { }); } const category = getCategoryInputOrThrow(workflow, jobName, matrix); - const checkoutPath = getCheckoutPathInputOrThrow(workflow, jobName, matrix); + const checkoutPath = getRepositoryRootOrThrow( + workflow, + jobName, + matrix, + config + ); const result = await generateFailedSarif( - logger, + logger2, features, config, category, @@ -162193,63 +195786,83 @@ async function prepareFailedSarif(logger, features, config) { return new Success(result); } } -async function generateFailedSarif(logger, features, config, category, checkoutPath, sarifFile) { +async function generateFailedSarif(logger2, features, config, category, checkoutPath, sarifFile) { const databasePath = config.dbLocation; - const codeql = await getCodeQL(logger, config.codeQLCmd); + const codeql = await getCodeQL(logger2, config.codeQLCmd); if (sarifFile === void 0) { sarifFile = "../codeql-failed-run.sarif"; } - if (databasePath === void 0 || !await features.getValue("export_diagnostics_enabled" /* ExportDiagnosticsEnabled */, codeql)) { - await codeql.diagnosticsExport(sarifFile, category, config); + const exportDiagnosticsEnabled = await features.getValue( + "export_diagnostics_enabled" /* ExportDiagnosticsEnabled */, + codeql + ); + if (databasePath === void 0 || !exportDiagnosticsEnabled) { + let diagnosticDir = getTempDiagnosticsRoot( + config.tempDir + ); + if (!exportDiagnosticsEnabled || !fs32.existsSync(diagnosticDir)) { + diagnosticDir = void 0; + } + await codeql.diagnosticsExport(sarifFile, category, config, diagnosticDir); } else { await codeql.databaseExportDiagnostics(databasePath, sarifFile, category); } return { sarifFile, category, checkoutPath }; } -async function maybeUploadFailedSarif(config, repositoryNwo, features, logger) { - const failedSarifResult = await prepareFailedSarif(logger, features, config); +async function maybeUploadFailedSarif(config, repositoryNwo, features, logger2) { + const failedSarifResult = await prepareFailedSarif(logger2, features, config); if (failedSarifResult.isFailure()) { return failedSarifResult.value; } const failedSarif = failedSarifResult.value; - logger.info(`Uploading failed SARIF file ${failedSarif.sarifFile}`); + logger2.info(`Uploading failed SARIF file ${failedSarif.sarifFile}`); const uploadResult = await uploadFiles( + config, failedSarif.sarifFile, failedSarif.checkoutPath, failedSarif.category, features, - logger, + logger2, CodeScanning ); await waitForProcessing( repositoryNwo, uploadResult.sarifID, - logger, + logger2, { isUnsuccessfulExecution: true } ); + if (uploadResult.sarifID && shouldSkipSarifUpload()) { + await uploadSarifArtifact(logger2, "test-mode-sarif", failedSarif); + } return uploadResult ? { ...uploadResult.statusReport, sarifID: uploadResult.sarifID } : {}; } -async function maybeUploadFailedSarifArtifact(config, features, logger) { - const failedSarifResult = await prepareFailedSarif(logger, features, config); +async function maybeUploadFailedSarifArtifact(config, features, logger2) { + const failedSarifResult = await prepareFailedSarif(logger2, features, config); if (failedSarifResult.isFailure()) { return failedSarifResult.value; } const failedSarif = failedSarifResult.value; - logger.info( - `Uploading failed SARIF file ${failedSarif.sarifFile} as artifact` - ); - const gitHubVersion = await getGitHubVersion(); - const client = await getArtifactUploaderClient(logger, gitHubVersion.type); - const suffix = getArtifactSuffix(getOptionalInput("matrix")); - const name = sanitizeArtifactName(`sarif-artifact-${suffix}`); - await client.uploadArtifact( - name, - [import_path8.default.normalize(failedSarif.sarifFile)], - import_path8.default.normalize("..") - ); - return { sarifID: name }; + return uploadSarifArtifact(logger2, "sarif-artifact", failedSarif); } -async function tryUploadSarifIfRunFailed(config, repositoryNwo, features, logger) { +async function uploadSarifArtifact(logger2, prefix, failedSarif) { + logger2.startGroup(`Uploading failed SARIF file as artifact`); + logger2.info(`Uploading '${failedSarif.sarifFile}' as artifact`); + try { + const gitHubVersion = await getGitHubVersion(); + const client = await getArtifactUploaderClient(logger2, gitHubVersion.type); + const suffix = getArtifactSuffix(getOptionalInput("matrix")); + const name = sanitizeArtifactName(`${prefix}-${suffix}`); + await client.uploadArtifact( + name, + [import_path8.default.normalize(failedSarif.sarifFile)], + import_path8.default.normalize(import_path8.default.dirname(failedSarif.sarifFile)) + ); + return { sarifID: name }; + } finally { + logger2.endGroup(); + } +} +async function tryUploadSarifIfRunFailed(config, repositoryNwo, features, logger2) { if (process.env["CODEQL_ACTION_ANALYZE_DID_COMPLETE_SUCCESSFULLY" /* ANALYZE_DID_COMPLETE_SUCCESSFULLY */] === "true") { return { upload_failed_run_skipped_because: "Analyze Action completed successfully" @@ -162261,32 +195874,32 @@ async function tryUploadSarifIfRunFailed(config, repositoryNwo, features, logger config, repositoryNwo, features, - logger + logger2 ); } else if (isRiskAssessmentEnabled(config)) { - return await maybeUploadFailedSarifArtifact(config, features, logger); + return await maybeUploadFailedSarifArtifact(config, features, logger2); } else { return { upload_failed_run_skipped_because: "No analysis kind that supports failed SARIF uploads is enabled." }; } } catch (e) { - logger.debug( + logger2.debug( `Failed to upload a SARIF file for this failed CodeQL code scanning run. ${e}` ); return createFailedUploadFailedSarifResult(e); } } -async function uploadFailureInfo(uploadAllAvailableDebugArtifacts, printDebugLogs2, codeql, config, repositoryNwo, features, logger) { - await recordOverlayStatus(codeql, config, features, logger); +async function uploadFailureInfo(uploadAllAvailableDebugArtifacts, printDebugLogs2, codeql, config, repositoryNwo, features, jobStatus, env, logger2) { + await recordOverlayStatus(codeql, config, features, jobStatus, env, logger2); const uploadFailedSarifResult = await tryUploadSarifIfRunFailed( config, repositoryNwo, features, - logger + logger2 ); if (uploadFailedSarifResult.upload_failed_run_skipped_because) { - logger.debug( + logger2.debug( `Won't upload a failed SARIF file for this CodeQL analysis because: ${uploadFailedSarifResult.upload_failed_run_skipped_because}.` ); } @@ -162298,50 +195911,72 @@ async function uploadFailureInfo(uploadAllAvailableDebugArtifacts, printDebugLog } if (process.env["CODEQL_ACTION_EXPECT_UPLOAD_FAILED_SARIF"] === "true") { if (!github4.context.payload.pull_request?.head.repo.fork) { - await removeUploadedSarif(uploadFailedSarifResult, logger); + await removeUploadedSarif(uploadFailedSarifResult, logger2); } else { - logger.info( + logger2.info( "Skipping deletion of failed SARIF because the workflow was triggered from a fork of codeql-action and doesn't have the appropriate permissions for deletion." ); } } - if (config.debugMode) { - logger.info( + if (config.debugMode && hasConfigKey(config, "dbLocation")) { + logger2.info( "Debug mode is on. Uploading available database bundles and logs as Actions debugging artifacts..." ); - const version = await codeql.getVersion(); - await uploadAllAvailableDebugArtifacts( - codeql, - config, - logger, - version.version - ); - await printDebugLogs2(config); + await uploadAllAvailableDebugArtifacts(codeql, config, logger2); + await printDebugLogs2(logger2, config); } - if (isSelfHostedRunner()) { + if (isSelfHostedRunner() && config.dbLocation) { try { - fs30.rmSync(config.dbLocation, { + fs32.rmSync(config.dbLocation, { recursive: true, force: true, maxRetries: 3 }); - logger.info( + logger2.info( `Cleaned up database cluster directory ${config.dbLocation}.` ); } catch (e) { - logger.warning( + logger2.warning( `Failed to clean up database cluster directory ${config.dbLocation}. Details: ${e}` ); } + } else if (config.dbLocation === void 0) { + logger2.debug( + "Skipping cleanup of database cluster directory since the configuration does not include a database path." + ); } else { - logger.debug( + logger2.debug( "Skipping cleanup of database cluster directory since we are running on a GitHub-hosted runner which will be automatically cleaned up." ); } return uploadFailedSarifResult; } -async function recordOverlayStatus(codeql, config, features, logger) { - if (config.overlayDatabaseMode !== "overlay-base" /* OverlayBase */ || process.env["CODEQL_ACTION_ANALYZE_DID_COMPLETE_SUCCESSFULLY" /* ANALYZE_DID_COMPLETE_SUCCESSFULLY */] === "true" || !await features.getValue("overlay_analysis_status_save" /* OverlayAnalysisStatusSave */)) { +function didCodeQlReportError(env) { + const jobStatus = env.getOptional("CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */); + return jobStatus === "JOB_STATUS_FAILURE" /* FailureStatus */ || jobStatus === "JOB_STATUS_CONFIGURATION_ERROR" /* ConfigErrorStatus */; +} +function isConclusiveJobStatus(jobStatus) { + switch (jobStatus?.trim().toLowerCase()) { + case "failure": + case "success": + return true; + default: + return false; + } +} +async function recordOverlayStatus(codeql, config, features, jobStatus, env, logger2) { + if (config.overlayDatabaseMode !== "overlay-base" /* OverlayBase */ || env.getOptional("CODEQL_ACTION_ANALYZE_DID_COMPLETE_SUCCESSFULLY" /* ANALYZE_DID_COMPLETE_SUCCESSFULLY */) === "true" || !await features.getValue("overlay_analysis_status_save" /* OverlayAnalysisStatusSave */)) { + return; + } else if (config.languages === void 0) { + logger2.debug( + "Not recording overlay status, because the configuration contains no 'languages'." + ); + return; + } + if (!isConclusiveJobStatus(jobStatus) && !didCodeQlReportError(env)) { + logger2.info( + `Not recording an improved incremental analysis failure for this job because the job status (${jobStatus ?? "unset"}) does not tell us whether the analysis itself failed.` + ); return; } const checkRunIdInput = getOptionalInput("check-run-id"); @@ -162353,9 +195988,9 @@ async function recordOverlayStatus(codeql, config, features, logger) { }, checkRunId !== void 0 && checkRunId >= 0 ? checkRunId : void 0 ); - const diskUsage = await checkDiskUsage(logger); + const diskUsage = await checkDiskUsage(logger2); if (diskUsage === void 0) { - logger.warning( + logger2.warning( "Unable to save overlay status to the Actions cache because the available disk space could not be determined." ); return; @@ -162365,24 +196000,24 @@ async function recordOverlayStatus(codeql, config, features, logger) { config.languages, diskUsage, overlayStatus, - logger + logger2 ); const blurb = "This job attempted to run with improved incremental analysis but it did not complete successfully. One possible reason for this is disk space constraints, since improved incremental analysis can require a significant amount of disk space for some repositories."; if (saved) { - logger.error( + logger2.error( `${blurb} This failure has been recorded in the Actions cache, so the next CodeQL analysis will run without improved incremental analysis. If you want to enable improved incremental analysis, try increasing the disk space available to the runner. If that doesn't help, contact GitHub Support for further assistance.` ); } else { - logger.error( + logger2.error( `${blurb} The attempt to save this failure status to the Actions cache failed. The Action will attempt to run with improved incremental analysis again.` ); } } -async function removeUploadedSarif(uploadFailedSarifResult, logger) { +async function removeUploadedSarif(uploadFailedSarifResult, logger2) { const sarifID = uploadFailedSarifResult.sarifID; if (sarifID) { - logger.startGroup("Deleting failed SARIF upload"); - logger.info( + logger2.startGroup("Deleting failed SARIF upload"); + logger2.info( `In test mode, therefore deleting the failed analysis to avoid impacting tool status for the Action repository. SARIF ID to delete: ${sarifID}.` ); const client = getApiClient(); @@ -162399,7 +196034,7 @@ async function removeUploadedSarif(uploadFailedSarifResult, logger) { ); if (analysisInfo.data.length === 1) { const analysis = analysisInfo.data[0]; - logger.info(`Analysis ID to delete: ${analysis.id}.`); + logger2.info(`Analysis ID to delete: ${analysis.id}.`); try { await client.request( "DELETE /repos/:owner/:repo/code-scanning/analyses/:analysis_id?confirm_delete", @@ -162409,7 +196044,7 @@ async function removeUploadedSarif(uploadFailedSarifResult, logger) { analysis_id: analysis.id } ); - logger.info(`Analysis deleted.`); + logger2.info(`Analysis deleted.`); } catch (e) { const origMessage = getErrorMessage(e); const newMessage = origMessage.includes( @@ -162429,39 +196064,47 @@ async function removeUploadedSarif(uploadFailedSarifResult, logger) { )}` ); } finally { - logger.endGroup(); + logger2.endGroup(); } } else { - logger.warning( + logger2.warning( "Could not delete the uploaded SARIF analysis because a SARIF ID wasn't provided by the API when uploading the SARIF file." ); } } // src/init-action-post.ts -async function run4(startedAt) { - const logger = getActionsLogger(); +async function run4(action) { + const logger2 = action.logger; let config; let uploadFailedSarifResult; let dependencyCachingUsage; try { - restoreInputs(); - const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + const jobStatus2 = getOptionalInput("job-status"); + restoreInputs(logger2); + const tmpDir = getTemporaryDirectory(); + config = await getConfig(tmpDir, logger2); + if (config === void 0) { + logger2.debug( + "Will try to load the configuration file from an aborted 'init' step, since there is no regular one." + ); + config = getAbortedInitConfig(action, tmpDir); + } + const gitHubVersion = config?.gitHubVersion ?? await getGitHubVersion(); + checkGitHubVersionInRange(gitHubVersion, logger2); const repositoryNwo = getRepositoryNwo(); const features = initFeatures( gitHubVersion, repositoryNwo, getTemporaryDirectory(), - logger + logger2 ); - config = await getConfig(getTemporaryDirectory(), logger); if (config === void 0) { - logger.warning( + logger2.warning( "Debugging artifacts are unavailable since the 'init' Action failed before it could produce any." ); } else { - const codeql = await getCodeQL(logger, config.codeQLCmd); + const codeql = await getCodeQL(logger2, config.codeQLCmd); uploadFailedSarifResult = await uploadFailureInfo( tryUploadAllAvailableDebugArtifacts, printDebugLogs, @@ -162469,22 +196112,27 @@ async function run4(startedAt) { config, repositoryNwo, features, - logger + jobStatus2, + action.env, + logger2 ); - if (await isAnalyzingDefaultBranch() && config.dependencyCachingEnabled !== "none" /* None */) { - dependencyCachingUsage = await getDependencyCacheUsage(logger); + if (await isAnalyzingDefaultBranch( + action.env, + config.repositoryRoot + ) && hasConfigKey(config, "dependencyCachingEnabled") && config.dependencyCachingEnabled !== "none" /* None */) { + dependencyCachingUsage = await getDependencyCacheUsage(logger2); } } } catch (unwrappedError) { - const error3 = wrapError(unwrappedError); - core22.setFailed(error3.message); + const error3 = wrapApiConfigurationError(wrapError(unwrappedError)); + core20.setFailed(error3.message); const statusReportBase2 = await createStatusReportBase( - "init-post" /* InitPost */, + action.name, getActionsStatus(error3), - startedAt, + action.startedAt, config, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3.message, error3.stack ); @@ -162493,15 +196141,15 @@ async function run4(startedAt) { } return; } - const jobStatus = getFinalJobStatus(config); - logger.info(`CodeQL job status was ${getJobStatusDisplayName(jobStatus)}.`); + const jobStatus = getFinalJobStatus(action, config); + logger2.info(`CodeQL job status was ${getJobStatusDisplayName(jobStatus)}.`); const statusReportBase = await createStatusReportBase( - "init-post" /* InitPost */, + action.name, "success", - startedAt, + action.startedAt, config, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { const statusReport = { @@ -162510,30 +196158,30 @@ async function run4(startedAt) { job_status: jobStatus, dependency_caching_usage: dependencyCachingUsage }; - logger.info("Sending status report for init-post step."); + logger2.info("Sending status report for init-post step."); await sendStatusReport(statusReport); - logger.info("Status report sent for init-post step."); + logger2.info("Status report sent for init-post step."); } } -function getFinalJobStatus(config) { - const existingJobStatus = getJobStatusFromEnvironment(); +function getFinalJobStatus(action, config) { + const existingJobStatus = getJobStatusFromEnvironment(action.env); if (existingJobStatus !== void 0) { return existingJobStatus; } let jobStatus; - if (process.env["CODEQL_ACTION_ANALYZE_DID_COMPLETE_SUCCESSFULLY" /* ANALYZE_DID_COMPLETE_SUCCESSFULLY */] === "true") { - core22.exportVariable("CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */, "JOB_STATUS_SUCCESS" /* SuccessStatus */); + if (action.env.getOptional("CODEQL_ACTION_ANALYZE_DID_COMPLETE_SUCCESSFULLY" /* ANALYZE_DID_COMPLETE_SUCCESSFULLY */) === "true") { + action.env.export("CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */, "JOB_STATUS_SUCCESS" /* SuccessStatus */); jobStatus = "JOB_STATUS_SUCCESS" /* SuccessStatus */; } else if (config !== void 0) { jobStatus = "JOB_STATUS_CONFIGURATION_ERROR" /* ConfigErrorStatus */; } else { jobStatus = "JOB_STATUS_UNKNOWN" /* UnknownStatus */; } - core22.exportVariable("CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */, jobStatus); + action.env.export("CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */, jobStatus); return jobStatus; } -function getJobStatusFromEnvironment() { - const jobStatusFromEnvironment = process.env["CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */]; +function getJobStatusFromEnvironment(env) { + const jobStatusFromEnvironment = env.getOptional("CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */); if (jobStatusFromEnvironment !== void 0) { if (Object.values(JobStatus).includes(jobStatusFromEnvironment)) { return jobStatusFromEnvironment; @@ -162542,41 +196190,33 @@ function getJobStatusFromEnvironment() { } return void 0; } +var initPost = { + name: "init-post" /* InitPost */, + run: run4 +}; async function runWrapper5() { - const startedAt = /* @__PURE__ */ new Date(); - const logger = getActionsLogger(); - try { - await run4(startedAt); - } catch (error3) { - core22.setFailed(`init post action failed: ${wrapError(error3).message}`); - await sendUnhandledErrorStatusReport( - "init-post" /* InitPost */, - startedAt, - error3, - logger - ); - } + return await runInActions(initPost); } // src/resolve-environment-action.ts -var core23 = __toESM(require_core()); +var core21 = __toESM(require_core()); // src/resolve-environment.ts -async function runResolveBuildEnvironment(cmd, logger, workingDir, language) { - logger.startGroup(`Attempting to resolve build environment for ${language}`); - const codeql = await getCodeQL(logger, cmd); +async function runResolveBuildEnvironment(cmd, logger2, workingDir, language) { + logger2.startGroup(`Attempting to resolve build environment for ${language}`); + const codeql = await getCodeQL(logger2, cmd); if (workingDir !== void 0) { - logger.info(`Using ${workingDir} as the working directory.`); + logger2.info(`Using ${workingDir} as the working directory.`); } const result = await codeql.resolveBuildEnvironment(workingDir, language); - logger.endGroup(); + logger2.endGroup(); return result; } // src/resolve-environment-action.ts var ENVIRONMENT_OUTPUT_NAME = "environment"; async function run5(startedAt) { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); let config; try { const statusReportBase2 = await createStatusReportBase( @@ -162584,16 +196224,16 @@ async function run5(startedAt) { "starting", startedAt, config, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase2 !== void 0) { await sendStatusReport(statusReportBase2); } const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); checkActionVersion(getActionVersion(), gitHubVersion); - config = await getConfig(getTemporaryDirectory(), logger); + config = await getConfig(getTemporaryDirectory(), logger2); if (config === void 0) { throw new ConfigurationError( "Config file could not be found at expected location. Has the 'init' action been called?" @@ -162602,20 +196242,20 @@ async function run5(startedAt) { const workingDirectory = getOptionalInput("working-directory"); const result = await runResolveBuildEnvironment( config.codeQLCmd, - logger, + logger2, workingDirectory, getRequiredInput("language") ); - core23.setOutput(ENVIRONMENT_OUTPUT_NAME, result); + core21.setOutput(ENVIRONMENT_OUTPUT_NAME, result); } catch (unwrappedError) { const error3 = wrapError(unwrappedError); if (error3 instanceof CliError) { - core23.setOutput(ENVIRONMENT_OUTPUT_NAME, {}); - logger.warning( + core21.setOutput(ENVIRONMENT_OUTPUT_NAME, {}); + logger2.warning( `Failed to resolve a build environment suitable for automatically building your code. ${error3.message}` ); } else { - core23.setFailed( + core21.setFailed( `Failed to resolve a build environment suitable for automatically building your code. ${error3.message}` ); const statusReportBase2 = await createStatusReportBase( @@ -162623,8 +196263,8 @@ async function run5(startedAt) { getActionsStatus(error3), startedAt, config, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3.message, error3.stack ); @@ -162639,8 +196279,8 @@ async function run5(startedAt) { "success", startedAt, config, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { await sendStatusReport(statusReportBase); @@ -162648,11 +196288,11 @@ async function run5(startedAt) { } async function runWrapper6() { const startedAt = /* @__PURE__ */ new Date(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); try { await run5(startedAt); } catch (error3) { - core23.setFailed( + core21.setFailed( `${"resolve-environment" /* ResolveEnvironment */} action failed: ${getErrorMessage( error3 )}` @@ -162661,22 +196301,22 @@ async function runWrapper6() { "resolve-environment" /* ResolveEnvironment */, startedAt, error3, - logger + logger2 ); } await checkForTimeout(); } // src/setup-codeql-action.ts -var core24 = __toESM(require_core()); -async function sendCompletedStatusReport3(startedAt, toolsInput, toolsDownloadStatusReport, toolsFeatureFlagsValid, toolsSource, toolsVersion, logger, error3) { +var core22 = __toESM(require_core()); +async function sendCompletedStatusReport3(startedAt, toolsInput, toolsDownloadStatusReport, toolsFeatureFlagsValid, toolsSource, toolsVersion, logger2, error3) { const statusReportBase = await createStatusReportBase( "setup-codeql" /* SetupCodeQL */, getActionsStatus(error3), startedAt, void 0, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3?.message, error3?.stack ); @@ -162693,17 +196333,14 @@ async function sendCompletedStatusReport3(startedAt, toolsInput, toolsDownloadSt if (toolsInput !== void 0) { initStatusReport.computed_inputs.tools = toolsInput; } - const initToolsDownloadFields = {}; - if (toolsDownloadStatusReport?.downloadDurationMs !== void 0) { - initToolsDownloadFields.tools_download_duration_ms = toolsDownloadStatusReport.downloadDurationMs; - } - if (toolsFeatureFlagsValid !== void 0) { - initToolsDownloadFields.tools_feature_flags_valid = toolsFeatureFlagsValid; - } + const initToolsDownloadFields = createInitToolsDownloadFields( + toolsDownloadStatusReport, + toolsFeatureFlagsValid + ); await sendStatusReport({ ...initStatusReport, ...initToolsDownloadFields }); } async function run6(actionState) { - const { logger, startedAt } = actionState; + const { logger: logger2, startedAt } = actionState; let codeql; let toolsInput; let toolsDownloadStatusReport; @@ -162711,36 +196348,37 @@ async function run6(actionState) { let toolsSource; let toolsVersion; try { - initializeEnvironment(getActionVersion()); + actionState.env.initialise(getActionVersion()); const apiDetails = { auth: getRequiredInput("token"), externalRepoAuth: getOptionalInput("external-repository-token"), - url: getRequiredEnvParam("GITHUB_SERVER_URL"), - apiURL: getRequiredEnvParam("GITHUB_API_URL") + ...getCurrentInstance(actionState.env) }; const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); checkActionVersion(getActionVersion(), gitHubVersion); const repositoryNwo = getRepositoryNwo(); const features = initFeatures( gitHubVersion, repositoryNwo, getTemporaryDirectory(), - logger + logger2 ); const repositoryPropertiesResult = await loadRepositoryProperties( repositoryNwo, - logger + logger2 ); const repositoryProperties = repositoryPropertiesResult.orElse({}); - const actionStateWithFeatures = { ...actionState, features }; + const actionStateWithFeatures = extendActionState(actionState, { + features + }); const statusReportBase = await createStatusReportBase( "setup-codeql" /* SetupCodeQL */, "starting", startedAt, void 0, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { await sendStatusReport(statusReportBase); @@ -162754,7 +196392,7 @@ async function run6(actionState) { const rawLanguages = getRawLanguagesNoAutodetect( getOptionalInput("languages") ); - const analysisKinds = await getAnalysisKinds(logger, features); + const analysisKinds = await getAnalysisKinds(logger2, features); const initCodeQLResult = await initCodeQL( toolsInput?.value, apiDetails, @@ -162762,27 +196400,32 @@ async function run6(actionState) { gitHubVersion.type, codeQLDefaultVersionInfo, rawLanguages, + // CodeQL resolves the dependencies of queries that aren't in compiled packs from the bundle, + // so the queries that the workflow runs with this CLI may need library packs for languages + // other than those in the `languages` input. That input therefore only informs the choice of + // CLI version. + "the 'setup-codeql' Action can't tell whether the queries that the workflow runs will need library packs for other languages", analysisKinds.length === 1 && analysisKinds[0] === "code-scanning" /* CodeScanning */, features, - logger + logger2 ); codeql = initCodeQLResult.codeql; toolsDownloadStatusReport = initCodeQLResult.toolsDownloadStatusReport; toolsVersion = initCodeQLResult.toolsVersion; toolsSource = initCodeQLResult.toolsSource; - core24.setOutput("codeql-path", codeql.getPath()); - core24.setOutput("codeql-version", (await codeql.getVersion()).version); - core24.exportVariable("CODEQL_ACTION_SETUP_CODEQL_HAS_RUN" /* SETUP_CODEQL_ACTION_HAS_RUN */, "true"); + core22.setOutput("codeql-path", codeql.getPath()); + core22.setOutput("codeql-version", (await codeql.getVersion()).version); + actionState.env.export("CODEQL_ACTION_SETUP_CODEQL_HAS_RUN" /* SETUP_CODEQL_ACTION_HAS_RUN */, "true"); } catch (unwrappedError) { const error3 = wrapError(unwrappedError); - core24.setFailed(error3.message); + core22.setFailed(error3.message); const statusReportBase = await createStatusReportBase( "setup-codeql" /* SetupCodeQL */, error3 instanceof ConfigurationError ? "user-error" : "failure", startedAt, void 0, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3.message, error3.stack ); @@ -162798,7 +196441,7 @@ async function run6(actionState) { toolsFeatureFlagsValid, toolsSource, toolsVersion, - logger + logger2 ); } var setupCodeQL2 = { @@ -162813,54 +196456,32 @@ async function runWrapper7() { // src/start-proxy-action.ts var import_child_process2 = require("child_process"); var path29 = __toESM(require("path")); -var core27 = __toESM(require_core()); +var core25 = __toESM(require_core()); // src/start-proxy.ts var path27 = __toESM(require("path")); -var core26 = __toESM(require_core()); var toolcache4 = __toESM(require_tool_cache()); -// src/start-proxy/validation.ts -var core25 = __toESM(require_core()); -function cloneCredential(schema, obj) { - const result = {}; - for (const key of Object.keys(schema)) { - if (!isDefined2(obj[key])) { - continue; - } - result[key] = obj[key]; - } - return result; -} -function getAuthConfig(config) { - for (const oidcSchema of oidcSchemas) { - if (validateSchema(oidcSchema.schema, config)) { - return cloneCredential(oidcSchema.schema, config); - } - } - if (isToken(config)) { - if (isDefined2(config.token)) { - core25.setSecret(config.token); - } - return cloneCredential(tokenSchema, config); - } else { - let username = void 0; - let password = void 0; - if ("password" in config && isString(config.password)) { - core25.setSecret(config.password); - password = config.password; - } - if ("username" in config && isString(config.username)) { - username = config.username; - } - return { - username, - password +// src/start-proxy/status-report.ts +var core23 = __toESM(require_core()); +async function sendSuccessStatusReport(startedAt, config, registry_types, status, logger2) { + const statusReportBase = await createStatusReportBase( + "start-proxy" /* StartProxy */, + "success", + startedAt, + config, + await checkDiskUsage(logger2), + logger2 + ); + if (statusReportBase !== void 0) { + const statusReport = { + ...statusReportBase, + registry_types: registry_types.sort().join(","), + start_proxy: status }; + await sendStatusReport(statusReport); } } - -// src/start-proxy.ts function getStartProxyErrorMessage(errorType) { switch (errorType) { case 0 /* DownloadFailed */: @@ -162878,32 +196499,15 @@ var StartProxyError = class extends Error { this.errorType = errorType; } }; -async function sendSuccessStatusReport(startedAt, config, registry_types, logger) { - const statusReportBase = await createStatusReportBase( - "start-proxy" /* StartProxy */, - "success", - startedAt, - config, - await checkDiskUsage(logger), - logger - ); - if (statusReportBase !== void 0) { - const statusReport = { - ...statusReportBase, - registry_types: registry_types.join(",") - }; - await sendStatusReport(statusReport); - } -} function getSafeErrorMessage(error3) { if (error3 instanceof StartProxyError) { return getStartProxyErrorMessage(error3.errorType); } return `Error from start-proxy Action omitted (${error3.constructor.name}).`; } -async function sendFailedStatusReport(logger, startedAt, language, unwrappedError) { +async function sendFailedStatusReport(logger2, startedAt, language, unwrappedError) { const error3 = wrapError(unwrappedError); - core26.setFailed(`start-proxy action failed: ${error3.message}`); + core23.setFailed(`start-proxy action failed: ${error3.message}`); const statusReportMessage = getSafeErrorMessage(error3); const errorStatusReportBase = await createStatusReportBase( "start-proxy" /* StartProxy */, @@ -162912,17 +196516,57 @@ async function sendFailedStatusReport(logger, startedAt, language, unwrappedErro { languages: language === void 0 ? void 0 : [language] }, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, statusReportMessage ); if (errorStatusReportBase !== void 0) { await sendStatusReport(errorStatusReportBase); } } + +// src/start-proxy/validation.ts +var core24 = __toESM(require_core()); +function cloneCredential(schema, obj) { + const result = {}; + for (const key of Object.keys(schema)) { + if (!isDefined2(obj[key])) { + continue; + } + result[key] = obj[key]; + } + return result; +} +function getAuthConfig(config) { + for (const oidcSchema of oidcSchemas) { + if (validateSchema(oidcSchema.schema, config)) { + return cloneCredential(oidcSchema.schema, config); + } + } + if (isToken(config)) { + if (isDefined2(config.token)) { + core24.setSecret(config.token); + } + return cloneCredential(tokenSchema, config); + } else { + let username = void 0; + let password = void 0; + if ("password" in config && isString(config.password)) { + core24.setSecret(config.password); + password = config.password; + } + if ("username" in config && isString(config.username)) { + username = config.username; + } + return { + username, + password + }; + } +} + +// src/start-proxy.ts var UPDATEJOB_PROXY = "update-job-proxy"; -var UPDATEJOB_PROXY_VERSION = "v2.0.20250624110901"; -var UPDATEJOB_PROXY_URL_PREFIX = "https://github.com/github/codeql-action/releases/download/codeql-bundle-v2.22.0/"; function isPAT(value) { return isAuthToken(value, [ GITHUB_PAT_CLASSIC_PATTERN, @@ -162962,24 +196606,24 @@ function getRegistryAddress(registry) { ); } } -function getCredentials(logger, registrySecrets, registriesCredentials, language) { +function getCredentials(logger2, registrySecrets, registriesCredentials, language) { const registryTypeForLanguage = language ? LANGUAGE_TO_REGISTRY_TYPE[language] : void 0; let credentialsStr; if (registriesCredentials !== void 0) { - logger.info(`Using registries_credentials input.`); + logger2.info(`Using registries_credentials input.`); credentialsStr = Buffer.from(registriesCredentials, "base64").toString(); } else if (registrySecrets !== void 0) { - logger.info(`Using registry_secrets input.`); + logger2.info(`Using registry_secrets input.`); credentialsStr = registrySecrets; } else { - logger.info(`No credentials defined.`); + logger2.info(`No credentials defined.`); return []; } let parsed; try { parsed = parseString(credentialsStr); } catch { - logger.error("Failed to parse the credentials data."); + logger2.error("Failed to parse the credentials data."); throw new ConfigurationError("Invalid credentials format."); } if (!isArray(parsed)) { @@ -162989,7 +196633,7 @@ function getCredentials(logger, registrySecrets, registriesCredentials, language } const out = []; for (const e of parsed) { - if (e === null || !isObject(e)) { + if (e === null || !isObject2(e)) { throw new ConfigurationError("Invalid credentials - must be an object"); } if (!isDefined2(e.type) || !isString(e.type)) { @@ -163000,12 +196644,12 @@ function getCredentials(logger, registrySecrets, registriesCredentials, language if (!ALWAYS_ENABLED_REGISTRY_TYPE.some((t) => t === e.type) && registryTypeForLanguage && !registryTypeForLanguage.some((t) => t === e.type)) { continue; } - const isPrintable2 = (str) => { + const isPrintable = (str) => { return str ? /^[\x20-\x7E]*$/.test(str) : true; }; for (const key of Object.keys(e)) { const val = e[key]; - if (typeof val === "string" && !isPrintable2(val)) { + if (typeof val === "string" && !isPrintable(val)) { throw new ConfigurationError( "Invalid credentials - fields must contain only printable characters" ); @@ -163015,7 +196659,7 @@ function getCredentials(logger, registrySecrets, registriesCredentials, language const passwordIsPAT = hasUsernameAndPassword(authConfig) && isDefined2(authConfig.password) && isPAT(authConfig.password); const tokenIsPAT = hasToken(authConfig) && isDefined2(authConfig.token) && isPAT(authConfig.token); if (noUsername && (passwordIsPAT || tokenIsPAT)) { - logger.warning( + logger2.warning( `A ${e.type} private registry is configured for ${e.host || e.url} using a GitHub Personal Access Token (PAT), but no username was provided. This may not work correctly. When configuring a private registry using a PAT, select "Username and password" and enter the username of the user who generated the PAT.` ); } @@ -163037,65 +196681,53 @@ function getCredentials(logger, registrySecrets, registriesCredentials, language } return out; } -function getProxyPackage() { - const platform2 = process.platform === "win32" ? "win64" : process.platform === "darwin" ? "osx64" : "linux64"; +function getProxyPackage(platform2) { return `${UPDATEJOB_PROXY}-${platform2}.tar.gz`; } -function getFallbackUrl(proxyPackage) { - return `${UPDATEJOB_PROXY_URL_PREFIX}${proxyPackage}`; -} -async function getReleaseByVersion(version) { - return getApiClient().rest.repos.getReleaseByTag({ - owner: "github", - repo: "codeql-action", - tag: version - }); -} async function getCliVersionFromFeatures(features) { const gitHubVersion = await getGitHubVersion(); return await features.getEnabledDefaultCliVersions(gitHubVersion.type); } -async function getDownloadUrl(logger, features) { - const proxyPackage = getProxyPackage(); +async function getDownloadUrl(action, apiDetails) { + let platform2 = getBundlePlatform(action.platform, action.arch); + if (platform2 === void 0) { + action.logger.warning( + `Unsupported platform ${action.platform} on architecture ${action.arch}, defaulting to ${"linux64" /* Linux64 */}` + ); + platform2 = "linux64" /* Linux64 */; + } + const proxyPackage = getProxyPackage(platform2); try { - const useFeaturesToDetermineCLI = await features.getValue( + const useFeaturesToDetermineCLI = await action.features.getValue( "start_proxy_use_features_release" /* StartProxyUseFeaturesRelease */ ); - const versionInfo = useFeaturesToDetermineCLI ? (await getCliVersionFromFeatures(features)).enabledVersions[0] : { + const versionInfo = useFeaturesToDetermineCLI ? (await getCliVersionFromFeatures(action.features)).enabledVersions[0] : { cliVersion, tagName: bundleVersion }; - const cliRelease = await getReleaseByVersion(versionInfo.tagName); - for (const asset of cliRelease.data.assets) { - if (asset.name === proxyPackage) { - logger.info( - `Found '${proxyPackage}' in release '${versionInfo.tagName}' at '${asset.url}'` - ); - return { - url: asset.url, - // The `update-job-proxy` doesn't have a version as such. Since we now bundle it - // with CodeQL CLI bundle releases, we use the corresponding CLI version to - // differentiate between (potentially) different versions of `update-job-proxy`. - version: versionInfo.cliVersion - }; - } - } + const proxyAssetUrl = await getCodeQLAssetDownloadURL( + action, + apiDetails, + versionInfo.tagName, + proxyPackage, + "private registry proxy" + ); + return { + url: proxyAssetUrl, + // The `update-job-proxy` doesn't have a version as such. Since we now bundle it + // with CodeQL CLI bundle releases, we use the corresponding CLI version to + // differentiate between (potentially) different versions of `update-job-proxy`. + version: versionInfo.cliVersion + }; } catch (ex) { - logger.warning( + throw new Error( `Failed to retrieve information about the linked release: ${getErrorMessage(ex)}` ); } - logger.info( - `Did not find '${proxyPackage}' in the linked release, falling back to hard-coded version.` - ); - return { - url: getFallbackUrl(proxyPackage), - version: UPDATEJOB_PROXY_VERSION - }; } -async function downloadProxy(logger, url2, authorization) { +async function downloadProxy(logger2, url2, authorization) { try { - return toolcache4.downloadTool( + return await toolcache4.downloadTool( url2, /* dest: */ void 0, @@ -163105,27 +196737,27 @@ async function downloadProxy(logger, url2, authorization) { } ); } catch (error3) { - logger.error( + logger2.error( `Failed to download proxy archive from ${url2}: ${getErrorMessage(error3)}` ); throw new StartProxyError(0 /* DownloadFailed */); } } -async function extractProxy(logger, archive) { +async function extractProxy(logger2, archive) { try { return await toolcache4.extractTar(archive); } catch (error3) { - logger.error( + logger2.error( `Failed to extract proxy archive from ${archive}: ${getErrorMessage(error3)}` ); throw new StartProxyError(1 /* ExtractionFailed */); } } -async function cacheProxy(logger, source, filename, version) { +async function cacheProxy(logger2, source, filename, version) { try { return await toolcache4.cacheDir(source, filename, version); } catch (error3) { - logger.error( + logger2.error( `Failed to add proxy archive from ${source} to toolcache: ${getErrorMessage(error3)}` ); throw new StartProxyError(2 /* CacheFailed */); @@ -163134,27 +196766,43 @@ async function cacheProxy(logger, source, filename, version) { function getProxyFilename() { return process.platform === "win32" ? `${UPDATEJOB_PROXY}.exe` : UPDATEJOB_PROXY; } -async function getProxyBinaryPath(logger, features) { - const proxyFileName = getProxyFilename(); - const proxyInfo = await getDownloadUrl(logger, features); - let proxyBin = toolcache4.find(proxyFileName, proxyInfo.version); - if (!proxyBin) { - const apiDetails = getApiDetails(); - const authorization = getAuthorizationHeaderFor( - logger, - apiDetails, - proxyInfo.url - ); - const temp = await downloadProxy(logger, proxyInfo.url, authorization); - const extracted = await extractProxy(logger, temp); - proxyBin = await cacheProxy( - logger, - extracted, - proxyFileName, - proxyInfo.version +async function getProxyBinaryPath(action, apiDetails) { + const logger2 = action.logger; + logger2.startGroup("Setting up authentication proxy"); + try { + const proxyFileName = getProxyFilename(); + const proxyInfo = await getDownloadUrl(action, apiDetails); + logger2.info( + `Using authentication proxy from CodeQL release ${proxyInfo.version}.` ); + let proxyDir = toolcache4.find(proxyFileName, proxyInfo.version); + if (!proxyDir) { + logger2.info( + `Authentication proxy is not in the toolcache. Will try to download it from '${proxyInfo.url}'.` + ); + const authorization = getAuthorizationHeaderFor( + logger2, + apiDetails, + proxyInfo.url + ); + const temp = await downloadProxy(logger2, proxyInfo.url, authorization); + logger2.info(`Downloaded the authentication proxy asset to '${temp}'.`); + const extracted = await extractProxy(logger2, temp); + proxyDir = await cacheProxy( + logger2, + extracted, + proxyFileName, + proxyInfo.version + ); + logger2.info(`Extracted the authentication proxy to '${proxyDir}'.`); + } + return { + path: path27.join(proxyDir, proxyFileName), + version: proxyInfo.version + }; + } finally { + logger2.endGroup(); } - return path27.join(proxyBin, proxyFileName); } // src/start-proxy/ca.ts @@ -163219,24 +196867,24 @@ function generateCertificateAuthority() { } // src/start-proxy/environment.ts -var fs31 = __toESM(require("fs")); +var fs33 = __toESM(require("fs")); var path28 = __toESM(require("path")); -var toolrunner5 = __toESM(require_toolrunner()); -var io8 = __toESM(require_io()); -function checkEnvVar(logger, name) { +var toolrunner6 = __toESM(require_toolrunner()); +var io9 = __toESM(require_io()); +function checkEnvVar(logger2, name) { const value = process.env[name]; if (isDefined2(value)) { const url2 = URL.parse(value); if (isDefined2(url2)) { url2.username = ""; url2.password = ""; - logger.info(`Environment variable '${name}' is set to '${url2}'.`); + logger2.info(`Environment variable '${name}' is set to '${url2}'.`); } else { - logger.info(`Environment variable '${name}' is set to '${value}'.`); + logger2.info(`Environment variable '${name}' is set to '${value}'.`); } return true; } else { - logger.debug(`Environment variable '${name}' is not set.`); + logger2.debug(`Environment variable '${name}' is not set.`); return false; } } @@ -163264,9 +196912,9 @@ var JAVA_PROXY_ENV_VARS = [ "JDK_JAVA_OPTIONS" /* JDK_JAVA_OPTIONS */, "_JAVA_OPTIONS" /* _JAVA_OPTIONS */ ]; -function checkJavaEnvVars(logger) { +function checkJavaEnvVars(logger2) { for (const envVar of JAVA_PROXY_ENV_VARS) { - checkEnvVar(logger, envVar); + checkEnvVar(logger2, envVar); } } function discoverActionsJdks() { @@ -163282,7 +196930,7 @@ function discoverActionsJdks() { } return paths; } -function checkJdkSettings(logger, jdkHome) { +function checkJdkSettings(logger2, jdkHome) { const filesToCheck = [ // JDK 9+ path28.join("conf", "net.properties"), @@ -163292,29 +196940,29 @@ function checkJdkSettings(logger, jdkHome) { for (const fileToCheck of filesToCheck) { const file = path28.join(jdkHome, fileToCheck); try { - if (fs31.existsSync(file)) { - logger.debug(`Found '${file}'.`); - const lines = String(fs31.readFileSync(file)).split("\n"); + if (fs33.existsSync(file)) { + logger2.debug(`Found '${file}'.`); + const lines = String(fs33.readFileSync(file)).split("\n"); for (const line of lines) { for (const property of javaProperties) { if (line.startsWith(`${property}=`)) { - logger.info(`Found '${line.trimEnd()}' in '${file}'.`); + logger2.info(`Found '${line.trimEnd()}' in '${file}'.`); } } } } else { - logger.debug(`'${file}' does not exist.`); + logger2.debug(`'${file}' does not exist.`); } } catch (err) { - logger.debug(`Failed to read '${file}': ${getErrorMessage(err)}`); + logger2.debug(`Failed to read '${file}': ${getErrorMessage(err)}`); } } } -async function showJavaSettings(logger) { +async function showJavaSettings(logger2) { try { - const java = await io8.which("java", true); + const java = await io9.which("java", true); let output = ""; - await new toolrunner5.ToolRunner( + await new toolrunner6.ToolRunner( java, ["-XshowSettings:all", "-XshowSettings:security:all", "-version"], { @@ -163329,11 +196977,11 @@ async function showJavaSettings(logger) { } } ).exec(); - logger.startGroup("Java settings"); - logger.info(output); - logger.endGroup(); + logger2.startGroup("Java settings"); + logger2.info(output); + logger2.endGroup(); } catch (err) { - logger.debug(`Failed to query java settings: ${getErrorMessage(err)}`); + logger2.debug(`Failed to query java settings: ${getErrorMessage(err)}`); } } var ProxyEnvVars = /* @__PURE__ */ ((ProxyEnvVars2) => { @@ -163342,27 +196990,27 @@ var ProxyEnvVars = /* @__PURE__ */ ((ProxyEnvVars2) => { ProxyEnvVars2["ALL_PROXY"] = "ALL_PROXY"; return ProxyEnvVars2; })(ProxyEnvVars || {}); -function checkProxyEnvVars(logger) { +function checkProxyEnvVars(logger2) { for (const envVar of Object.values(ProxyEnvVars)) { - checkEnvVar(logger, envVar); - checkEnvVar(logger, envVar.toLowerCase()); + checkEnvVar(logger2, envVar); + checkEnvVar(logger2, envVar.toLowerCase()); } } -async function checkProxyEnvironment(logger, language) { - checkProxyEnvVars(logger); +async function checkProxyEnvironment(logger2, language) { + checkProxyEnvVars(logger2); if (language === void 0 || language === "java" /* java */) { - checkJavaEnvVars(logger); - await showJavaSettings(logger); + checkJavaEnvVars(logger2); + await showJavaSettings(logger2); const jdks = discoverActionsJdks(); for (const jdk of jdks) { - checkJdkSettings(logger, jdk); + checkJdkSettings(logger2, jdk); } } } // src/start-proxy/reachability.ts var https2 = __toESM(require("https")); -var import_https_proxy_agent = __toESM(require_dist3()); +var import_https_proxy_agent = __toESM(require_dist2()); var connectionTestConfig = { nuget_feed: { path: "v3/index.json" } }; @@ -163390,7 +197038,7 @@ var NetworkReachabilityBackend = class { proxy; agent; async checkConnection(url2) { - return new Promise((resolve14, reject) => { + return new Promise((resolve15, reject) => { const req = https2.request( url2, { @@ -163403,7 +197051,7 @@ var NetworkReachabilityBackend = class { (res) => { res.destroy(); if (res.statusCode !== void 0 && res.statusCode < 400) { - resolve14(res.statusCode); + resolve15(res.statusCode); } else { reject(new ReachabilityError(res.statusCode)); } @@ -163420,11 +197068,11 @@ var NetworkReachabilityBackend = class { }); } }; -async function checkConnections(logger, proxy, backend) { +async function checkConnections(logger2, proxy, backend) { const result = /* @__PURE__ */ new Set(); if (proxy.registries.length === 0) return result; - logger.startGroup("Testing connections via the proxy"); - logger.info( + logger2.startGroup("Testing connections via the proxy"); + logger2.info( `The connection tests performed here are best-effort only and failures here may not affect the subsequent analysis. See ${"https://docs.github.com/en/code-security/reference/code-scanning/code-scanning-logs#diagnostic-information-for-private-package-registries" /* PRIVATE_REGISTRY_LOGS */} for more information.` ); try { @@ -163436,77 +197084,77 @@ async function checkConnections(logger, proxy, backend) { const address = getAddressString(registry); const url2 = URL.parse(address); if (url2 === null) { - logger.info( + logger2.info( `Skipping check for ${address} since it is not a valid URL.` ); continue; } const testUrl = makeTestUrl(config, url2); try { - logger.debug(`Testing connection to ${url2}...`); + logger2.debug(`Testing connection to ${url2}...`); const statusCode = await backend.checkConnection(testUrl); - logger.info(`Successfully tested connection to ${url2} (${statusCode})`); + logger2.info(`Successfully tested connection to ${url2} (${statusCode})`); result.add(registry); } catch (e) { if (e instanceof ReachabilityError && e.statusCode !== void 0) { - logger.info(`Connection test to ${url2} failed. (${e.statusCode})`); + logger2.info(`Connection test to ${url2} failed. (${e.statusCode})`); } else { - logger.warning( + logger2.warning( `Connection test to ${url2} failed: ${getErrorMessage(e)}` ); } } } - logger.debug(`Finished testing connections to private registries.`); + logger2.debug(`Finished testing connections to private registries.`); } catch (e) { - logger.warning( + logger2.warning( `Failed to test connections to private registries: ${getErrorMessage(e)}` ); } - logger.endGroup(); + logger2.endGroup(); return result; } // src/start-proxy-action.ts async function run7(action) { const startedAt = action.startedAt; - const logger = action.logger; + const logger2 = action.logger; let features; let language; try { persistInputs(); const tempDir = getTemporaryDirectory(); const proxyLogFilePath = path29.resolve(tempDir, "proxy.log"); - core27.saveState("proxy-log-file", proxyLogFilePath); + core25.saveState("proxy-log-file", proxyLogFilePath); const repositoryNwo = getRepositoryNwo(); const gitHubVersion = await getGitHubVersion(); features = initFeatures( gitHubVersion, repositoryNwo, getTemporaryDirectory(), - logger + logger2 ); const languageInput = getOptionalInput("language"); language = languageInput ? parseBuiltInLanguage(languageInput) : void 0; const credentials = getCredentials( - logger, + logger2, getOptionalInput("registry_secrets"), getOptionalInput("registries_credentials"), language ); if (credentials.length === 0) { - logger.info("No credentials found, skipping proxy setup."); + logger2.info("No credentials found, skipping proxy setup."); return; } - logger.info( + logger2.info( `Credentials loaded for the following registries: ${credentials.map((c) => credentialToStr(c)).join("\n")}` ); - if (core27.isDebug() || isInTestMode()) { + if (core25.isDebug() || isInTestMode()) { try { - await checkProxyEnvironment(logger, language); + await checkProxyEnvironment(logger2, language); } catch (err) { - logger.debug( + logger2.debug( `Unable to inspect runner environment: ${getErrorMessage(err)}` ); } @@ -163516,24 +197164,29 @@ async function run7(action) { all_credentials: credentials, ca }; - const proxyBin = await getProxyBinaryPath(logger, features); + const actionWithFeatures = extendActionState(action, { features }); + const proxyBin = await getProxyBinaryPath( + actionWithFeatures, + getApiDetails(action.env) + ); const proxyInfo = await startProxy( - proxyBin, + proxyBin.path, proxyConfig, proxyLogFilePath, - logger + logger2 ); - await checkConnections(logger, proxyInfo); + await checkConnections(logger2, proxyInfo); await sendSuccessStatusReport( startedAt, { languages: language === void 0 ? void 0 : [language] }, proxyConfig.all_credentials.map((c) => c.type), - logger + { proxy_version: proxyBin.version }, + logger2 ); } catch (unwrappedError) { - await sendFailedStatusReport(logger, startedAt, language, unwrappedError); + await sendFailedStatusReport(logger2, startedAt, language, unwrappedError); } } var startProxyAction = { @@ -163544,7 +197197,7 @@ var startProxyAction = { async function runWrapper8() { await runInActions(startProxyAction); } -async function startProxy(binPath, config, logFilePath, logger) { +async function startProxy(binPath, config, logFilePath, logger2) { const host = "127.0.0.1"; let port = 49152; let subprocess = void 0; @@ -163561,7 +197214,7 @@ async function startProxy(binPath, config, logFilePath, logger) { ); subprocess.unref(); if (subprocess.pid) { - core27.saveState("proxy-process-pid", `${subprocess.pid}`); + core25.saveState("proxy-process-pid", `${subprocess.pid}`); } subprocess.on("error", (error3) => { subprocessError = error3; @@ -163579,48 +197232,42 @@ async function startProxy(binPath, config, logFilePath, logger) { if (subprocessError) { throw subprocessError; } - logger.info(`Proxy started on ${host}:${port}`); - core27.setOutput("proxy_host", host); - core27.setOutput("proxy_port", port.toString()); - core27.setOutput("proxy_ca_certificate", config.ca.cert); + logger2.info(`Proxy started on ${host}:${port}`); + core25.setOutput("proxy_host", host); + core25.setOutput("proxy_port", port.toString()); + core25.setOutput("proxy_ca_certificate", config.ca.cert); const registry_urls = config.all_credentials.filter((credential) => credential.url !== void 0).map((credential) => ({ type: credential.type, url: credential.url, "replaces-base": credential["replaces-base"] })); - core27.setOutput("proxy_urls", JSON.stringify(registry_urls)); + core25.setOutput("proxy_urls", JSON.stringify(registry_urls)); return { host, port, cert: config.ca.cert, registries: registry_urls }; } // src/start-proxy-action-post.ts -var core28 = __toESM(require_core()); +var core26 = __toESM(require_core()); async function runWrapper9() { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); try { - restoreInputs(); - const pid = core28.getState("proxy-process-pid"); + restoreInputs(logger2); + const pid = core26.getState("proxy-process-pid"); if (pid) { process.kill(Number(pid)); } const config = await getConfig( getTemporaryDirectory(), - logger + logger2 ); - if (config?.debugMode || core28.isDebug()) { - const logFilePath = core28.getState("proxy-log-file"); - logger.info( + if (config?.debugMode || core26.isDebug()) { + const logFilePath = core26.getState("proxy-log-file"); + logger2.info( "Debug mode is on. Uploading proxy log as Actions debugging artifact..." ); - if (config?.gitHubVersion.type === void 0) { - logger.warning( - `Did not upload debug artifacts because cannot determine the GitHub variant running.` - ); - return; - } const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); await uploadArtifacts( - logger, + logger2, [logFilePath], getTemporaryDirectory(), "proxy-log-file", @@ -163628,22 +197275,22 @@ async function runWrapper9() { ); } } catch (error3) { - logger.warning( + logger2.warning( `start-proxy post-action step failed: ${getErrorMessage(error3)}` ); } } // src/upload-sarif-action.ts -var core29 = __toESM(require_core()); -async function sendSuccessStatusReport2(startedAt, uploadStats, logger) { +var core27 = __toESM(require_core()); +async function sendSuccessStatusReport2(startedAt, uploadStats, logger2) { const statusReportBase = await createStatusReportBase( "upload-sarif" /* UploadSarif */, "success", startedAt, void 0, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { const statusReport = { @@ -163653,26 +197300,28 @@ async function sendSuccessStatusReport2(startedAt, uploadStats, logger) { await sendStatusReport(statusReport); } } -async function run8({ startedAt, logger }) { +async function run8(action) { + const logger2 = action.logger; try { - initializeEnvironment(getActionVersion()); + action.env.initialise(getActionVersion()); const gitHubVersion = await getGitHubVersion(); checkActionVersion(getActionVersion(), gitHubVersion); persistInputs(); + const tempDir = getTemporaryDirectory(); const repositoryNwo = getRepositoryNwo(); const features = initFeatures( gitHubVersion, repositoryNwo, - getTemporaryDirectory(), - logger + tempDir, + logger2 ); const startingStatusReportBase = await createStatusReportBase( "upload-sarif" /* UploadSarif */, "starting", - startedAt, + action.startedAt, void 0, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (startingStatusReportBase !== void 0) { await sendStatusReport(startingStatusReportBase); @@ -163680,9 +197329,11 @@ async function run8({ startedAt, logger }) { const sarifPath = getRequiredInput("sarif_file"); const checkoutPath = getRequiredInput("checkout_path"); const category = getOptionalInput("category"); + const maybeConfig = await getConfig(tempDir, logger2); const uploadResults = await postProcessAndUploadSarif( - logger, + logger2, features, + maybeConfig, "always", checkoutPath, sarifPath, @@ -163695,11 +197346,11 @@ async function run8({ startedAt, logger }) { } const codeScanningResult = uploadResults["code-scanning" /* CodeScanning */]; if (codeScanningResult !== void 0) { - core29.setOutput("sarif-id", codeScanningResult.sarifID); + core27.setOutput("sarif-id", codeScanningResult.sarifID); } - core29.setOutput("sarif-ids", JSON.stringify(uploadResults)); + core27.setOutput("sarif-ids", JSON.stringify(uploadResults)); if (shouldSkipSarifUpload()) { - core29.debug( + core27.debug( "SARIF upload disabled by an environment variable. Waiting for processing is disabled." ); } else if (getRequiredInput("wait-for-processing") === "true") { @@ -163707,26 +197358,26 @@ async function run8({ startedAt, logger }) { await waitForProcessing( getRepositoryNwo(), codeScanningResult.sarifID, - logger + logger2 ); } } await sendSuccessStatusReport2( - startedAt, + action.startedAt, codeScanningResult?.statusReport || {}, - logger + logger2 ); } catch (unwrappedError) { const error3 = isThirdPartyAnalysis("upload-sarif" /* UploadSarif */) && unwrappedError instanceof InvalidSarifUploadError ? new ConfigurationError(unwrappedError.message) : wrapError(unwrappedError); const message = error3.message; - core29.setFailed(message); + core27.setFailed(message); const errorStatusReportBase = await createStatusReportBase( "upload-sarif" /* UploadSarif */, getActionsStatus(error3), - startedAt, + action.startedAt, void 0, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, message, error3.stack ); @@ -163745,33 +197396,27 @@ async function runWrapper10() { } // src/upload-sarif-action-post.ts -var core30 = __toESM(require_core()); +var core28 = __toESM(require_core()); async function runWrapper11() { try { - restoreInputs(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); + restoreInputs(logger2); const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); if (process.env["CODEQL_ACTION_INIT_HAS_RUN" /* INIT_ACTION_HAS_RUN */] !== "true") { if (gitHubVersion.type === void 0) { - core30.warning( + core28.warning( `Did not upload debug artifacts because cannot determine the GitHub variant running.` ); return; } await withGroup( "Uploading combined SARIF debug artifact", - () => uploadCombinedSarifArtifacts( - logger, - gitHubVersion.type, - // The codeqlVersion is not applicable for uploading non-codeql sarif. - // We can assume all versions are safe to upload. - void 0 - ) + () => uploadCombinedSarifArtifacts(logger2, gitHubVersion.type) ); } } catch (error3) { - core30.setFailed( + core28.setFailed( `upload-sarif post-action step failed: ${getErrorMessage(error3)}` ); } @@ -163934,7 +197579,7 @@ tmp/lib/tmp.js: *) js-yaml/dist/js-yaml.mjs: - (*! js-yaml 5.2.3 https://github.com/nodeca/js-yaml @license MIT *) + (*! js-yaml 5.5.0 https://github.com/nodeca/js-yaml @license MIT *) long/index.js: (** diff --git a/package-lock.json b/package-lock.json index c63a1e310e..ca703da546 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "codeql", - "version": "4.37.9", + "version": "4.39.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "codeql", - "version": "4.37.9", + "version": "4.39.3", "license": "MIT", "workspaces": [ "pr-checks" @@ -14,7 +14,7 @@ "dependencies": { "@actions/artifact": "^5.0.3", "@actions/artifact-legacy": "npm:@actions/artifact@^1.1.2", - "@actions/cache": "^5.2.0", + "@actions/cache": "^5.3.0", "@actions/core": "^2.0.3", "@actions/exec": "^2.0.0", "@actions/github": "^8.0.1", @@ -22,28 +22,27 @@ "@actions/http-client": "^3.0.0", "@actions/io": "^2.0.0", "@actions/tool-cache": "^3.0.1", - "@octokit/core": "^7.0.7", - "@octokit/plugin-paginate-rest": "^14.0.0", - "@octokit/plugin-rest-endpoint-methods": "^17.0.0", + "@octokit/core": "^7.0.8", + "@octokit/plugin-paginate-rest": "^16.0.0", + "@octokit/plugin-rest-endpoint-methods": "^18.0.0", "@octokit/plugin-retry": "^8.1.1", "archiver": "^8.0.0", - "fast-deep-equal": "^3.1.3", - "follow-redirects": "^1.16.0", + "follow-redirects": "^1.16.1", "get-folder-size": "^5.0.0", "https-proxy-agent": "^7.0.6", - "js-yaml": "^5.2.3", + "js-yaml": "^5.5.0", "jsonschema": "1.5.0", "long": "^5.3.2", - "node-forge": "^1.4.0", + "node-forge": "^1.4.1", "semver": "^7.8.5", - "undici": "^6.28.0", - "uuid": "^14.0.1" + "undici": "^7.30.1", + "uuid": "^14.0.3" }, "devDependencies": { "@ava/typescript": "6.0.0", - "@eslint/compat": "^2.1.0", + "@eslint/compat": "^2.1.1", "@microsoft/eslint-formatter-sarif": "^3.1.0", - "@octokit/types": "^16.0.0", + "@octokit/types": "^18.0.0", "@types/archiver": "^8.0.0", "@types/follow-redirects": "^1.14.4", "@types/js-yaml": "^4.0.9", @@ -51,29 +50,22 @@ "@types/node-forge": "^1.3.14", "@types/sarif": "^2.1.7", "@types/semver": "^7.8.0", - "@types/sinon": "^22.0.0", + "@types/sinon": "^22.0.1", "ava": "^6.4.1", "esbuild": "^0.28.2", "eslint": "^9.39.5", "eslint-import-resolver-typescript": "^4.4.5", "eslint-plugin-github": "^6.1.2", "eslint-plugin-import-x": "^4.17.1", - "eslint-plugin-jsdoc": "^62.9.0", + "eslint-plugin-jsdoc": "^65.4.0", "eslint-plugin-no-async-foreach": "^0.1.1", - "glob": "^13.0.6", - "globals": "^17.11.0", + "glob": "^14.0.3", + "globals": "^17.13.0", "nock": "^14.0.17", + "prettier": "^3.9.10", "sinon": "^22.1.0", "typescript": "^6.0.3", - "typescript-eslint": "^8.67.0" - } - }, - "node_modules/@aashutoshrathi/word-wrap": { - "version": "1.2.6", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" + "typescript-eslint": "^8.72.0" } }, "node_modules/@actions/artifact": { @@ -374,9 +366,9 @@ "license": "Apache-2.0" }, "node_modules/@actions/artifact/node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "license": "MIT", "dependencies": { "balanced-match": "^1.0.0" @@ -459,19 +451,19 @@ } }, "node_modules/@actions/cache": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@actions/cache/-/cache-5.2.0.tgz", - "integrity": "sha512-1R1Oc8cuDNCygsIP7gLiKLGCymOw/k5FkGQkXZFcLz6/RWyMImkfP0dZX6kjA9SRAmANcKNocI2XrsIaZ1it8w==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@actions/cache/-/cache-5.3.0.tgz", + "integrity": "sha512-VqJBlQFt1lpp7op7o/Z0syWywX9cN8TxjFCPjHyGHmXCiczU5NII5ZdEpGpTelUnOGFG2bO7viUx9q3q7WR/Gg==", "license": "MIT", "dependencies": { - "@actions/core": "^2.0.0", + "@actions/core": "^2.0.3", "@actions/exec": "^2.0.0", "@actions/glob": "^0.5.1", "@actions/http-client": "^3.0.2", "@actions/io": "^2.0.0", "@azure/abort-controller": "^1.1.0", - "@azure/core-rest-pipeline": "^1.22.0", - "@azure/storage-blob": "^12.29.1", + "@azure/core-rest-pipeline": "^1.25.0", + "@azure/storage-blob": "^12.34.0", "@protobuf-ts/runtime-rpc": "^2.11.1", "semver": "^6.3.1" } @@ -517,6 +509,51 @@ "undici": "^6.23.0" } }, + "node_modules/@actions/github/node_modules/@octokit/openapi-types": { + "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==", + "license": "MIT" + }, + "node_modules/@actions/github/node_modules/@octokit/plugin-paginate-rest": { + "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==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^16.0.0" + }, + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "@octokit/core": ">=6" + } + }, + "node_modules/@actions/github/node_modules/@octokit/plugin-rest-endpoint-methods": { + "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==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^16.0.0" + }, + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "@octokit/core": ">=6" + } + }, + "node_modules/@actions/github/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==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^27.0.0" + } + }, "node_modules/@actions/glob": { "version": "0.5.1", "resolved": "https://registry.npmjs.org/@actions/glob/-/glob-0.5.1.tgz", @@ -620,9 +657,9 @@ } }, "node_modules/@azure/core-client": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/@azure/core-client/-/core-client-1.10.1.tgz", - "integrity": "sha512-Nh5PhEOeY6PrnxNPsEHRr9eimxLwgLlpmguQaHKBinFYA/RU9+kOYVOQqOrTsCL+KSxrLLl1gD8Dk5BFW/7l/w==", + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@azure/core-client/-/core-client-1.11.1.tgz", + "integrity": "sha512-2QygG2F76ZpMP2eMztiJvAiFMu71M9rDeU7vO/QKg5Css7MgM4frUOslFjhVjRhbGaCNPtz/S8M6y46/fFKVuQ==", "license": "MIT", "dependencies": { "@azure/abort-controller": "^2.1.2", @@ -634,45 +671,47 @@ "tslib": "^2.6.2" }, "engines": { - "node": ">=20.0.0" + "node": ">=22.0.0" } }, "node_modules/@azure/core-client/node_modules/@azure/abort-controller": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz", - "integrity": "sha512-nBrLsEWm4J2u5LpAPjxADTlq3trDgVZZXHNKabeXZtpq3d3AbN/KGO82R87rdDz5/lYB024rtEf10/q0urNgsA==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.2.0.tgz", + "integrity": "sha512-fNAjWnA/nZ2jz31kxR/AqRaUT8ewHBw/WuBIosK0moMy1C9e5ValbDfFdIxJzVOOYaYkV/b2F1S4H/aHiqfVQg==", "license": "MIT", "dependencies": { "tslib": "^2.6.2" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "node_modules/@azure/core-http-compat": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@azure/core-http-compat/-/core-http-compat-2.3.1.tgz", - "integrity": "sha512-az9BkXND3/d5VgdRRQVkiJb2gOmDU8Qcq4GvjtBmDICNiQ9udFmDk4ZpSB5Qq1OmtDJGlQAfBaS4palFsazQ5g==", + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@azure/core-http-compat/-/core-http-compat-2.5.0.tgz", + "integrity": "sha512-BoSmXPx2er1Ai+wKlDvj29jIQespCNBwEmKyZVHO2kEFsWbGjAjwMCGzug3DJM5/QYIV3vej0S1zcU5bq9fa8w==", "license": "MIT", "dependencies": { - "@azure/abort-controller": "^2.1.2", - "@azure/core-client": "^1.10.0", - "@azure/core-rest-pipeline": "^1.22.0" + "@azure/abort-controller": "^2.1.2" }, "engines": { - "node": ">=20.0.0" + "node": ">=22.0.0" + }, + "peerDependencies": { + "@azure/core-client": "^1.10.0", + "@azure/core-rest-pipeline": "^1.22.0" } }, "node_modules/@azure/core-http-compat/node_modules/@azure/abort-controller": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz", - "integrity": "sha512-nBrLsEWm4J2u5LpAPjxADTlq3trDgVZZXHNKabeXZtpq3d3AbN/KGO82R87rdDz5/lYB024rtEf10/q0urNgsA==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.2.0.tgz", + "integrity": "sha512-fNAjWnA/nZ2jz31kxR/AqRaUT8ewHBw/WuBIosK0moMy1C9e5ValbDfFdIxJzVOOYaYkV/b2F1S4H/aHiqfVQg==", "license": "MIT", "dependencies": { "tslib": "^2.6.2" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "node_modules/@azure/core-lro": { @@ -715,9 +754,9 @@ } }, "node_modules/@azure/core-rest-pipeline": { - "version": "1.22.2", - "resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.22.2.tgz", - "integrity": "sha512-MzHym+wOi8CLUlKCQu12de0nwcq9k9Kuv43j4Wa++CsCpJwps2eeBQwD2Bu8snkxTtDKDx4GwjuR9E8yC8LNrg==", + "version": "1.25.0", + "resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.25.0.tgz", + "integrity": "sha512-bMs8ekJLjX8wPV+9IPBges1SLPyuDtE9g5gLDWOpxzKcoOFQnpLGkbcT1tdw3FaAmDS1gnPmMmJ6y/T5B96kIA==", "license": "MIT", "dependencies": { "@azure/abort-controller": "^2.1.2", @@ -725,11 +764,11 @@ "@azure/core-tracing": "^1.3.0", "@azure/core-util": "^1.13.0", "@azure/logger": "^1.3.0", - "@typespec/ts-http-runtime": "^0.3.0", + "@typespec/ts-http-runtime": "^0.3.4", "tslib": "^2.6.2" }, "engines": { - "node": ">=20.0.0" + "node": ">=22.0.0" } }, "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller": { @@ -809,9 +848,9 @@ } }, "node_modules/@azure/storage-blob": { - "version": "12.29.1", - "resolved": "https://registry.npmjs.org/@azure/storage-blob/-/storage-blob-12.29.1.tgz", - "integrity": "sha512-7ktyY0rfTM0vo7HvtK6E3UvYnI9qfd6Oz6z/+92VhGRveWng3kJwMKeUpqmW/NmwcDNbxHpSlldG+vsUnRFnBg==", + "version": "12.34.0", + "resolved": "https://registry.npmjs.org/@azure/storage-blob/-/storage-blob-12.34.0.tgz", + "integrity": "sha512-cXDTCAMwDx8Ng9yUe82kOOd2kPnZ8AQqe4FkLMcpaQ3Mvr3/PXVdvRhyP0FtY5/U5Oh6JGk3EcEibaFOymRLFw==", "license": "MIT", "dependencies": { "@azure/abort-controller": "^2.1.2", @@ -825,12 +864,13 @@ "@azure/core-util": "^1.11.0", "@azure/core-xml": "^1.4.5", "@azure/logger": "^1.1.4", - "@azure/storage-common": "^12.1.1", + "@azure/storage-common": "^12.5.0", + "apache-arrow": "^21.1.0", "events": "^3.0.0", "tslib": "^2.8.1" }, "engines": { - "node": ">=20.0.0" + "node": ">=22.0.0" } }, "node_modules/@azure/storage-blob/node_modules/@azure/abort-controller": { @@ -846,15 +886,15 @@ } }, "node_modules/@azure/storage-common": { - "version": "12.1.1", - "resolved": "https://registry.npmjs.org/@azure/storage-common/-/storage-common-12.1.1.tgz", - "integrity": "sha512-eIOH1pqFwI6UmVNnDQvmFeSg0XppuzDLFeUNO/Xht7ODAzRLgGDh7h550pSxoA+lPDxBl1+D2m/KG3jWzCUjTg==", + "version": "12.5.0", + "resolved": "https://registry.npmjs.org/@azure/storage-common/-/storage-common-12.5.0.tgz", + "integrity": "sha512-bttzuhQiCIwrkzjPDA+AtAR7dg19L/CC6ztcqJ5LfvWpXuys9mHp0UQ0udYnoUvv9SCT9KTR5kqFvFr0e6k0lQ==", "license": "MIT", "dependencies": { "@azure/abort-controller": "^2.1.2", "@azure/core-auth": "^1.9.0", - "@azure/core-http-compat": "^2.2.0", - "@azure/core-rest-pipeline": "^1.19.1", + "@azure/core-http-compat": "^2.4.0", + "@azure/core-rest-pipeline": "^1.24.0", "@azure/core-tracing": "^1.2.0", "@azure/core-util": "^1.11.0", "@azure/logger": "^1.1.4", @@ -862,19 +902,19 @@ "tslib": "^2.8.1" }, "engines": { - "node": ">=20.0.0" + "node": ">=22.0.0" } }, "node_modules/@azure/storage-common/node_modules/@azure/abort-controller": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz", - "integrity": "sha512-nBrLsEWm4J2u5LpAPjxADTlq3trDgVZZXHNKabeXZtpq3d3AbN/KGO82R87rdDz5/lYB024rtEf10/q0urNgsA==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.2.0.tgz", + "integrity": "sha512-fNAjWnA/nZ2jz31kxR/AqRaUT8ewHBw/WuBIosK0moMy1C9e5ValbDfFdIxJzVOOYaYkV/b2F1S4H/aHiqfVQg==", "license": "MIT", "dependencies": { "tslib": "^2.6.2" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "node_modules/@emnapi/core": { @@ -911,34 +951,92 @@ "tslib": "^2.4.0" } }, - "node_modules/@es-joy/jsdoccomment": { - "version": "0.86.0", - "resolved": "https://registry.npmjs.org/@es-joy/jsdoccomment/-/jsdoccomment-0.86.0.tgz", - "integrity": "sha512-ukZmRQ81WiTpDWO6D/cTBM7XbrNtutHKvAVnZN/8pldAwLoJArGOvkNyxPTBGsPjsoaQBJxlH+tE2TNA/92Qgw==", + "node_modules/@es-joy/escodegen": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@es-joy/escodegen/-/escodegen-4.2.0.tgz", + "integrity": "sha512-jWqqS3StW6vGwJeT8yu6alS4nipOBi3kD/pR63+9hG2NfGafCJ4viDME15mVf+fyupyptcUJDXfv63gFF5Gzfg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@es-joy/estraverse": "^7.1.1", + "@es-joy/jsdoccomment": "^0.62.0", + "esprima": "^4.0.1", + "esutils": "^2.0.3", + "optionator": "^0.9.4" + }, + "bin": { + "escodegen": "bin/escodegen.js", + "esgenerate": "bin/esgenerate.js" + }, + "engines": { + "node": ">=6.0" + }, + "optionalDependencies": { + "source-map": "~0.7.6" + } + }, + "node_modules/@es-joy/escodegen/node_modules/@es-joy/jsdoccomment": { + "version": "0.62.0", + "resolved": "https://registry.npmjs.org/@es-joy/jsdoccomment/-/jsdoccomment-0.62.0.tgz", + "integrity": "sha512-yWi6sm7INEwnfS7IJvE0dU+RTrwzLPFcY7e7eGpu/l5Q9lWfQ2ROwZ0qVnc242jw2TUPsfHX3XMIISkGBv57RQ==", "dev": true, "license": "MIT", "dependencies": { "@types/estree": "^1.0.8", - "@typescript-eslint/types": "^8.58.0", - "comment-parser": "1.4.6", - "esquery": "^1.7.0", - "jsdoc-type-pratt-parser": "~7.2.0" + "@typescript-eslint/types": "^8.44.1", + "comment-parser": "1.4.1", + "esquery": "^1.6.0", + "jsdoc-type-pratt-parser": "~5.9.0" }, "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": ">=20.11.0" } }, - "node_modules/@es-joy/jsdoccomment/node_modules/esquery": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", - "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "node_modules/@es-joy/escodegen/node_modules/comment-parser": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/comment-parser/-/comment-parser-1.4.1.tgz", + "integrity": "sha512-buhp5kePrmda3vhc5B9t7pUQXAb2Tnd0qgpkIhPhkHXxJpiPJ11H0ZEU0oBpJ2QztSbzG/ZxMj/CHsYJqRHmyg==", "dev": true, - "license": "BSD-3-Clause", + "license": "MIT", + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/@es-joy/escodegen/node_modules/jsdoc-type-pratt-parser": { + "version": "5.9.2", + "resolved": "https://registry.npmjs.org/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-5.9.2.tgz", + "integrity": "sha512-TYzkACp/wPvDJLRY7qpHXtrhgwoAaojIOnLaaVNi+AbPU2u1kkjfKd9hXXTq0qSAGsyYXvwUXt99h9I5iCmjjw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@es-joy/estraverse": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/@es-joy/estraverse/-/estraverse-7.1.1.tgz", + "integrity": "sha512-h2d737iS0LFAqypZOmXizu54qAbHofI/RpD30Zom03O6BCXKHuFevWKPcGarZbGq82h7qSBb5G6kLdhTMO+caw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/@es-joy/jsdoccomment": { + "version": "0.100.0", + "resolved": "https://registry.npmjs.org/@es-joy/jsdoccomment/-/jsdoccomment-0.100.0.tgz", + "integrity": "sha512-QuIT5kMg3XWN22Wa1rcXmR/GkfSg6Ygs/ikMiHihdSpu+o3O59LygkFV9srKa5xHplBFwNd5ZCo3bywL4k7qMQ==", + "dev": true, + "license": "MIT", "dependencies": { - "estraverse": "^5.1.0" + "@types/estree": "^1.0.9", + "@typescript-eslint/types": "^8.72.0", + "comment-parser": "1.4.9", + "esquery": "^1.7.0", + "jsdoc-type-pratt-parser": "~9.3.0" }, "engines": { - "node": ">=0.10" + "node": "^22.22.2 || >=24.15.0" } }, "node_modules/@es-joy/resolve.exports": { @@ -1423,9 +1521,9 @@ } }, "node_modules/@eslint/compat": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@eslint/compat/-/compat-2.1.0.tgz", - "integrity": "sha512-LgaSCymEpw7tF53xvDw9SNsraPb1IBHxpdABIOM0hW8UAlP8znrjYtuxfR58FSJ3L9BhwD+FaPRFQpZq84Nh6g==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@eslint/compat/-/compat-2.1.1.tgz", + "integrity": "sha512-rMcy8GSrwNzcISX/BlTDY/GLB4eCopEuy9woIls3To+15OLxykZrxxq+WUcylCPCQ6F4MujjBM1DX5V1aqI3Vw==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -1535,9 +1633,9 @@ } }, "node_modules/@eslint/eslintrc/node_modules/js-yaml": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz", - "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "dev": true, "funding": [ { @@ -1613,29 +1711,43 @@ "license": "MIT" }, "node_modules/@humanfs/core": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", - "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", "dev": true, "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, "engines": { "node": ">=18.18.0" } }, "node_modules/@humanfs/node": { - "version": "0.16.7", - "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz", - "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==", + "version": "0.16.8", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@humanfs/core": "^0.19.1", + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", "@humanwhocodes/retry": "^0.4.0" }, "engines": { "node": ">=18.18.0" } }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, "node_modules/@humanwhocodes/config-array": { "version": "0.13.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", @@ -1699,6 +1811,12 @@ "node": ">=18.0.0" } }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.0.2.tgz", + "integrity": "sha512-GJPHIgPPtFl+nLhFHyF0zZoFcOFLsZWbHFFzo+Zr+PWDXJbl9hHxb2w+9SiF2fHmLgKaXIpUzQo3SbBBZ9WObw==", + "license": "BlueOak-1.0.0" + }, "node_modules/@mapbox/node-pre-gyp": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-2.0.3.tgz", @@ -1980,9 +2098,9 @@ } }, "node_modules/@microsoft/eslint-formatter-sarif/node_modules/js-yaml": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz", - "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "dev": true, "funding": [ { @@ -2087,16 +2205,16 @@ } }, "node_modules/@octokit/core": { - "version": "7.0.7", - "resolved": "https://registry.npmjs.org/@octokit/core/-/core-7.0.7.tgz", - "integrity": "sha512-DcB0M3KFgr9ECI328lhBMVsyFT2DnmNucSBTqEN3exyNKUzkkpUSCHmTRcunF41Eou2TIQKW4seewri8ON9bSA==", + "version": "7.0.8", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-7.0.8.tgz", + "integrity": "sha512-L7y8eYc+AwxGr2PWI4WFt1VG4TiJ66c26BD16mXpYIlXxG0SMigM1+m4aTSlYyBr5BlQsGAlz8uDCoZN4SEMcg==", "license": "MIT", "dependencies": { "@octokit/auth-token": "^6.0.0", - "@octokit/graphql": "^9.0.4", - "@octokit/request": "^10.0.13", - "@octokit/request-error": "^7.1.1", - "@octokit/types": "^17.0.0", + "@octokit/graphql": "^9.0.5", + "@octokit/request": "^10.0.16", + "@octokit/request-error": "^7.1.2", + "@octokit/types": "^18.0.0", "before-after-hook": "^4.0.0", "universal-user-agent": "^7.0.0" }, @@ -2104,21 +2222,6 @@ "node": ">= 20" } }, - "node_modules/@octokit/core/node_modules/@octokit/openapi-types": { - "version": "28.0.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-28.0.0.tgz", - "integrity": "sha512-0rFyLuyHvIj6uuZWuDslxkowFYdPXoNIkeAv4b27dzm2Tf4vGWXnPsMcxs7d65kLdMERgP3wc1AEPlqMz8e1cQ==", - "license": "MIT" - }, - "node_modules/@octokit/core/node_modules/@octokit/types": { - "version": "17.0.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-17.0.0.tgz", - "integrity": "sha512-ByP1v7YL5SMveFPP7+sj0/ZuWCOOg/Chs4NafOMpq6WNIM/hdGY0S7C0TCGDBWu1aGmOxmUIhMx3cO+IdwYZ1Q==", - "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^28.0.0" - } - }, "node_modules/@octokit/core/node_modules/universal-user-agent": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-7.0.3.tgz", @@ -2126,33 +2229,18 @@ "license": "ISC" }, "node_modules/@octokit/endpoint": { - "version": "11.0.4", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-11.0.4.tgz", - "integrity": "sha512-f1cOWoHPmxryJFknxbtDdjODWfV8A9tc8Aae6ermXPNgHFZ/x91AtHIz4gicEjL8hkJiip+u21QHJORfBv/qiA==", + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-11.0.5.tgz", + "integrity": "sha512-iXa654H3yFafF/ieHkukfbgWo2rmXD2ceD0ZOtrPhw1bc3FDch1d9N/TNs0FQ1/cIbwb7kspUX8jzIs8nzb9DQ==", "license": "MIT", "dependencies": { - "@octokit/types": "^17.0.0", + "@octokit/types": "^18.0.0", "universal-user-agent": "^7.0.2" }, "engines": { "node": ">= 20" } }, - "node_modules/@octokit/endpoint/node_modules/@octokit/openapi-types": { - "version": "28.0.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-28.0.0.tgz", - "integrity": "sha512-0rFyLuyHvIj6uuZWuDslxkowFYdPXoNIkeAv4b27dzm2Tf4vGWXnPsMcxs7d65kLdMERgP3wc1AEPlqMz8e1cQ==", - "license": "MIT" - }, - "node_modules/@octokit/endpoint/node_modules/@octokit/types": { - "version": "17.0.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-17.0.0.tgz", - "integrity": "sha512-ByP1v7YL5SMveFPP7+sj0/ZuWCOOg/Chs4NafOMpq6WNIM/hdGY0S7C0TCGDBWu1aGmOxmUIhMx3cO+IdwYZ1Q==", - "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^28.0.0" - } - }, "node_modules/@octokit/endpoint/node_modules/universal-user-agent": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-7.0.3.tgz", @@ -2160,34 +2248,19 @@ "license": "ISC" }, "node_modules/@octokit/graphql": { - "version": "9.0.4", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-9.0.4.tgz", - "integrity": "sha512-5s15CCiY8XXQ+FG+b1YQcl6Z2FA++nwAz/tg2VUrTmnMncP+2nnGUEYANImdnxsA2Fnq+Mbl7hDjUTw7cFAwcg==", + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-9.0.5.tgz", + "integrity": "sha512-bt/hm03LeU6Vy7FwTrkkC9p3XGT/lBwClglMqxBSe5/q0E5CdJTXeAqEI0vlw89/LF/G6tryTIH8HirZ3prMVg==", "license": "MIT", "dependencies": { - "@octokit/request": "^10.0.13", - "@octokit/types": "^17.0.0", + "@octokit/request": "^10.0.16", + "@octokit/types": "^18.0.0", "universal-user-agent": "^7.0.0" }, "engines": { "node": ">= 20" } }, - "node_modules/@octokit/graphql/node_modules/@octokit/openapi-types": { - "version": "28.0.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-28.0.0.tgz", - "integrity": "sha512-0rFyLuyHvIj6uuZWuDslxkowFYdPXoNIkeAv4b27dzm2Tf4vGWXnPsMcxs7d65kLdMERgP3wc1AEPlqMz8e1cQ==", - "license": "MIT" - }, - "node_modules/@octokit/graphql/node_modules/@octokit/types": { - "version": "17.0.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-17.0.0.tgz", - "integrity": "sha512-ByP1v7YL5SMveFPP7+sj0/ZuWCOOg/Chs4NafOMpq6WNIM/hdGY0S7C0TCGDBWu1aGmOxmUIhMx3cO+IdwYZ1Q==", - "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^28.0.0" - } - }, "node_modules/@octokit/graphql/node_modules/universal-user-agent": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-7.0.3.tgz", @@ -2195,18 +2268,18 @@ "license": "ISC" }, "node_modules/@octokit/openapi-types": { - "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==", + "version": "29.0.1", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-29.0.1.tgz", + "integrity": "sha512-9qWOMFNxxLokERcms42rU0PTLqQmVs7g5E41TI4mCOxmpFayD1rfC7XxOL55cG9MBZLFlC31BrR37myMKardwg==", "license": "MIT" }, "node_modules/@octokit/plugin-paginate-rest": { - "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==", + "version": "16.0.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-16.0.0.tgz", + "integrity": "sha512-7RtUeGZypAK4EA4LrjTCnsLALNOoUcYh5vOnCNXpdIQVTQCPh4OFu7324iPqAls3KGgVnZktKUnNKZCOKyHrlA==", "license": "MIT", "dependencies": { - "@octokit/types": "^16.0.0" + "@octokit/types": "^18.0.0" }, "engines": { "node": ">= 20" @@ -2225,12 +2298,12 @@ } }, "node_modules/@octokit/plugin-rest-endpoint-methods": { - "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==", + "version": "18.0.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-18.0.0.tgz", + "integrity": "sha512-1wM02pQTHEarWYij0Bb4gu8X8fBy2FJdI4HMTSFDxtYLbOkJErGVx5ywmM6jeS8tOmC0iCiRLrn6YsSIecUeOQ==", "license": "MIT", "dependencies": { - "@octokit/types": "^16.0.0" + "@octokit/types": "^17.0.0" }, "engines": { "node": ">= 20" @@ -2239,6 +2312,21 @@ "@octokit/core": ">=6" } }, + "node_modules/@octokit/plugin-rest-endpoint-methods/node_modules/@octokit/openapi-types": { + "version": "28.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-28.0.0.tgz", + "integrity": "sha512-0rFyLuyHvIj6uuZWuDslxkowFYdPXoNIkeAv4b27dzm2Tf4vGWXnPsMcxs7d65kLdMERgP3wc1AEPlqMz8e1cQ==", + "license": "MIT" + }, + "node_modules/@octokit/plugin-rest-endpoint-methods/node_modules/@octokit/types": { + "version": "17.0.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-17.0.0.tgz", + "integrity": "sha512-ByP1v7YL5SMveFPP7+sj0/ZuWCOOg/Chs4NafOMpq6WNIM/hdGY0S7C0TCGDBWu1aGmOxmUIhMx3cO+IdwYZ1Q==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^28.0.0" + } + }, "node_modules/@octokit/plugin-retry": { "version": "8.1.1", "resolved": "https://registry.npmjs.org/@octokit/plugin-retry/-/plugin-retry-8.1.1.tgz", @@ -2272,16 +2360,16 @@ } }, "node_modules/@octokit/request": { - "version": "10.0.13", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-10.0.13.tgz", - "integrity": "sha512-v2269YxL9Yf+x3d+gRI63FP0vFQEiWgLyBzxe/Y+0yFDg2B/Tzf5dhh9VNfccVAQnfcfwQWyk/y6Bn7rUXXs7A==", + "version": "10.0.16", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-10.0.16.tgz", + "integrity": "sha512-A0zWGjHzISIb+9ccG8s0dq7LKO5zVpJLRICjgUb+sJxEWqn8RUHB1rD3AE51+PECvXHIxqZ1VVvs4fHTSD9nUQ==", "license": "MIT", "dependencies": { - "@octokit/endpoint": "^11.0.3", - "@octokit/request-error": "^7.1.1", - "@octokit/types": "^17.0.0", - "content-type": "^2.0.0", - "json-with-bigint": "^3.5.3", + "@octokit/endpoint": "^11.0.5", + "@octokit/request-error": "^7.1.2", + "@octokit/types": "^18.0.0", + "content-type": "^3.0.0", + "json-with-bigint": "^3.5.12", "universal-user-agent": "^7.0.2" }, "engines": { @@ -2289,47 +2377,17 @@ } }, "node_modules/@octokit/request-error": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-7.1.1.tgz", - "integrity": "sha512-+eaY7G2VVpSf2pc5Gn1+mph837V/d/TYTJAgWL9Tb0ogGYcpN3IlAVFgjL+Vv93F/sevrxkvsYCedtpLdcFLzA==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-7.1.2.tgz", + "integrity": "sha512-XZRuT3xZ84D3gYErI1DZvhJ33dCWVV6uzBtWkaBB4TvA/L6eOeTZodxLFVB44bBEEo3vEx7y00UfX1tBLrtLRg==", "license": "MIT", "dependencies": { - "@octokit/types": "^17.0.0" + "@octokit/types": "^18.0.0" }, "engines": { "node": ">= 20" } }, - "node_modules/@octokit/request-error/node_modules/@octokit/openapi-types": { - "version": "28.0.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-28.0.0.tgz", - "integrity": "sha512-0rFyLuyHvIj6uuZWuDslxkowFYdPXoNIkeAv4b27dzm2Tf4vGWXnPsMcxs7d65kLdMERgP3wc1AEPlqMz8e1cQ==", - "license": "MIT" - }, - "node_modules/@octokit/request-error/node_modules/@octokit/types": { - "version": "17.0.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-17.0.0.tgz", - "integrity": "sha512-ByP1v7YL5SMveFPP7+sj0/ZuWCOOg/Chs4NafOMpq6WNIM/hdGY0S7C0TCGDBWu1aGmOxmUIhMx3cO+IdwYZ1Q==", - "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^28.0.0" - } - }, - "node_modules/@octokit/request/node_modules/@octokit/openapi-types": { - "version": "28.0.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-28.0.0.tgz", - "integrity": "sha512-0rFyLuyHvIj6uuZWuDslxkowFYdPXoNIkeAv4b27dzm2Tf4vGWXnPsMcxs7d65kLdMERgP3wc1AEPlqMz8e1cQ==", - "license": "MIT" - }, - "node_modules/@octokit/request/node_modules/@octokit/types": { - "version": "17.0.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-17.0.0.tgz", - "integrity": "sha512-ByP1v7YL5SMveFPP7+sj0/ZuWCOOg/Chs4NafOMpq6WNIM/hdGY0S7C0TCGDBWu1aGmOxmUIhMx3cO+IdwYZ1Q==", - "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^28.0.0" - } - }, "node_modules/@octokit/request/node_modules/universal-user-agent": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-7.0.3.tgz", @@ -2337,12 +2395,12 @@ "license": "ISC" }, "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==", + "version": "18.0.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-18.0.0.tgz", + "integrity": "sha512-l6bAF43PNxkJp6g+W4PjoUSSkxHomXw2nOum5CTftJz1NlV3vu93NImgOYtLf6CbBUb5j+fiuzW0PPQ5JTSvZA==", "license": "MIT", "dependencies": { - "@octokit/openapi-types": "^27.0.0" + "@octokit/openapi-types": "^29.0.1" } }, "node_modules/@open-draft/deferred-promise": { @@ -2590,11 +2648,21 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/debug": { + "version": "4.1.13", + "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz", + "integrity": "sha1-ItHMnVQtNZPK6nZPl0MGqzYobuc=", + "license": "MIT", + "dependencies": { + "@types/ms": "*" + } + }, "node_modules/@types/estree": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", - "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", - "dev": true + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" }, "node_modules/@types/follow-redirects": { "version": "1.14.4", @@ -2623,6 +2691,21 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/mdast": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "integrity": "sha1-fM9y7dLxqn3TQ34YDGQ3NYWATdY=", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", + "integrity": "sha1-BSqmekjszEMJ1/AZG35BQ0uQu3g=", + "license": "MIT" + }, "node_modules/@types/node": { "version": "20.19.43", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", @@ -2668,32 +2751,33 @@ "license": "MIT" }, "node_modules/@types/sinon": { - "version": "22.0.0", - "resolved": "https://registry.npmjs.org/@types/sinon/-/sinon-22.0.0.tgz", - "integrity": "sha512-TDbVpbccc2HfiqHR09Argj3mHV1KMW7sCCKj52fsl8lbRLkEn7fB1966EWhOKWUBcqfBueZuPoA7/OK1CKiy3g==", + "version": "22.0.1", + "resolved": "https://registry.npmjs.org/@types/sinon/-/sinon-22.0.1.tgz", + "integrity": "sha512-MThluJXPmpBY+Z5S3565F2z+hjkCXnBrr36j2mitVQ7JUtxA+A+YQhs+0Q6J8jxb0SVJvydO+6NWfj9EBzpiBQ==", "dev": true, "license": "MIT", "dependencies": { - "@types/sinonjs__fake-timers": "*" + "@sinonjs/fake-timers": "^15.4.0" } }, - "node_modules/@types/sinonjs__fake-timers": { - "version": "8.1.2", - "dev": true, + "node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha1-rKqw+RnOaczmKcLU7S60rcG2wgw=", "license": "MIT" }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.67.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.67.0.tgz", - "integrity": "sha512-Un7Heoyj65NREbKAyIrFxeM143NZpExWmy1Nep4DLeQOeLlTeumPjoNKnBrU5D5moWXbPJgRa5Uwcdu0faVNGQ==", + "version": "8.72.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.0.tgz", + "integrity": "sha512-aysKgysPX9XOv/dk95UkvUDe++Q3n3dJPG9CEWT3RUccxfkPJ+Qn6nhKPDhZXU6Ofo9kgwGWwKyQCnZIXTgngg==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.67.0", - "@typescript-eslint/type-utils": "8.67.0", - "@typescript-eslint/utils": "8.67.0", - "@typescript-eslint/visitor-keys": "8.67.0", + "@typescript-eslint/scope-manager": "8.72.0", + "@typescript-eslint/type-utils": "8.72.0", + "@typescript-eslint/utils": "8.72.0", + "@typescript-eslint/visitor-keys": "8.72.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" @@ -2706,7 +2790,7 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^8.67.0", + "@typescript-eslint/parser": "^8.72.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } @@ -2722,16 +2806,16 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "8.67.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.67.0.tgz", - "integrity": "sha512-fUBfTuuEulWqX6V8+O3PtScV01tzYYRUDTAirHFKoRAt7nOzoGiPt0M/bB47wWNy0coOOcgEwAMUtBpykMxl6w==", + "version": "8.72.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.0.tgz", + "integrity": "sha512-0O+x3ynciD6zuXb1CKSu165haQV6ey53DKhHHUnujP7U+XlltJG+/keT0Xhd1HXCze+IHf7Tvt39ovyepX/LNw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "8.67.0", - "@typescript-eslint/types": "8.67.0", - "@typescript-eslint/typescript-estree": "8.67.0", - "@typescript-eslint/visitor-keys": "8.67.0", + "@typescript-eslint/scope-manager": "8.72.0", + "@typescript-eslint/types": "8.72.0", + "@typescript-eslint/typescript-estree": "8.72.0", + "@typescript-eslint/visitor-keys": "8.72.0", "debug": "^4.4.3" }, "engines": { @@ -2765,14 +2849,14 @@ } }, "node_modules/@typescript-eslint/project-service": { - "version": "8.67.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.67.0.tgz", - "integrity": "sha512-cvE8c7ulYeXN9fYuszhCeCsbzyVEXuhrRCybnBre7TUmqb5nRmBfQAwCj0O3WJFDeyAZt4VYv51vMCC9LHSdYw==", + "version": "8.72.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.0.tgz", + "integrity": "sha512-bzHngBbmIgzj6TsTjVUCntGx6FFLgE7mPjpO0PzHycOaZHXqS43XnrkFIHRS16LLr/xO6FHSXG3GJFo/F4bSBQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.67.0", - "@typescript-eslint/types": "^8.67.0", + "@typescript-eslint/tsconfig-utils": "^8.72.0", + "@typescript-eslint/types": "^8.72.0", "debug": "^4.4.3" }, "engines": { @@ -2805,14 +2889,14 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.67.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.67.0.tgz", - "integrity": "sha512-EgvsleTwS4E+WzzSvem8fAUubLwatMNF1B5hHSLQxcvs7q2dtRhGyujHwLJSYlG41niJ7GP24Aha2+0mb1b2kg==", + "version": "8.72.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.0.tgz", + "integrity": "sha512-JewPyJOYcXBSAS7PIgufscHOwZqhTGyBRiQJhhuDln66tMchxvvt7nJ90JKKIoOelmdHA3kAQbm9cEUHc4JSEA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.67.0", - "@typescript-eslint/visitor-keys": "8.67.0" + "@typescript-eslint/types": "8.72.0", + "@typescript-eslint/visitor-keys": "8.72.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -2823,9 +2907,9 @@ } }, "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.67.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.67.0.tgz", - "integrity": "sha512-vV+LUSv5njUWsknE71fqKTlXUva+R76SaeORd6Zojcunk/6DvKFXONU3BrAs2H49mbygUXt6gbYunzwqNwlhdg==", + "version": "8.72.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.0.tgz", + "integrity": "sha512-0vbxCf7xLVPSjcOdm6eQbgViH8EDJ8xnl1laLT9yoqSz2YmcSfSg5Vdl0JUvZf6rcuJ0ZivJIuMD4edTg8obaA==", "dev": true, "license": "MIT", "engines": { @@ -2840,15 +2924,15 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.67.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.67.0.tgz", - "integrity": "sha512-aVWDXbRmdXO9siTfX4ditQI1T9+zVcNazT48EJCD0v40/9RIFoUgZ05CmGEq9H2gixRpjUn/iplwvlcvutJW/Q==", + "version": "8.72.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.0.tgz", + "integrity": "sha512-gEXxmmbSTSOVTC37IYYvremOM31v+UN2W772bJxmVYPhAOPSUxtacyb7wkm1EhkYKU6KzFJsdU44DCV4to0LWw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.67.0", - "@typescript-eslint/typescript-estree": "8.67.0", - "@typescript-eslint/utils": "8.67.0", + "@typescript-eslint/types": "8.72.0", + "@typescript-eslint/typescript-estree": "8.72.0", + "@typescript-eslint/utils": "8.72.0", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, @@ -2883,9 +2967,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.67.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.67.0.tgz", - "integrity": "sha512-sBtgslww8nsMYUjhdPBiSyUqSzT8uR6g93A2QXnQC8+cGdjz0CyaOdqHDRJb1AtORbZCNUJBBeFA/tNR2uQmww==", + "version": "8.72.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.0.tgz", + "integrity": "sha512-Adfoy59kxNEjT5E5fnyrp7GpHYuWs8ONbdohu4ez6IU46qDq8LltG90tLmkucZB2uhYL8mqBjtXqGd8yhfjXqQ==", "dev": true, "license": "MIT", "engines": { @@ -2897,16 +2981,16 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.67.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.67.0.tgz", - "integrity": "sha512-EKQBCE9yNlRJYm7jdTW5AhDacDUmSwQb0FAJAmK2EKYrNXIsa2vxcSZx6PvJ/dEdI6lS+Y9W+EXckLj0iPFGcw==", + "version": "8.72.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.0.tgz", + "integrity": "sha512-gwLfFgWcw15tN2KXDCJvxEOQjPn+P3j/n3eSqkZ5sX4VpW9Cosodr+tWwBZRvJT3TcKx6HnPRGZMCNAiP1Xhug==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/project-service": "8.67.0", - "@typescript-eslint/tsconfig-utils": "8.67.0", - "@typescript-eslint/types": "8.67.0", - "@typescript-eslint/visitor-keys": "8.67.0", + "@typescript-eslint/project-service": "8.72.0", + "@typescript-eslint/tsconfig-utils": "8.72.0", + "@typescript-eslint/types": "8.72.0", + "@typescript-eslint/visitor-keys": "8.72.0", "debug": "^4.4.3", "minimatch": "^10.2.2", "semver": "^7.7.3", @@ -2935,9 +3019,9 @@ } }, "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { - "version": "5.0.9", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", - "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "dev": true, "license": "MIT", "dependencies": { @@ -2982,16 +3066,16 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "8.67.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.67.0.tgz", - "integrity": "sha512-U9D1FdwEWBwok3hxxSdhclMb0twvt9QnjIQ0VfQ1AiX2epnpSgv2ubVDsayOFyY8K6FX+AQ7E0FKWVG3iKsj1A==", + "version": "8.72.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.0.tgz", + "integrity": "sha512-0up3oArJZBYnzOaEXKo8DmI43QvMZyPoFEt9LWzRJcyl/RcJjfKKPebknN1VbTgXBf3M/KggUh5uUMdURLnseg==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.67.0", - "@typescript-eslint/types": "8.67.0", - "@typescript-eslint/typescript-estree": "8.67.0" + "@typescript-eslint/scope-manager": "8.72.0", + "@typescript-eslint/types": "8.72.0", + "@typescript-eslint/typescript-estree": "8.72.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -3006,13 +3090,13 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.67.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.67.0.tgz", - "integrity": "sha512-fkv8dHRDqfGtTHuJeebdrQ7cX6Ad4WAS00rgHh9UGvMycF1mjBfsxry1XsLIFhWZ6Judlh6UdzK+TYlbpCXgnA==", + "version": "8.72.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.0.tgz", + "integrity": "sha512-E2mroviasaWecDzTGiGMtuEguuLVOeRggnrIn93CJuxYJzQBHbyymlT08aVQydbBal5538o+JkBKXh2sRuCyIA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.67.0", + "@typescript-eslint/types": "8.72.0", "eslint-visitor-keys": "^5.0.0" }, "engines": { @@ -3037,9 +3121,9 @@ } }, "node_modules/@typespec/ts-http-runtime": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/@typespec/ts-http-runtime/-/ts-http-runtime-0.3.2.tgz", - "integrity": "sha512-IlqQ/Gv22xUC1r/WQm4StLkYQmaaTsXAhUVsNE0+xiyf0yRFiH5++q78U3bw6bLKDCTmh0uqKB9eG9+Bt75Dkg==", + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@typespec/ts-http-runtime/-/ts-http-runtime-0.3.9.tgz", + "integrity": "sha512-edSdeAqkdxBVzA1yL1LrLCml1YjyCVvPMtMqJpbF+6K609tHe8V6sQUzFQSGcYNhcuhOceZtjvN32+mpIth30A==", "license": "MIT", "dependencies": { "http-proxy-agent": "^7.0.0", @@ -3047,7 +3131,7 @@ "tslib": "^2.6.2" }, "engines": { - "node": ">=20.0.0" + "node": ">=22.0.0" } }, "node_modules/@ungap/structured-clone": { @@ -3446,7 +3530,6 @@ }, "node_modules/ansi-regex": { "version": "5.0.1", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -3456,7 +3539,6 @@ "version": "6.2.3", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", - "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -3465,6 +3547,36 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/apache-arrow": { + "version": "21.2.0", + "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-21.2.0.tgz", + "integrity": "sha512-Hxe6Agq26gQOM954qpzYSllJBPJl+e16U5CkfuMUhLrNba+5nKkttIVlflaovN6oaTratqMGAO8H5u/aNhmHWQ==", + "license": "Apache-2.0", + "dependencies": { + "@types/node": "^25.2.0", + "flatbuffers": "^25.1.24", + "json-with-bigint": "^3.5.3", + "tslib": "^2.6.2" + }, + "bin": { + "arrow2csv": "bin/arrow2csv.js" + } + }, + "node_modules/apache-arrow/node_modules/@types/node": { + "version": "25.9.8", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.8.tgz", + "integrity": "sha512-VfMrScDmMhUJQmd5hArdQnFvK0OIeD36uN2Va1FcpYaLB/BgkgM8Ulc50XtYISPMz7APJ30+N0T5EM0jlcdfRw==", + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/apache-arrow/node_modules/undici-types": { + "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==", + "license": "MIT" + }, "node_modules/archiver": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/archiver/-/archiver-8.0.0.tgz", @@ -3516,17 +3628,18 @@ } }, "node_modules/are-docs-informative": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/are-docs-informative/-/are-docs-informative-0.0.2.tgz", - "integrity": "sha512-ixiS0nLNNG5jNQzgZJNoUpBKdo9yTYZMGJ+QgT2jmjR7G7+QHRCc4v6LQ3NgE7EBJq+o0ams3waJwkrlBom8Ig==", + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/are-docs-informative/-/are-docs-informative-0.1.1.tgz", + "integrity": "sha512-sqRsNQBwbKLRX0jV5Cu5uzmtflf892n4Vukz7T659ebL4pz3mpOqCMU7lxMoBTFwnp10E3YB5ZcyHM41W5bcDA==", "dev": true, "license": "MIT", "engines": { - "node": ">=14" + "node": ">=18" } }, "node_modules/argparse": { "version": "2.0.1", + "dev": true, "license": "Python-2.0" }, "node_modules/aria-query": { @@ -3916,6 +4029,19 @@ ], "license": "MIT" }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.20", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.20.tgz", + "integrity": "sha512-H0ulySigv6icDJ1F7SjtdCD6PrhTpdYCmP0CactWy1+ekh0AFd0o1Wn5T8b+hnTmdBx19u9yhL6wvCylXMY7zw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/before-after-hook": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-4.0.0.tgz", @@ -3956,9 +4082,9 @@ "license": "MIT" }, "node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "license": "MIT", "dependencies": { "balanced-match": "^1.0.0", @@ -3979,9 +4105,9 @@ } }, "node_modules/browserslist": { - "version": "4.24.2", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.2.tgz", - "integrity": "sha512-ZIc+Q62revdMcqC6aChtW4jz3My3klmCO1fEmINZY/8J3EpBg5/A/D0AKmBveUh6pgoeycoMkVMko84tuYS+Gg==", + "version": "4.28.8", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.8.tgz", + "integrity": "sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA==", "dev": true, "funding": [ { @@ -3999,10 +4125,11 @@ ], "license": "MIT", "dependencies": { - "caniuse-lite": "^1.0.30001669", - "electron-to-chromium": "^1.5.41", - "node-releases": "^2.0.18", - "update-browserslist-db": "^1.1.1" + "baseline-browser-mapping": "^2.11.12", + "caniuse-lite": "^1.0.30001809", + "electron-to-chromium": "^1.5.402", + "node-releases": "^2.0.53", + "update-browserslist-db": "^1.3.0" }, "bin": { "browserslist": "cli.js" @@ -4110,9 +4237,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001766", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001766.tgz", - "integrity": "sha512-4C0lfJ0/YPjJQHagaE9x2Elb69CIqEPZeG0anQt9SIvIoOH4a4uaRl73IavyO+0qZh6MDLH//DrXThEYKHkmYA==", + "version": "1.0.30001810", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001810.tgz", + "integrity": "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==", "dev": true, "funding": [ { @@ -4168,6 +4295,16 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/character-entities": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", + "integrity": "sha1-LQnC5yzZUjB2zLIRV9/2atQ/zCI=", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/chownr": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", @@ -4306,7 +4443,6 @@ }, "node_modules/color-convert": { "version": "2.0.1", - "dev": true, "license": "MIT", "dependencies": { "color-name": "~1.1.4" @@ -4317,13 +4453,12 @@ }, "node_modules/color-name": { "version": "1.1.4", - "dev": true, "license": "MIT" }, "node_modules/comment-parser": { - "version": "1.4.6", - "resolved": "https://registry.npmjs.org/comment-parser/-/comment-parser-1.4.6.tgz", - "integrity": "sha512-ObxuY6vnbWTN6Od72xfwN9DbzC7Y2vv8u1Soi9ahRKL37gb6y1qk6/dgjs+3JWuXJHWvsg3BXIwzd/rkmAwavg==", + "version": "1.4.9", + "resolved": "https://registry.npmjs.org/comment-parser/-/comment-parser-1.4.9.tgz", + "integrity": "sha512-+2AvZKjJaNq9GQljm3tr0utwrig5BL+jgJGvz5rDpGKNIp+ojcRXWUwBbh/sGIi1QCprR6PsKFakub+w1v+4hQ==", "dev": true, "license": "MIT", "engines": { @@ -4386,12 +4521,12 @@ } }, "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==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-3.0.0.tgz", + "integrity": "sha512-AIi5H6p0xk5uknXcN3/rmhP8jgp69OfSe/JuKiQAFprJ7UGw7mwj7m4XcmDzlrnJDG+cGpphAINGdU3g3g7kDw==", "license": "MIT", "engines": { - "node": ">=18" + "node": ">=22" }, "funding": { "type": "opencollective", @@ -4442,7 +4577,6 @@ "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -4553,6 +4687,19 @@ } } }, + "node_modules/decode-named-character-reference": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", + "integrity": "sha1-PkBgN2CHTC5YZ2kbWZ1zp9oltT8=", + "license": "MIT", + "dependencies": { + "character-entities": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/deep-is": { "version": "0.1.4", "dev": true, @@ -4596,6 +4743,15 @@ "version": "2.3.1", "license": "ISC" }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha1-JkQhTxmX057Q7g7OcjNUkKesZ74=", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -4606,6 +4762,19 @@ "node": ">=8" } }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha1-TbfCyk3G4Og0wwvnDJS7yXbccBg=", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/diff": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/diff/-/diff-9.0.0.tgz", @@ -4642,9 +4811,9 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.5.68", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.68.tgz", - "integrity": "sha512-FgMdJlma0OzUYlbrtZ4AeXjKxKPk6KT8WOP8BjcqxWtlg8qyJQjRzPJzUtUn5GBg1oQ26hFs7HOOHJMYiJRnvQ==", + "version": "1.5.420", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.420.tgz", + "integrity": "sha512-2yD6XreGusOfNV+dUcvipJEXc3n/n7fgr7996aszTG+YY5E4mqM4tOq/3uhP129cazL9YHbVWSpc79ePotWtPA==", "dev": true, "license": "ISC" }, @@ -4662,7 +4831,6 @@ }, "node_modules/emoji-regex": { "version": "8.0.0", - "dev": true, "license": "MIT" }, "node_modules/es-abstract": { @@ -5220,9 +5388,9 @@ } }, "node_modules/eslint-plugin-import-x/node_modules/brace-expansion": { - "version": "5.0.9", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", - "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "dev": true, "license": "MIT", "dependencies": { @@ -5257,32 +5425,40 @@ } }, "node_modules/eslint-plugin-jsdoc": { - "version": "62.9.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-62.9.0.tgz", - "integrity": "sha512-PY7/X4jrVgoIDncUmITlUqK546Ltmx/Pd4Hdsu4CvSjryQZJI2mEV4vrdMufyTetMiZ5taNSqvK//BTgVUlNkA==", + "version": "65.4.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-65.4.0.tgz", + "integrity": "sha512-bRiU6LfCFmLL7GuePKvA6ZIcXLonhZGCg2TgQLmkcExeVdAirQp2Hsf3xeSUTmlKwAAsREVEOLbZYD8F7oA69g==", "dev": true, "license": "BSD-3-Clause", "dependencies": { - "@es-joy/jsdoccomment": "~0.86.0", + "@es-joy/escodegen": "^4.2.0", + "@es-joy/jsdoccomment": "~0.100.0", "@es-joy/resolve.exports": "1.2.0", - "are-docs-informative": "^0.0.2", - "comment-parser": "1.4.6", + "@typescript-eslint/utils": "^8.72.0", + "are-docs-informative": "^0.1.1", + "comment-parser": "1.4.9", "debug": "^4.4.3", - "escape-string-regexp": "^4.0.0", + "escape-string-regexp": "^5.0.0", "espree": "^11.2.0", "esquery": "^1.7.0", "html-entities": "^2.6.0", - "object-deep-merge": "^2.0.0", + "object-deep-merge": "^2.0.1", "parse-imports-exports": "^0.2.4", - "semver": "^7.7.4", - "spdx-expression-parse": "^4.0.0", + "semver": "^7.8.5", + "spdx-expression-parse": "^5.0.0", "to-valid-identifier": "^1.0.0" }, "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": "^22.22.2 || >=24.15.0" }, "peerDependencies": { - "eslint": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0" + "eslint": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0", + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } } }, "node_modules/eslint-plugin-jsdoc/node_modules/debug": { @@ -5304,13 +5480,13 @@ } }, "node_modules/eslint-plugin-jsdoc/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==", + "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": { - "node": ">=10" + "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -5347,19 +5523,6 @@ "url": "https://opencollective.com/eslint" } }, - "node_modules/eslint-plugin-jsdoc/node_modules/esquery": { - "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", - "dependencies": { - "estraverse": "^5.1.0" - }, - "engines": { - "node": ">=0.10" - } - }, "node_modules/eslint-plugin-jsx-a11y": { "version": "6.10.2", "resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.10.2.tgz", @@ -5606,7 +5769,9 @@ } }, "node_modules/esquery": { - "version": "1.5.0", + "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", "dependencies": { @@ -5697,6 +5862,7 @@ }, "node_modules/fast-deep-equal": { "version": "3.1.3", + "dev": true, "license": "MIT" }, "node_modules/fast-diff": { @@ -5873,6 +6039,12 @@ "node": ">=16" } }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "license": "Apache-2.0" + }, "node_modules/flatted": { "version": "3.4.2", "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", @@ -5881,9 +6053,9 @@ "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", - "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.1.tgz", + "integrity": "sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==", "funding": [ { "type": "individual", @@ -6101,14 +6273,14 @@ } }, "node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "version": "14.0.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.3.tgz", + "integrity": "sha512-A1vjIwC3qpdCso45Iw127gnp7sPhqgY8lUQhDrArIs+GbmfaaVPFuoyy7WyLT9EPZCRZ7j7aLdwUhQmHWesEow==", "license": "BlueOak-1.0.0", "dependencies": { - "minimatch": "^10.2.2", + "minimatch": "^11.0.2", "minipass": "^7.1.3", - "path-scurry": "^2.0.2" + "path-scurry": "^3.0.0" }, "engines": { "node": "18 || 20 || >=22" @@ -6140,9 +6312,9 @@ } }, "node_modules/glob/node_modules/brace-expansion": { - "version": "5.0.9", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", - "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "license": "MIT", "dependencies": { "balanced-match": "^4.0.2" @@ -6152,12 +6324,13 @@ } }, "node_modules/glob/node_modules/minimatch": { - "version": "10.2.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz", - "integrity": "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==", + "version": "11.0.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.2.tgz", + "integrity": "sha512-pWTgz5CN3tjqyZNSK2tePlSmu9IwM41q8yn8Usdqqwe9TIHh+9dEpLLjF4uApsfPEAZY71qtSiA2B2APEr+1Yw==", "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^5.0.2" + "@isaacs/nonrecursive-glob-match": "^1.0.2", + "brace-expansion": "^5.0.12" }, "engines": { "node": "18 || 20 || >=22" @@ -6167,9 +6340,9 @@ } }, "node_modules/globals": { - "version": "17.11.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-17.11.0.tgz", - "integrity": "sha512-Z2I8hM+PbJDXQDq3Icgpzv+mPdwr68iZUU9d5WW4FuXfDUQfkZaZuvjMv42/5crNyw154+9+VWXbYrUgDXbxNw==", + "version": "17.13.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-17.13.0.tgz", + "integrity": "sha512-RwMTC61u7hrG3ZJMkZQOK4JLJrKS8QtoTii63EmWvFXHqycY9FObBJQCbsLxSO8kjKhWE5kV1GC+Vb1g3RI0Zg==", "dev": true, "license": "MIT", "engines": { @@ -6686,7 +6859,6 @@ }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -6997,7 +7169,6 @@ }, "node_modules/isexe": { "version": "2.0.0", - "dev": true, "license": "ISC" }, "node_modules/js-string-escape": { @@ -7010,9 +7181,9 @@ } }, "node_modules/js-yaml": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.2.3.tgz", - "integrity": "sha512-n+mUVyUX5bVv7G/G2zyIHOhdxfuU1dY2NOFzTQUWiMUbFss8b57NFlgCCaggU78wSw5KVS9cllzeLyzyR+n5nw==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.5.0.tgz", + "integrity": "sha512-paNr4LFIFPjeeSmwNYdrb8FafLLG/Cr2Af3GjbsHJ5CxIjH4r0c2emlmRdAtpPAieP1gRVzk6buBbVP5gBMGAg==", "funding": [ { "type": "github", @@ -7025,12 +7196,28 @@ ], "license": "MIT", "dependencies": { - "argparse": "^2.0.1" + "argparse": "^3.0.3" }, "bin": { "js-yaml": "bin/js-yaml.mjs" } }, + "node_modules/js-yaml/node_modules/argparse": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.3.tgz", + "integrity": "sha512-Sn98ftV3KfsO8xfLPHG6oT8y+b0yvbrLgZjgPDXsharNY15tTAjqIsIju4S32nl6/iEUNNE4v+yL2Zhm8ooP3w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "PSF-2.0" + }, "node_modules/jschardet": { "version": "3.1.4", "resolved": "https://registry.npmjs.org/jschardet/-/jschardet-3.1.4.tgz", @@ -7042,13 +7229,16 @@ } }, "node_modules/jsdoc-type-pratt-parser": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-7.2.0.tgz", - "integrity": "sha512-dh140MMgjyg3JhJZY/+iEzW+NO5xR2gpbDFKHqotCmexElVntw7GjWjt511+C/Ef02RU5TKYrJo/Xlzk+OLaTw==", + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-9.3.0.tgz", + "integrity": "sha512-JZ8lKMCZXDlM1jAjAK5tTmtFJtgv6iFQQfjE3Fza6jBRACUueaEXLY17n1u05JO1lcPkNxgP+ddEDtiPsk5ktg==", "dev": true, "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.9" + }, "engines": { - "node": ">=20.0.0" + "node": "^22.22.2 || >=24.15.0" } }, "node_modules/json-buffer": { @@ -7074,9 +7264,9 @@ "license": "ISC" }, "node_modules/json-with-bigint": { - "version": "3.5.10", - "resolved": "https://registry.npmjs.org/json-with-bigint/-/json-with-bigint-3.5.10.tgz", - "integrity": "sha512-Vcx+JVNEBts/xfcoCS69sKrOhOk/3TVlvlT+XzUOefVKnnrbYSCKpDCm10pohsJFtsJVYnwa/cXRZ4eElzaM6w==", + "version": "3.5.12", + "resolved": "https://registry.npmjs.org/json-with-bigint/-/json-with-bigint-3.5.12.tgz", + "integrity": "sha512-uwbF/wSSuOgC7qqlq27Xp5B6a2MHVug3t0idZdTqu0JnlFvgJuH7ju+KAk/J06C7GfhoYy2gnb9wz2INqcne7w==", "license": "MIT" }, "node_modules/json5": { @@ -7211,6 +7401,18 @@ "node": ">= 0.8.0" } }, + "node_modules/lite-matter": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/lite-matter/-/lite-matter-0.1.2.tgz", + "integrity": "sha512-cGSYxO6vcipYZBSF5dUtDF3IqbkNxSjVQuvs5Ol3fO35URzHEvG2Ml0KbH5kvXXsx33SgbfwiVp6afwovarD8A==", + "license": "MIT", + "dependencies": { + "yaml": "^2.9.0" + }, + "funding": { + "url": "https://github.com/sponsors/mgks" + } + }, "node_modules/load-json-file": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-7.0.1.tgz", @@ -7223,143 +7425,622 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "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, + "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", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "license": "MIT" + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.kebabcase": { + "version": "4.1.1", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.snakecase": { + "version": "4.1.1", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.upperfirst": { + "version": "4.3.1", + "dev": true, + "license": "MIT" + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==" + }, + "node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/matcher": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/matcher/-/matcher-5.0.0.tgz", + "integrity": "sha512-s2EMBOWtXFc8dgqvoAzKJXxNHibcdJMV0gwqKUaw9E2JBJuGUK7DrNKrA6g/i+v72TT16+6sVm5mS3thaMLQUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^5.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/matcher/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": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/md5-hex": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/md5-hex/-/md5-hex-3.0.1.tgz", + "integrity": "sha512-BUiRtTtV39LIJwinWBjqVsU9xhdnz7/i889V859IBFpuqGAj6LuOvHv5XLbgZ2R7ptJoJaEcxkv88/h25T7Ciw==", + "dev": true, + "dependencies": { + "blueimp-md5": "^2.10.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/mdast-util-from-markdown": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.1.0.tgz", + "integrity": "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "decode-named-character-reference": "^1.0.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", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-to-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz", + "integrity": "sha1-elEhR1VWoE5+3etnsmSq550xKBQ=", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/memoize": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/memoize/-/memoize-10.2.0.tgz", + "integrity": "sha512-DeC6b7QBrZsRs3Y02A6A7lQyzFbsQbqgjI6UW0GigGWV+u1s25TycMr0XHZE4cJce7rY/vyw2ctMQqfDkIhUEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/memoize?sponsor=1" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromark": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz", + "integrity": "sha1-kTlaPhiEoZjmIRbjPJxWjjmTb9s=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/debug": "^4.0.0", + "debug": "^4.0.0", + "decode-named-character-reference": "^1.0.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": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz", + "integrity": "sha1-xpFjDkhQIaaM8o28Kyyifr9njNQ=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^1.0.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-factory-destination": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz", + "integrity": "sha1-j++OD3CB8EdPvdkt61DJkKAmRjk=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-label": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz", + "integrity": "sha1-UmfvqX8eUlTvx/ILRZo4yyEFi6E=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "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": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz", + "integrity": "sha1-NtAhLpYrKzEh+FJfx6PHwCnzNPw=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-title": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz", + "integrity": "sha1-I35KpdWKlYY/AQMtnumwkPHebpQ=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "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": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz", + "integrity": "sha1-BrJrKYPE0nv8xlezPiUTTUhosLE=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "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": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "integrity": "sha1-L5h4MaQNTFEKwmHomFLE6XA8zaY=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-chunked": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz", + "integrity": "sha1-R/vNk0caP8yrhs/wOEf8NVLbEFE=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-classify-character": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz", + "integrity": "sha1-05n6+cRcoUyLS+mLHqSBvO2Htik=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "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": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz", + "integrity": "sha1-Kg9JCrCL/1zC/V7sbdDKBPibMKk=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", "dependencies": { - "p-locate": "^5.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "micromark-util-chunked": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, - "node_modules/lodash": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", - "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", - "license": "MIT" - }, - "node_modules/lodash.camelcase": { - "version": "4.3.0", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.kebabcase": { - "version": "4.1.1", - "dev": true, - "license": "MIT" + "node_modules/micromark-util-decode-numeric-character-reference": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz", + "integrity": "sha1-/PFbZgl5OI5vEYzba/fXnXPSb+U=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } }, - "node_modules/lodash.merge": { - "version": "4.6.2", - "dev": true, - "license": "MIT" + "node_modules/micromark-util-decode-string": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz", + "integrity": "sha1-bLmVguXScehO/KjmGoB5lNcWHrI=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^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/lodash.snakecase": { - "version": "4.1.1", - "dev": true, + "node_modules/micromark-util-encode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "integrity": "sha1-DVHRwJVVHPqsNoMmljz1XxX1QLg=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT" }, - "node_modules/lodash.upperfirst": { - "version": "4.3.1", - "dev": true, + "node_modules/micromark-util-html-tag-name": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz", + "integrity": "sha1-5AQDCWSBmGtBwQZif5j3LU0QuCU=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT" }, - "node_modules/long": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", - "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==" - }, - "node_modules/lru-cache": { - "version": "11.5.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz", - "integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==", - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/matcher": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/matcher/-/matcher-5.0.0.tgz", - "integrity": "sha512-s2EMBOWtXFc8dgqvoAzKJXxNHibcdJMV0gwqKUaw9E2JBJuGUK7DrNKrA6g/i+v72TT16+6sVm5mS3thaMLQUw==", - "dev": true, + "node_modules/micromark-util-normalize-identifier": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz", + "integrity": "sha1-ww13sugyrPZSb4vxqke8nJQ4wW0=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", "dependencies": { - "escape-string-regexp": "^5.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "micromark-util-symbol": "^2.0.0" } }, - "node_modules/matcher/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, + "node_modules/micromark-util-resolve-all": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz", + "integrity": "sha1-4aLWLN0jcjCirhGDkCexk4HjHos=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "dev": true, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/md5-hex": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/md5-hex/-/md5-hex-3.0.1.tgz", - "integrity": "sha512-BUiRtTtV39LIJwinWBjqVsU9xhdnz7/i889V859IBFpuqGAj6LuOvHv5XLbgZ2R7ptJoJaEcxkv88/h25T7Ciw==", - "dev": true, "dependencies": { - "blueimp-md5": "^2.10.0" - }, - "engines": { - "node": ">=8" + "micromark-util-types": "^2.0.0" } }, - "node_modules/memoize": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/memoize/-/memoize-10.2.0.tgz", - "integrity": "sha512-DeC6b7QBrZsRs3Y02A6A7lQyzFbsQbqgjI6UW0GigGWV+u1s25TycMr0XHZE4cJce7rY/vyw2ctMQqfDkIhUEA==", - "dev": true, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "integrity": "sha1-q4l4m4GKWHUrc9a1UjhiG3+qj9c=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", "dependencies": { - "mimic-function": "^5.0.1" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sindresorhus/memoize?sponsor=1" + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" } }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "dev": true, + "node_modules/micromark-util-subtokenize": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz", + "integrity": "sha1-2K3lug8xl6HPaimZ+7/mNXoaGe4=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", - "engines": { - "node": ">= 8" + "dependencies": { + "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": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "integrity": "sha1-5dpJTo6ysHGg0I+zT2zv7GwKGbg=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", + "integrity": "sha1-8AIl9fWg68MlT5bDa2YFxLOTkI4=", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, "node_modules/micromatch": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", @@ -7517,9 +8198,9 @@ } }, "node_modules/node-forge": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.0.tgz", - "integrity": "sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.1.tgz", + "integrity": "sha512-w5/MfWaeMrpR/5ba6fZyAUTLSuE6aYz7H/3cYrqwZEmf5eQS3IaaLgJt4MBv7HglGFWmV22K8h4U18RJQmw/ow==", "license": "(BSD-3-Clause OR GPL-2.0)", "engines": { "node": ">= 6.13.0" @@ -7538,11 +8219,14 @@ } }, "node_modules/node-releases": { - "version": "2.0.18", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.18.tgz", - "integrity": "sha512-d9VeXT4SJ7ZeOqGX6R5EM022wpL+eWPooLI+5UpWn2jCT1aosUQEhQP214x33Wkwx3JQMvIm+tIoVOdodFS40g==", + "version": "2.0.54", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.54.tgz", + "integrity": "sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==", "dev": true, - "license": "MIT" + "license": "MIT", + "engines": { + "node": ">=18" + } }, "node_modules/nofilter": { "version": "3.1.0", @@ -7610,9 +8294,9 @@ } }, "node_modules/object-deep-merge": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/object-deep-merge/-/object-deep-merge-2.0.0.tgz", - "integrity": "sha512-3DC3UMpeffLTHiuXSy/UG4NOIYTLlY9u3V82+djSCLYClWobZiS4ivYzpIUWrRY/nfsJ8cWsKyG3QfyLePmhvg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/object-deep-merge/-/object-deep-merge-2.0.1.tgz", + "integrity": "sha512-aKttDKcU3pyZqKcCkDhsMn70WmZFG2JGDQLP9EcLyTSIFQRCPWLAmBZRLJnrVUrhPG1jETEEbfdgbNtJf1LyMg==", "dev": true, "license": "MIT" }, @@ -7717,16 +8401,18 @@ } }, "node_modules/optionator": { - "version": "0.9.3", + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", "dev": true, "license": "MIT", "dependencies": { - "@aashutoshrathi/word-wrap": "^1.2.3", "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", - "type-check": "^0.4.0" + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" }, "engines": { "node": ">= 0.8.0" @@ -7885,7 +8571,6 @@ }, "node_modules/path-key": { "version": "3.1.1", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -7897,9 +8582,9 @@ "license": "MIT" }, "node_modules/path-scurry": { - "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==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", + "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", "license": "BlueOak-1.0.0", "dependencies": { "lru-cache": "^11.0.0", @@ -7984,9 +8669,9 @@ } }, "node_modules/prettier": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.4.1.tgz", - "integrity": "sha512-G+YdqtITVZmOJje6QkXQWzl3fSfMxFwm1tjTyo9exhkmWSqC4Yhd1+lug++IlR2mvRVAxEDDWYkQdeSztajqgg==", + "version": "3.9.10", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.10.tgz", + "integrity": "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==", "dev": true, "license": "MIT", "bin": { @@ -8125,9 +8810,9 @@ } }, "node_modules/readdir-glob/node_modules/brace-expansion": { - "version": "5.0.9", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", - "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "license": "MIT", "dependencies": { "balanced-match": "^4.0.2" @@ -8485,7 +9170,6 @@ }, "node_modules/shebang-command": { "version": "2.0.0", - "dev": true, "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" @@ -8496,7 +9180,6 @@ }, "node_modules/shebang-regex": { "version": "3.0.0", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -8582,7 +9265,6 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "dev": true, "engines": { "node": ">=14" }, @@ -8650,6 +9332,17 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "dev": true, + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": ">= 12" + } + }, "node_modules/spdx-exceptions": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.5.0.tgz", @@ -8658,9 +9351,9 @@ "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==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-5.0.0.tgz", + "integrity": "sha512-vngmw3Rgn+o2arXNbnZaj5UtOEBuWBfvaI+Wc8GFfykIhA5/vdK9/Sp/XkLv63dykz2rxKDvKEHupF5P0FORcQ==", "dev": true, "license": "MIT", "dependencies": { @@ -8669,9 +9362,9 @@ } }, "node_modules/spdx-license-ids": { - "version": "3.0.22", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.22.tgz", - "integrity": "sha512-4PRT4nh1EImPbt2jASOKHX7PB7I+e4IWNLvkKFDxNhJlfjbYlleYQh285Z/3mPTHSAK/AvdMmw5BNNuYH8ShgQ==", + "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==", "dev": true, "license": "CC0-1.0" }, @@ -8758,7 +9451,6 @@ }, "node_modules/string-width": { "version": "4.2.3", - "dev": true, "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", @@ -8844,7 +9536,6 @@ }, "node_modules/strip-ansi": { "version": "6.0.1", - "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" @@ -8934,9 +9625,9 @@ } }, "node_modules/supertap/node_modules/js-yaml": { - "version": "3.15.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.0.tgz", - "integrity": "sha512-ttBQIIQPDeLjpPOohtUdXuXUVoA2uIB6fEH9HyJ7234s5mBJ5wTx20njxplLZQgLaOfpmPQA7X2t5AX6tIPbog==", + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", "dev": true, "license": "MIT", "dependencies": { @@ -9013,9 +9704,9 @@ } }, "node_modules/tar": { - "version": "7.5.20", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.20.tgz", - "integrity": "sha512-9FcyK4PA6+WbzlTM9WhQm6vB5W7cP7dUiPsv1g7YDwEQnQ1CGpK3MGlKk/ITVWMk05kHZuBhmVhiv8LZoy/PFQ==", + "version": "7.5.22", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", + "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { @@ -9203,9 +9894,9 @@ "license": "0BSD" }, "node_modules/tsx": { - "version": "4.23.12", - "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.12.tgz", - "integrity": "sha512-FDf4L4sYzKtzWYhU/Xm0AQFdTjdIxNo9ElTf2mxXM6k8YMHXzYUe4yODVaXP4V9uMFbVg8c0qyBccK2OOxb45Q==", + "version": "4.23.15", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz", + "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", "dev": true, "license": "MIT", "dependencies": { @@ -9355,16 +10046,16 @@ } }, "node_modules/typescript-eslint": { - "version": "8.67.0", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.67.0.tgz", - "integrity": "sha512-S2udFs8tCKEKffuJ4TB1idGUZiXdCPGi3IPBGWXarbLQ5UPXORV8QEVzJ4gCRduURMb5EkpNCdjbk0eDIuI8Yg==", + "version": "8.72.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.72.0.tgz", + "integrity": "sha512-r26Fkc8As+mZvqp7SLsMmNFyYUup/6CjK7/eHBHmhOw6GH6n6YFxHVFrG0jN1c5CMpDzelLPxvgeCOzx7BjN+A==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/eslint-plugin": "8.67.0", - "@typescript-eslint/parser": "8.67.0", - "@typescript-eslint/typescript-estree": "8.67.0", - "@typescript-eslint/utils": "8.67.0" + "@typescript-eslint/eslint-plugin": "8.72.0", + "@typescript-eslint/parser": "8.72.0", + "@typescript-eslint/typescript-estree": "8.72.0", + "@typescript-eslint/utils": "8.72.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -9398,12 +10089,12 @@ } }, "node_modules/undici": { - "version": "6.28.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz", - "integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==", + "version": "7.30.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz", + "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==", "license": "MIT", "engines": { - "node": ">=18.17" + "node": ">=20.18.1" } }, "node_modules/undici-types": { @@ -9426,6 +10117,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "integrity": "sha1-RJxuIaiA4IVb9aq63rOnQDFKusI=", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/universal-user-agent": { "version": "6.0.0", "license": "ISC" @@ -9476,9 +10180,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.1.tgz", - "integrity": "sha512-R8UzCaa9Az+38REPiJ1tXlImTJXlVfgHZsglwBD/k6nj76ctsH1E3q4doGrukiLQd3sGQYu56r5+lo5r94l29A==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.2.tgz", + "integrity": "sha512-UQ+MSxlhRm1bzjhU+DcuXfjFO1FzNtqhK5+9Yvlp90ItDLk5vT932A0rFu619nf7RVS+Y/VeaUW1jaRDqZ8VJw==", "dev": true, "funding": [ { @@ -9497,7 +10201,7 @@ "license": "MIT", "dependencies": { "escalade": "^3.2.0", - "picocolors": "^1.1.0" + "picocolors": "^1.1.1" }, "bin": { "update-browserslist-db": "cli.js" @@ -9528,9 +10232,9 @@ "license": "MIT" }, "node_modules/uuid": { - "version": "14.0.1", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-14.0.1.tgz", - "integrity": "sha512-6ZxzVpzDXDa3bJWaHilVayA+BH/1zmxCJoVgvmqJnid/gPoKHxUrS/aC/T6LGQtNHT+XHG9fXPJB4d+IrU30Ew==", + "version": "14.0.3", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-14.0.3.tgz", + "integrity": "sha512-Sc5u1VVln93y1Xnz4R+CunOZc7R9LUcTmhj7Rc7Eg3HVcf7rVn2FOoa812fe0W8p3jD7xeoGSYbfqCGGH2B6xw==", "funding": [ "https://github.com/sponsors/broofa", "https://github.com/sponsors/ctavan" @@ -9569,7 +10273,6 @@ }, "node_modules/which": { "version": "2.0.2", - "dev": true, "license": "ISC", "dependencies": { "isexe": "^2.0.0" @@ -9670,6 +10373,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "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_modules/wrap-ansi": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", @@ -9758,9 +10471,9 @@ } }, "node_modules/yaml": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", - "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", "license": "ISC", "bin": { "yaml": "bin.mjs" @@ -9845,16 +10558,37 @@ "dependencies": { "@actions/core": "^2.0.3", "@actions/github": "^8.0.1", - "@octokit/core": "^7.0.7", - "@octokit/plugin-paginate-rest": ">=9.2.2", - "@octokit/plugin-rest-endpoint-methods": "^17.0.0", + "@actions/tool-cache": "^3.0.1", + "@octokit/core": "^7.0.8", + "@octokit/plugin-paginate-rest": ">=16.0.0", + "@octokit/plugin-rest-endpoint-methods": "^18.0.0", + "glob": "^14.0.3", + "lite-matter": "^0.1.2", + "mdast-util-from-markdown": "^2.1.0", "semver": "^7.8.5", - "yaml": "^2.9.0" + "yaml": "^2.9.1" }, "devDependencies": { - "@types/node": "^20.19.43", - "tsx": "^4.23.12" + "@types/node": "^24.19.0", + "tsx": "^4.23.15" } + }, + "pr-checks/node_modules/@types/node": { + "version": "24.19.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.0.tgz", + "integrity": "sha512-zY+5tKxXdhGh1PYI0ac+7juvEu4OI6vWtVVoj5i2m42jxAY1U+zHGt6QCyOFwykdP62sM3MJ9stoYYUw5aCWew==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "pr-checks/node_modules/undici-types": { + "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" } } } diff --git a/package.json b/package.json index 8f1232ef38..8d917bf060 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,12 @@ { "name": "codeql", - "version": "4.37.9", + "version": "4.39.3", "private": true, "description": "CodeQL action", "scripts": { "_build_comment": "echo 'Run the full build so we typecheck the project and can reuse the transpiled files in npm test'", "build": "./scripts/check-node-modules.sh && npm run transpile && node build.mjs", + "format-yaml": "prettier --write --parser yaml '**/*.{yml,yaml}'", "lint": "eslint --report-unused-disable-directives --max-warnings=0 .", "lint-ci": "SARIF_ESLINT_IGNORE_SUPPRESSED=true eslint --report-unused-disable-directives --max-warnings=0 . --format @microsoft/eslint-formatter-sarif --output-file=eslint.sarif", "lint-fix": "eslint --report-unused-disable-directives --max-warnings=0 . --fix", @@ -13,7 +14,8 @@ "test": "npm run ava -- src/", "test-debug": "npm run test -- --timeout=20m", "transpile": "tsc --build --verbose tsconfig.json", - "update-pr-checks": "./pr-checks/sync.sh" + "update-pr-checks": "./pr-checks/sync.sh", + "typecheck": "tsc --noEmit" }, "license": "MIT", "workspaces": [ @@ -22,7 +24,7 @@ "dependencies": { "@actions/artifact": "^5.0.3", "@actions/artifact-legacy": "npm:@actions/artifact@^1.1.2", - "@actions/cache": "^5.2.0", + "@actions/cache": "^5.3.0", "@actions/core": "^2.0.3", "@actions/exec": "^2.0.0", "@actions/github": "^8.0.1", @@ -30,28 +32,27 @@ "@actions/http-client": "^3.0.0", "@actions/io": "^2.0.0", "@actions/tool-cache": "^3.0.1", - "@octokit/core": "^7.0.7", - "@octokit/plugin-paginate-rest": "^14.0.0", - "@octokit/plugin-rest-endpoint-methods": "^17.0.0", + "@octokit/core": "^7.0.8", + "@octokit/plugin-paginate-rest": "^16.0.0", + "@octokit/plugin-rest-endpoint-methods": "^18.0.0", "@octokit/plugin-retry": "^8.1.1", "archiver": "^8.0.0", - "fast-deep-equal": "^3.1.3", - "follow-redirects": "^1.16.0", + "follow-redirects": "^1.16.1", "get-folder-size": "^5.0.0", "https-proxy-agent": "^7.0.6", - "js-yaml": "^5.2.3", + "js-yaml": "^5.5.0", "jsonschema": "1.5.0", "long": "^5.3.2", - "node-forge": "^1.4.0", + "node-forge": "^1.4.1", "semver": "^7.8.5", - "uuid": "^14.0.1", - "undici": "^6.28.0" + "undici": "^7.30.1", + "uuid": "^14.0.3" }, "devDependencies": { "@ava/typescript": "6.0.0", - "@eslint/compat": "^2.1.0", + "@eslint/compat": "^2.1.1", "@microsoft/eslint-formatter-sarif": "^3.1.0", - "@octokit/types": "^16.0.0", + "@octokit/types": "^18.0.0", "@types/archiver": "^8.0.0", "@types/follow-redirects": "^1.14.4", "@types/js-yaml": "^4.0.9", @@ -59,21 +60,22 @@ "@types/node-forge": "^1.3.14", "@types/sarif": "^2.1.7", "@types/semver": "^7.8.0", - "@types/sinon": "^22.0.0", + "@types/sinon": "^22.0.1", "ava": "^6.4.1", "esbuild": "^0.28.2", "eslint": "^9.39.5", "eslint-import-resolver-typescript": "^4.4.5", "eslint-plugin-github": "^6.1.2", "eslint-plugin-import-x": "^4.17.1", - "eslint-plugin-jsdoc": "^62.9.0", + "eslint-plugin-jsdoc": "^65.4.0", "eslint-plugin-no-async-foreach": "^0.1.1", - "glob": "^13.0.6", - "globals": "^17.11.0", + "glob": "^14.0.3", + "globals": "^17.13.0", "nock": "^14.0.17", + "prettier": "^3.9.10", "sinon": "^22.1.0", "typescript": "^6.0.3", - "typescript-eslint": "^8.67.0" + "typescript-eslint": "^8.72.0" }, "overrides": { "@actions/tool-cache": { @@ -94,7 +96,7 @@ "eslint-plugin-jsx-a11y": { "semver": ">=6.3.1" }, - "glob": "^13.0.6", - "undici": "^6.28.0" + "glob": "^14.0.3", + "undici": "^7.30.1" } } diff --git a/pr-checks/.nvmrc b/pr-checks/.nvmrc new file mode 100644 index 0000000000..a45fd52cc5 --- /dev/null +++ b/pr-checks/.nvmrc @@ -0,0 +1 @@ +24 diff --git a/pr-checks/api-client.ts b/pr-checks/api-client.ts index 93675dba77..b8f914d815 100644 --- a/pr-checks/api-client.ts +++ b/pr-checks/api-client.ts @@ -1,10 +1,7 @@ import * as githubUtils from "@actions/github/lib/utils"; -import { type Octokit } from "@octokit/core"; -import { type PaginateInterface } from "@octokit/plugin-paginate-rest"; -import { type Api } from "@octokit/plugin-rest-endpoint-methods"; /** The type of the Octokit client. */ -export type ApiClient = Octokit & Api & { paginate: PaginateInterface }; +export type ApiClient = InstanceType; /** Constructs an `ApiClient` using `token` for authentication. */ export function getApiClient(token: string): ApiClient { diff --git a/pr-checks/bundle-changelog.test.ts b/pr-checks/bundle-changelog.test.ts index 6cc4d096ba..448851507d 100644 --- a/pr-checks/bundle-changelog.test.ts +++ b/pr-checks/bundle-changelog.test.ts @@ -10,17 +10,13 @@ import { afterEach, beforeEach, describe, it } from "node:test"; import { CLI_VERSION_ENV_VAR, + getChangenote, getCLIVersion, getPRNumber, getPRUrl, PR_URL_ENV_VAR, - updateChangelog, } from "./bundle-changelog"; -import { - EMPTY_CHANGELOG, - NO_CHANGES_STR, - UNRELEASED_PLACEHOLDER, -} from "./changelog"; +import { isValidChangenoteContent } from "./changelog/validate"; let testDir: string; @@ -85,58 +81,15 @@ describe("getPRNumber", async () => { }); }); -const testChangelog = `${EMPTY_CHANGELOG.trimEnd()} - -## 4.23.7 - -- Other change - -## 4.23.6 - -${NO_CHANGES_STR}`; - -const expectedChangelog = `# CodeQL Action Changelog - -## ${UNRELEASED_PLACEHOLDER} - -- Update default CodeQL bundle version to - -## 4.23.7 - -- Other change - -## 4.23.6 - -${NO_CHANGES_STR}`; - -describe("updateChangelog", async () => { - await it("removes `NO_CHANGES_STR` if present in [UNRELEASED] section", async () => { - const result = updateChangelog(EMPTY_CHANGELOG, ""); - assert.ok(!result.includes(NO_CHANGES_STR.trim())); - }); - - await it("doesn't remove `NO_CHANGES_STR` if present in versioned section", async () => { - const result = updateChangelog( - EMPTY_CHANGELOG.replace(UNRELEASED_PLACEHOLDER, "1.2.3"), - "", +describe("getChangenote", async () => { + await it("returns a note linking to the bundle release and the PR", async () => { + assert.equal( + getChangenote("1.2.3", testPrUrl), + "- Update default CodeQL bundle version to [1.2.3](https://github.com/github/codeql-action/releases/tag/codeql-bundle-v1.2.3). [#42](https://github.com/github/codeql-action/pulls/42)\n", ); - assert.ok(result.includes(NO_CHANGES_STR.trim())); - }); - - await it("throws if there are no sections", async () => { - assert.throws(() => { - updateChangelog( - "# CodeQL Action Changelog", - "- Update default CodeQL bundle version to", - ); - }); }); - await it("adds note at the end of the first section", async () => { - const result = updateChangelog( - testChangelog, - "- Update default CodeQL bundle version to", - ); - assert.deepEqual(result, expectedChangelog); + await it("returns valid changenote content", async () => { + assert.ok(isValidChangenoteContent(getChangenote("1.2.3", testPrUrl))); }); }); diff --git a/pr-checks/bundle-changelog.ts b/pr-checks/bundle-changelog.ts index 557a8556c1..8019c70904 100755 --- a/pr-checks/bundle-changelog.ts +++ b/pr-checks/bundle-changelog.ts @@ -1,17 +1,13 @@ #!/usr/bin/env npx tsx /** - * Updates the changelog with a change note for an updated CodeQL CLI bundle. + * Creates a changenote file for an update to the default CodeQL CLI bundle. */ import * as fs from "node:fs"; +import * as path from "node:path"; -import { - parseChangelog, - renderChangelog, - UNRELEASED_PLACEHOLDER, -} from "./changelog"; -import { CHANGELOG_FILE, CLI_BUNDLE_RELEASE_URL_PREFIX } from "./config"; +import { CHANGENOTES_DIR, CLI_BUNDLE_RELEASE_URL_PREFIX } from "./config"; import { getErrorMessage } from "./util"; export const CLI_VERSION_ENV_VAR = "CLI_VERSION"; @@ -58,42 +54,19 @@ export function getPRNumber(prUrl: string) { } /** - * Updates `changelog` by adding `changelogNote` to the first section. + * Returns the contents of the changenote file for an update to the default + * CodeQL CLI bundle. * - * @param contents The existing changelog contents. - * @param changelogNote The note to add to the first section. + * @param cliVersion The CodeQL CLI version of the new default bundle. + * @param prUrl The URL of the PR that updates the default bundle. + * @throws If the PR number can't be determined from `prUrl`. */ -export function updateChangelog(contents: string, changelogNote: string) { - // If the "[UNRELEASED]" section starts with "no user facing changes", remove that line. - contents = contents.replace( - `## ${UNRELEASED_PLACEHOLDER}\n\nNo user facing changes.`, - `## ${UNRELEASED_PLACEHOLDER}\n`, - ); +export function getChangenote(cliVersion: string, prUrl: string): string { + // The GitHub Release for the new bundle version. + const bundleReleaseUrl = `${CLI_BUNDLE_RELEASE_URL_PREFIX}${cliVersion}`; - const changelog = parseChangelog(contents); - - if (changelog.sections.length === 0) { - throw new Error("The changelog contains no existing sections."); - } - - // Add the changelog note to the bottom of the first section. - const firstSection = changelog.sections[0]; - const lastLine = firstSection.bodyLines.pop(); - - if (lastLine !== undefined && lastLine.trim() !== "") { - // We expect the last line to be empty. If it isn't for some reason, - // add it back. - firstSection.bodyLines.push(lastLine); - } - - firstSection.bodyLines.push(changelogNote); - - // If the last line is empty as expected, then add it back in after the new note. - if (lastLine?.trim() === "") { - firstSection.bodyLines.push(lastLine); - } - - return renderChangelog(changelog); + const prNumber = getPRNumber(prUrl); + return `- Update default CodeQL bundle version to [${cliVersion}](${bundleReleaseUrl}). [#${prNumber}](${prUrl})\n`; } function main() { @@ -101,27 +74,24 @@ function main() { const cliVersion = getCLIVersion(); const prUrl = getPRUrl(); - // The GitHub Release for the new bundle version. - const bundleReleaseUrl = `${CLI_BUNDLE_RELEASE_URL_PREFIX}${cliVersion}`; - - // Get the PR number from the PR URL. - const prNumber = getPRNumber(prUrl); - const changelogNote = `- Update default CodeQL bundle version to [${cliVersion}](${bundleReleaseUrl}). [#${prNumber}](${prUrl})`; - - let changelog = fs.readFileSync(CHANGELOG_FILE, "utf-8"); - - changelog = updateChangelog(changelog, changelogNote); - - fs.writeFileSync(CHANGELOG_FILE, changelog); + // Include the CLI version in the file name so that changenotes for + // different bundle updates don't conflict. + const changenotePath = path.join( + CHANGENOTES_DIR, + `update-bundle-${cliVersion}.md`, + ); + fs.writeFileSync(changenotePath, getChangenote(cliVersion, prUrl)); return 0; } catch (err) { - console.error(`Failed to bundle changelog: ${getErrorMessage(err)}`); + console.error( + `Failed to create changenote for bundle update: ${getErrorMessage(err)}`, + ); return -1; } } // Only call `main` if this script was run directly. -if (require.main === module) { +if (import.meta.main) { process.exit(main()); } diff --git a/pr-checks/bundle-metadata.ts b/pr-checks/bundle-metadata.ts index 25c282e9ae..f06b7104d3 100755 --- a/pr-checks/bundle-metadata.ts +++ b/pr-checks/bundle-metadata.ts @@ -43,6 +43,6 @@ async function main() { } // Only call `main` if this script was run directly. -if (require.main === module) { +if (import.meta.main) { void main(); } diff --git a/pr-checks/changelog.test.ts b/pr-checks/changelog.test.ts index 817852e3e1..8132e65766 100755 --- a/pr-checks/changelog.test.ts +++ b/pr-checks/changelog.test.ts @@ -9,17 +9,46 @@ import * as fs from "node:fs"; import { describe, it } from "node:test"; import { + addBodyLinesToUnreleasedSection, + ChangelogSection, EMPTY_CHANGELOG, + getHeader, getReleaseDateString, + NO_CHANGES_STR, parseChangelog, processChangelogForBackports, renderChangelog, setVersionAndDate, + UNRELEASED_PLACEHOLDER, } from "./changelog"; import { CHANGELOG_FILE } from "./config"; const testDate = new Date(2026, 7, 14); +describe("getHeader", async () => { + function Section(headerLine: string): ChangelogSection { + return { + headerLine, + bodyLines: [], + }; + } + await it("returns non-headers unchanged", () => { + assert.equal("foo", getHeader(Section("foo"))); + assert.equal("- bar", getHeader(Section("- bar"))); + }); + await it("strips octothorpes", async () => { + assert.equal("foo", getHeader(Section("# foo"))); + assert.equal("foo", getHeader(Section("## foo"))); + assert.equal("foo", getHeader(Section("### foo"))); + assert.equal("foo", getHeader(Section("#### foo"))); + assert.equal("foo", getHeader(Section("##### foo"))); + assert.equal("foo", getHeader(Section("###### foo"))); + }); + await it("strips whitespace", async () => { + assert.equal("foo", getHeader(Section("# foo "))); + }); +}); + describe("getReleaseDateString", async () => { await it("formats dates as expected", async () => { assert.equal(getReleaseDateString(testDate), "14 Aug 2026"); @@ -70,3 +99,73 @@ describe("processChangelogForBackports", async () => { assert.deepEqual(result.split("\n"), testChangelogResult.split("\n")); }); }); + +describe("addBodyLinesToUnreleasedSection", async () => { + function newChangelogWithSections(sections: ChangelogSection[]) { + return { + preamble: [], + sections, + }; + } + + await it("throws error if '[UNRELEASED]' section is not first", async () => { + const invalidChangelog = newChangelogWithSections([ + { + headerLine: "## Release 1.0.0", + bodyLines: [], + }, + { + headerLine: `## ${UNRELEASED_PLACEHOLDER}`, + bodyLines: [], + }, + ]); + assert.throws(() => + addBodyLinesToUnreleasedSection(invalidChangelog, ["foo"]), + ); + }); + + await it("overwrites 'No user facing changes.'", async () => { + const changelog = newChangelogWithSections([ + { + headerLine: `## ${UNRELEASED_PLACEHOLDER}`, + bodyLines: ["", NO_CHANGES_STR, ""], + }, + ]); + + addBodyLinesToUnreleasedSection(changelog, ["- foo"]); + + assert.equal(changelog.sections[0].bodyLines.length, 3); + assert.deepEqual(changelog.sections[0].bodyLines, ["", "- foo", ""]); + }); + + await it("does nothing if lines is empty", async () => { + const changelog = newChangelogWithSections([ + { + headerLine: `## ${UNRELEASED_PLACEHOLDER}`, + bodyLines: ["", NO_CHANGES_STR, ""], + }, + ]); + const changelogClone = structuredClone(changelog); + + addBodyLinesToUnreleasedSection(changelog, []); + + assert.deepEqual(changelog, changelogClone); + }); + + await it("inserts a line", async () => { + const changelog = newChangelogWithSections([ + { + headerLine: `## ${UNRELEASED_PLACEHOLDER}`, + bodyLines: ["", "- Added a new dependency.", ""], + }, + ]); + const lineToInsert = "- foo"; + + addBodyLinesToUnreleasedSection(changelog, [lineToInsert]); + + assert.equal(changelog.sections[0].bodyLines.length, 4); + assert.ok( + changelog.sections[0].bodyLines.some((line) => line === lineToInsert), + ); + }); +}); diff --git a/pr-checks/changelog.ts b/pr-checks/changelog.ts index 4cf1e75494..496310d21f 100644 --- a/pr-checks/changelog.ts +++ b/pr-checks/changelog.ts @@ -6,14 +6,16 @@ import { CHANGELOG_FILE, DryRunOption } from "./config"; export const UNRELEASED_PLACEHOLDER = "[UNRELEASED]"; /** The default contents for a section in the changelog. */ -export const NO_CHANGES_STR = "No user facing changes.\n\n"; +export const NO_CHANGES_STR = "No user facing changes."; /** Placeholder changelog content for a new release. */ export const EMPTY_CHANGELOG = `# CodeQL Action Changelog ## ${UNRELEASED_PLACEHOLDER} -${NO_CHANGES_STR}`; +${NO_CHANGES_STR} + +`; /** * Represents sections in a changelog. @@ -31,6 +33,13 @@ export interface Changelog { sections: ChangelogSection[]; } +/** + * Returns the text of the header (without the '## ' prefix) of the given section. + * */ +export function getHeader(section: ChangelogSection): string { + return section.headerLine.replace(/^#+\s+/, "").trimEnd(); +} + /** Returns `date` formatted as `DD Mon YYYY`. */ export function getReleaseDateString(today: Date = new Date()): string { return today.toLocaleDateString("en-GB", { @@ -125,6 +134,42 @@ export function parseChangelog(content: string): Changelog { return { preamble, sections }; } +/** + * Inserts the changenotes `lines` in the `[UNRELEASED]` section of `changelog`. + * If the section contains the stock message {@link NO_CHANGES_STR}, then + * `lines` will be inserted in place and the stock message will be deleted. + * + * @throws Error -- if the [UNRELEASED] section does not exist. + * + * @param changelog The CHANGELOG object to modify. + * @param lines The changenotes to insert. + */ +export function addBodyLinesToUnreleasedSection( + changelog: Changelog, + lines: string[], +) { + // Do nothing if there is nothing to insert. + if (lines.length === 0) return; + + const unreleasedSection = changelog.sections[0]; + if (getHeader(unreleasedSection) !== UNRELEASED_PLACEHOLDER) { + throw Error( + `'${UNRELEASED_PLACEHOLDER}' is not the first section of 'CHANGELOG.md'`, + ); + } + + if (unreleasedSection.bodyLines.includes(NO_CHANGES_STR)) { + unreleasedSection.bodyLines = ["", ...lines, ""]; + return; + } + + // The last body line should be a blank line (for spacing). + // Remove it so that we can add `lines` and then add the blank line back. + unreleasedSection.bodyLines.pop(); + unreleasedSection.bodyLines.push(...lines); + unreleasedSection.bodyLines.push(""); +} + /** * Combines an array of lines into a single string by adding line breaks. */ @@ -204,7 +249,7 @@ export function processChangelogForBackports( // Add an entry if we didn't keep any. if (!foundContent) { - section.bodyLines.push(NO_CHANGES_STR.trim()); + section.bodyLines.push(NO_CHANGES_STR); } } diff --git a/pr-checks/changelog/validate.test.ts b/pr-checks/changelog/validate.test.ts new file mode 100644 index 0000000000..77a18e8ba2 --- /dev/null +++ b/pr-checks/changelog/validate.test.ts @@ -0,0 +1,166 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { withTmpFile } from "../../src/util"; + +import { + hasValidChangenoteCategory, + isValidChangenoteContent, + isValidChangenoteFile, + isValidChangenoteFilename, + VALID_CHANGE_NOTE_CATEGORIES, +} from "./validate"; + +await describe("isValidChangenoteContent", async () => { + await it("recognizes an unordered Markdown list", () => { + const inputs = [ + "- One changenote entry", + "- First item\n- Second item", + "\n\n\n\n- Fixed a bug\n- Added a feature", + ]; + + for (const input of inputs) { + assert.equal(isValidChangenoteContent(input), true); + } + }); + + await it("does not recognize non-Markdown text", () => { + const inputs = [ + "This is not a list.", + '["this", "is", "JSON"]', + "---", + "***", + "___", + "paragraph", + ]; + + for (const input of inputs) { + assert.equal(isValidChangenoteContent(input), false); + } + }); + + await it("does not recognize ordered Markdown lists", () => { + const inputs = [ + "1. First item\n2. Second item", + "\n\n\n1. First item\n1. Second item", + ]; + + for (const input of inputs) { + assert.equal(isValidChangenoteContent(input), false); + } + }); + + await it("requires all list items to use a hyphen bullet", () => { + const inputs = [ + "* Fixed a bug\n* Added feature", + "+ Fixed a bug\n+ Added feature", + "- Fixed a bug\n* Added feature", + "- Fixed a bug\n+ Added feature", + "- Fixed a bug\n * Added feature\n + Updated docs", + "\n\n\n* Fixed a bug", + "\n\n\n+ Fixed a bug", + "---\n* Fixed a bug\n* Added feature", + ] as const; + + for (const input of inputs) { + assert.equal(isValidChangenoteContent(input), false); + } + }); + + await it("does not contain other Markdown elements", () => { + const inputs = [ + "- Fixed a bug\n\nParagraph of text", + "- Fixed a bug\n\n* Added a feature", + "# Header\n- Fixed a bug", + "- Fixed a bug\n## Subheader", + ]; + + for (const input of inputs) { + assert.equal(isValidChangenoteContent(input), false); + } + }); +}); + +await describe("isValidChangenoteFilename", async () => { + await it("accepts valid filenames", () => { + const inputs = [ + "2023-01-01-fix-bug.md", + "2023-12-31-add-feature.md", + "2023-06-15-update-docs.md", + ]; + + for (const input of inputs) { + assert.equal(isValidChangenoteFilename(input), true); + } + }); + + await it("rejects invalid filenames", () => { + const inputs = [ + "missing-date-from-filename.md", + "2021-01-01.md", + "2026-12-19-wrong-file-name-extension.txt", + ]; + + for (const input of inputs) { + assert.equal(isValidChangenoteFilename(input), false); + } + }); +}); + +await describe("hasValidChangenoteCategory", async () => { + await it("accepts valid categories", () => { + for (const category of Object.keys(VALID_CHANGE_NOTE_CATEGORIES)) { + const frontmatter = { category }; + assert.equal(hasValidChangenoteCategory(frontmatter), true); + } + }); + + await it("rejects invalid categories", () => { + const inputs = [ + "", + "invalid-category", + "bug-fix", + "new-feature", + "security-patch", + "miscellaneous", + "documentation", + ]; + + for (const category of inputs) { + const frontmatter = { category }; + assert.equal(hasValidChangenoteCategory(frontmatter), false); + } + }); + + await it("reject missing category", () => { + assert.equal(hasValidChangenoteCategory({}), false); + assert.equal(hasValidChangenoteCategory({ category: null }), false); + assert.equal(hasValidChangenoteCategory({ category: undefined }), false); + }); +}); + +await describe("isValidChangenoteFile", async () => { + await it("accepts a valid change-note file", async () => { + await withTmpFile( + "2026-01-01-fix-bug.md", + "---\ncategory: fix\n---\n- Fixed a bug\n", + (filePath) => { + assert.equal(isValidChangenoteFile(filePath), true); + }, + ); + }); + + await it("rejects a non-existent path", async () => { + assert.equal(isValidChangenoteFile("non-existent-file.md"), false); + }); + + await it("rejects invalid Markdown", async () => { + await withTmpFile( + "2026-01-01-fix-bug.md", + "---\ncategory: fix\n---\n* Fixed a bug\n", + (filePath) => { + assert.equal(isValidChangenoteFile(filePath), false); + }, + ); + }); +}); diff --git a/pr-checks/changelog/validate.ts b/pr-checks/changelog/validate.ts new file mode 100644 index 0000000000..fa0caec3e5 --- /dev/null +++ b/pr-checks/changelog/validate.ts @@ -0,0 +1,106 @@ +import * as fs from "node:fs"; + +import { matter } from "lite-matter"; +import type { List, ListItem } from "mdast"; +import { fromMarkdown } from "mdast-util-from-markdown"; + +// Regex for filename: YYYY-MM-DD-id.md +const VALID_CHANGE_NOTE_FILENAME_PATTERN = + /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])-([a-z0-9]+(?:-[a-z0-9]+)*)\.md$/; + +export const VALID_CHANGE_NOTE_CATEGORIES = { + breaking: "Breaking Changes", + feature: "New Features", + improvement: "Improvements", + securityFix: "Security Fixes", + fix: "Bug Fixes", + unship: "Removed Features", + deprecation: "Deprecations", + knownIssue: "Known Issues", + misc: "Miscellaneous", +}; + +/** + * Validates that the given Markdown string meets the criteria for a change-note, which is: + * - A single unordered list + * - Each list item must start with a hyphen (-) + * - No other Markdown elements are allowed + * @param content The Markdown string to validate + * @returns True if the string is a valid change-note, false otherwise + */ +export function isValidChangenoteContent(content: string): boolean { + const ast = fromMarkdown(content); + const lines = content.split("\n"); + + function listHasHyphenBullets(node: List | ListItem): boolean { + if (node.type === "list") { + return node.children.every(listHasHyphenBullets); + } + + const line = lines[node.position!.start.line - 1].trim(); + return ( + line.startsWith("-") && + node.children.every( + (child) => child.type !== "list" || listHasHyphenBullets(child), + ) + ); + } + + return ( + ast.children.length === 1 && + ast.children[0].type === "list" && + ast.children[0].ordered === false && + listHasHyphenBullets(ast.children[0]) + ); +} + +/** + * Validates that the given filename meets the criteria for a change-note filename. + * @param filename The name of the change-note file to validate. + * @returns True if the filename is valid, false otherwise. + */ +export function isValidChangenoteFilename(filename: string): boolean { + return filename.match(VALID_CHANGE_NOTE_FILENAME_PATTERN) !== null; +} + +/** + * Validates that the given frontmatter has a valid change-note category. + * @param frontmatter The frontmatter object to validate. + * @returns True if the frontmatter has a valid category, false otherwise. + */ +export function hasValidChangenoteCategory( + frontmatter: Record, +): boolean { + const category = frontmatter["category"]; + return ( + typeof category === "string" && + Object.hasOwn(VALID_CHANGE_NOTE_CATEGORIES, category) + ); +} + +/** + * Validates that the given change-note file meets all of the criteria for a change-note. + * @param filename The name of the change-note file to validate. + * @returns True if the file is a valid change-note, false otherwise. + */ +export function isValidChangenoteFile(filename: string): boolean { + let isValid: boolean = true; + + let fileData: string | undefined; + try { + fileData = fs.readFileSync(filename, "utf8"); + } catch (error) { + console.error(`${filename}: failed to read file`, error); + return false; + } + + const { content } = matter(fileData); + if (!isValidChangenoteContent(content)) { + isValid = false; + console.error( + `${filename}: invalid Markdown; content must be a single unordered list with hyphen bullets and no other Markdown elements`, + ); + } + + return isValid; +} diff --git a/pr-checks/changenotes.ts b/pr-checks/changenotes.ts new file mode 100755 index 0000000000..d9ccd84613 --- /dev/null +++ b/pr-checks/changenotes.ts @@ -0,0 +1,143 @@ +#!/usr/bin/env npx tsx + +import * as fs from "node:fs"; +import { pathToFileURL } from "node:url"; +import { parseArgs } from "node:util"; +import path from "path"; + +import { ExitCode } from "@actions/core"; +import { matter } from "lite-matter"; + +import { + addBodyLinesToUnreleasedSection, + parseChangelog, + renderChangelog, + withChangelog, +} from "./changelog"; +import { isValidChangenoteFile } from "./changelog/validate"; +import { CHANGENOTES_DIR } from "./config"; + +/** + * Describes a changenote file, including its file path, frontmatter, and content. + */ +interface ChangenoteFile { + absolutePath: string; + data: Record; + content: string; +} + +/** + * Returns the absolute file paths of all files in + * {@link CHANGENOTES_DIR} (except ".gitkeep" and "README.md"). + * */ +function listUnreleasedChangenoteDir(): string[] { + return fs + .readdirSync(CHANGENOTES_DIR) + .filter((name) => ![".gitkeep", "README.md"].includes(name)) + .map((name) => path.join(CHANGENOTES_DIR, name)); +} + +/** + * Scans the {@link CHANGENOTES_DIR} directory for changenote files + * and returns a parsed listing of those changenote files. + */ +function getChangenotes(): ChangenoteFile[] { + return listUnreleasedChangenoteDir().map((absolutePath) => { + return { + absolutePath, + ...matter(fs.readFileSync(absolutePath, "utf-8")), + }; + }); +} + +/** + * Populates the '[UNRELEASED]' section of CHANGELOG.md with the contents + * of the changenotes in {@link CHANGENOTES_DIR} and then deletes those changenotes. + * @param contents The contents of CHANGELOG.md + * @returns The updated contents of CHANGELOG.md + */ +export function transferChangenotesToChangelog(contents: string): string { + const changenotes = getChangenotes(); + const changenoteBodies = changenotes.map((c) => c.content.trim()); + const changenotePaths = changenotes.map((c) => c.absolutePath); + + const changelog = parseChangelog(contents); + addBodyLinesToUnreleasedSection(changelog, changenoteBodies); + const updatedChangelog = renderChangelog(changelog); + + for (const p of changenotePaths) { + fs.unlinkSync(p); + } + + return updatedChangelog; +} + +const entryPoint = process.argv[1]; +if (entryPoint && import.meta.url === pathToFileURL(entryPoint).href) { + try { + process.exit(main()); + } catch (error) { + console.error(error); + process.exit(ExitCode.Failure); + } +} + +function main(): ExitCode { + const { positionals } = parseArgs({ + allowPositionals: true, + strict: true, + }); + const [command] = positionals; + switch (command) { + case undefined: + case "help": + return usage(); + case "assemble": + return assemble(); + case "validate": + return validate(); + default: + console.error(`Unknown command: ${command}`); + return ExitCode.Failure; + } +} + +function usage(): ExitCode { + const message = + "Usage: changenotes.ts assemble\n" + + " changenotes.ts validate\n" + + " changenotes.ts help"; + console.log(message); + return ExitCode.Success; +} + +function assemble(): ExitCode { + try { + withChangelog((contents) => { + return transferChangenotesToChangelog(contents); + }, {}); + return ExitCode.Success; + } catch (e) { + console.error("Failed to assemble changenotes to 'CHANGELOG.md'", e); + } + return ExitCode.Failure; +} + +function validate(): ExitCode { + try { + const allChangenotesValid = getChangenotes().reduce( + (r, changenote) => r && isValidChangenoteFile(changenote.absolutePath), + true, + ); + if (allChangenotesValid) { + console.log(`All changenotes in '${CHANGENOTES_DIR}' are valid.`); + return ExitCode.Success; + } + } catch (error) { + console.error( + `Failed to read changenotes directory '${CHANGENOTES_DIR}'`, + error, + ); + } + return ExitCode.Failure; +} diff --git a/pr-checks/check-diagnostics.ts b/pr-checks/check-diagnostics.ts new file mode 100644 index 0000000000..cc619aa9c3 --- /dev/null +++ b/pr-checks/check-diagnostics.ts @@ -0,0 +1,118 @@ +import fs from "fs"; +import path from "path"; + +import * as core from "@actions/core"; +import { globSync } from "glob"; + +import * as sarif from "../src/sarif"; + +const DIAGNOSTIC_ID = + process.env["DIAGNOSTIC_ID"] ?? "lang/diagnostics/example"; +const DIAGNOSTIC_NAME = process.env["DIAGNOSTIC_NAME"] ?? "Diagnostic name"; +const EXPECTED_MESSAGE = process.env["EXPECTED_MESSAGE"] ?? "Plaintext message"; +const EXPECTED_LOCATIONS = Number.parseInt( + process.env["EXPECTED_LOCATIONS"] ?? "1", +); + +function checkStatusPageNotification(n: sarif.Notification) { + const expectedMessage = EXPECTED_MESSAGE.trim(); + if (!n.message.text?.includes(expectedMessage)) { + if (n.message.text !== undefined) { + core.setFailed( + `Expected the status page diagnostic to contain the message '${expectedMessage}', but found '${n.message.text.replaceAll("\n", "\\n")}'.`, + ); + } else { + core.setFailed( + `Expected the status page diagnostic to contain the message '${expectedMessage}', but found nothing.`, + ); + } + } + + const locationCount = n.locations?.length ?? 0; + if (locationCount !== EXPECTED_LOCATIONS) { + core.setFailed( + `Expected the status page diagnostic to have exactly ${EXPECTED_LOCATIONS} location(s), but found ${locationCount}.`, + ); + } +} + +function checkSarif(sarifFile: string) { + core.info(`Checking SARIF file at '${sarifFile}'`); + + const log = JSON.parse(fs.readFileSync(sarifFile, "utf8")) as sarif.Log; + const run = log.runs[0]; + + if (run.invocations === undefined) { + throw new Error("run.invocations is undefined"); + } + + const toolExecutionNotifications = + run.invocations[0].toolExecutionNotifications; + + if (toolExecutionNotifications === undefined) { + throw new Error("toolExecutionNotifications is undefined"); + } + + const statusPageNotifications = toolExecutionNotifications.filter( + (n) => + n.descriptor?.id === DIAGNOSTIC_ID && + n.properties?.visibility?.statusPage, + ); + if (statusPageNotifications.length !== 1) { + core.setFailed( + "Expected exactly one status page reporting descriptor for this diagnostic in the " + + `'runs[].invocations[].toolExecutionNotifications[]' SARIF property, but found ` + + `${statusPageNotifications.length}. All notification reporting descriptors: ` + + `${JSON.stringify(toolExecutionNotifications)}.`, + ); + } + checkStatusPageNotification(statusPageNotifications[0]); + + const notifications = run.tool.driver.notifications; + + if (notifications === undefined) { + throw new Error("notifications is undefined"); + } + + const diagnosticNotification = notifications.filter( + (n) => + n.id === DIAGNOSTIC_ID && + n.name === DIAGNOSTIC_ID && + n.fullDescription?.text === DIAGNOSTIC_NAME, + ); + if (diagnosticNotification.length !== 1) { + core.setFailed( + "Expected exactly one notification for this diagnostic in the " + + `'runs[].tool.driver.notifications[]' SARIF property, but found ` + + `${diagnosticNotification.length}. All notifications: ` + + `${JSON.stringify(notifications)}.`, + ); + } +} + +const sarifPath = process.env["SARIF_PATH"]; + +if (sarifPath === undefined) { + throw new Error( + "The path to a SARIF file or directory must be set in 'SARIF_PATH'.", + ); +} + +if (fs.statSync(sarifPath).isDirectory()) { + const sarifFiles = globSync("**/*.sarif", { + cwd: path.resolve(sarifPath), + absolute: true, + }); + + if (sarifFiles.length < 1) { + throw new Error(`Unable to find any .sarif files in '${sarifPath}'.`); + } + + for (const sarifFile of sarifFiles) { + checkSarif(sarifFile); + } +} else { + checkSarif(sarifPath); +} + +core.info("Finished diagnostic export test"); diff --git a/pr-checks/check-repo-size.ts b/pr-checks/check-repo-size.ts index e38b19cce0..b15a85c1b3 100644 --- a/pr-checks/check-repo-size.ts +++ b/pr-checks/check-repo-size.ts @@ -218,6 +218,6 @@ async function run(): Promise { } } -if (require.main === module) { +if (import.meta.main) { void run(); } diff --git a/pr-checks/check-unchanged.ts b/pr-checks/check-unchanged.ts new file mode 100755 index 0000000000..05ceb7ab4b --- /dev/null +++ b/pr-checks/check-unchanged.ts @@ -0,0 +1,153 @@ +#!/usr/bin/env npx tsx + +import * as fs from "node:fs"; +import * as path from "node:path"; +import { parseArgs } from "node:util"; + +import * as core from "@actions/core"; + +import { runCommand, runGit } from "./command"; +import { LIB_ROOT, PR_CHECKS_DIR, REPO_ROOT } from "./config"; +import { getErrorMessage } from "./util"; + +/** + * Checks whether the repo is clean by running `git status --porcelain`. + * If the repository is not clean, the changes are printed to stdout. + * + * @returns `true` if the repo is clean or `false` otherwise. + */ +function isRepoClean(): boolean { + const stdout = runGit(["status", "--porcelain"]); + + if (stdout === "") { + return true; + } + + console.log(stdout); + return false; +} + +/** + * Checks whether the repository is clean to begin with, then runs {@link body}, and finally + * checks if the repository is still clean. + * + * @param body The function to run. + * @returns `true` if the repo is clean or `false` otherwise. + */ +function checkUnchanged(body: () => void): boolean { + // Sanity check that repo is clean to start with + if (isRepoClean()) { + console.info("Repository is clean."); + } else { + // If we get a fail here then this workflow needs attention... + console.error("The repository contains uncomitted changes!"); + return false; + } + + body(); + + // Check that repo is still clean + const result = isRepoClean(); + if (result) { + console.info("Repository is still clean."); + } else { + console.info("Repository is now dirty."); + } + return result; +} + +/** + * Produces a full diff for the repository and adds it to the workflow job summary + * under the {@link summaryHeader} header. + */ +async function addDiffToSummary(summaryHeader: string) { + const diffFile = path.join( + process.env["RUNNER_TEMP"] ?? PR_CHECKS_DIR, + "summary.diff", + ); + + try { + runCommand("git", ["status"]); + runCommand("git", ["diff", `--output=${diffFile}`], { + execOptions: { cwd: REPO_ROOT }, + }); + + core.summary.addHeading(summaryHeader, 3); + core.summary.addCodeBlock(fs.readFileSync(diffFile, "utf-8"), "diff"); + await core.summary.write(); + + try { + fs.rmSync(diffFile); + } catch (err) { + console.warn( + `Failed to remove temporary diff file from '${diffFile}': ${getErrorMessage(err)}`, + ); + } + } catch (err) { + console.error( + `Failed to add full diff to summary for '${summaryHeader}': ${getErrorMessage(err)}`, + ); + } +} + +/** + * Rebuilds the JavaScript by cleaning up and running `npm run build`. + */ +function rebuildJavaScript() { + // Wipe the lib directory in case there are extra unnecessary files in there + console.info(`Removing ${LIB_ROOT}...`); + fs.rmSync(LIB_ROOT, { recursive: true, force: true }); + + // Generate the JavaScript files + runCommand("npm", ["run", "build"], { execOptions: { shell: true } }); +} + +/** + * Formats YAML files with `npm run format-yaml`. + */ +function formatYAML() { + runCommand("npm", ["run", "format-yaml"], { execOptions: { shell: true } }); +} + +async function main() { + const { values: options } = parseArgs({ + options: { language: { type: "string", default: "javascript" } }, + }); + console.info(`Checking that ${options.language} files are unchanged.`); + + if (options.language === "javascript") { + if (!checkUnchanged(rebuildJavaScript)) { + // If we get a fail here then the PR needs attention + console.error("Failed: JavaScript files are not up to date."); + console.error("Run 'rm -rf lib && npm run build' to update."); + + await addDiffToSummary("Transpiled JS diff"); + + // Reset bundled files to allow other checks to test for changes + runCommand("git", ["checkout", "lib"]); + + return 1; + } + + console.info("Success: JavaScript files are up to date"); + } else if (options.language === "yaml") { + if (!checkUnchanged(formatYAML)) { + // If we get a fail here then the PR needs attention + console.error("Failed: YAML files are not correctly formatted."); + console.error("Run 'npm run format-yaml' to format them."); + + await addDiffToSummary("YAML formatting changes"); + + return 1; + } + + console.info("Success: YAML files are correctly formatted"); + } else { + console.error(`Unknown language: ${options.language}`); + return 1; + } + + return 0; +} + +process.exit(await main()); diff --git a/pr-checks/checks/all-platform-bundle.yml b/pr-checks/checks/all-platform-bundle.yml index d35620706f..24bd290159 100644 --- a/pr-checks/checks/all-platform-bundle.yml +++ b/pr-checks/checks/all-platform-bundle.yml @@ -2,7 +2,8 @@ name: "All-platform bundle" description: "Tests using an all-platform CodeQL Bundle" operatingSystems: - ubuntu - - macos + - os: macos + runner-image: macos-26-xlarge - windows versions: - nightly-latest diff --git a/pr-checks/checks/analysis-kinds.yml b/pr-checks/checks/analysis-kinds.yml index 5b2aaf4aad..ef7cb80e17 100644 --- a/pr-checks/checks/analysis-kinds.yml +++ b/pr-checks/checks/analysis-kinds.yml @@ -46,7 +46,7 @@ steps: post-processed-sarif-path: "${{ runner.temp }}/post-processed" - name: Upload SARIF files - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: | analysis-kinds-${{ matrix.os }}-${{ matrix.version }}-${{ matrix.analysis-kinds }} @@ -54,7 +54,7 @@ steps: retention-days: 7 - name: Upload post-processed SARIF - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: | post-processed-${{ matrix.os }}-${{ matrix.version }}-${{ matrix.analysis-kinds }} diff --git a/pr-checks/checks/analyze-ref-input.yml b/pr-checks/checks/analyze-ref-input.yml index 683d40df9f..16231cefe2 100644 --- a/pr-checks/checks/analyze-ref-input.yml +++ b/pr-checks/checks/analyze-ref-input.yml @@ -14,5 +14,5 @@ steps: run: ./build.sh - uses: ./../action/analyze with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" diff --git a/pr-checks/checks/bundle-from-toolcache.yml b/pr-checks/checks/bundle-from-toolcache.yml index 0e51e2e12b..947b273903 100644 --- a/pr-checks/checks/bundle-from-toolcache.yml +++ b/pr-checks/checks/bundle-from-toolcache.yml @@ -2,30 +2,20 @@ name: "Bundle: From toolcache" description: "The CodeQL bundle should be cached within the toolcache" versions: - toolcache +installNode: true steps: - - name: Install @actions/tool-cache - run: npm install @actions/tool-cache@3 - name: Check toolcache contains CodeQL continue-on-error: true - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 - with: - script: | - const toolcache = require('@actions/tool-cache'); - const allCodeqlVersions = toolcache.findAllVersions('CodeQL'); - if (allCodeqlVersions.length === 0) { - throw new Error(`CodeQL could not be found in the toolcache`); - } + run: | + cd ./../action + npx tsx ./pr-checks/toolcache.ts installed + - id: setup-codeql uses: ./../action/setup-codeql with: tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Check CodeQL is installed within the toolcache - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 - with: - script: | - const toolcache = require('@actions/tool-cache'); - const allCodeqlVersions = toolcache.findAllVersions('CodeQL'); - console.log(`Found CodeQL versions: ${allCodeqlVersions}`); - if (allCodeqlVersions.length === 0) { - throw new Error('CodeQL not found in toolcache'); - } + run: | + cd ./../action + npx tsx ./pr-checks/toolcache.ts installed diff --git a/pr-checks/checks/bundle-toolcache.yml b/pr-checks/checks/bundle-toolcache.yml index 83d1d7d0b5..3317a45f40 100644 --- a/pr-checks/checks/bundle-toolcache.yml +++ b/pr-checks/checks/bundle-toolcache.yml @@ -6,46 +6,31 @@ operatingSystems: - ubuntu - macos - windows +installNode: true steps: - name: Remove CodeQL from toolcache - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 - with: - script: | - const fs = require('fs'); - const path = require('path'); - const codeqlPath = path.join(process.env['RUNNER_TOOL_CACHE'], 'CodeQL'); - fs.rmdirSync(codeqlPath, { recursive: true }); - - name: Install @actions/tool-cache - run: npm install @actions/tool-cache@3 + run: | + cd ./../action + npx tsx ./pr-checks/toolcache.ts clear + - name: Check toolcache does not contain CodeQL - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 - with: - script: | - const toolcache = require('@actions/tool-cache'); - const allCodeqlVersions = toolcache.findAllVersions('CodeQL'); - if (allCodeqlVersions.length !== 0) { - throw new Error(`CodeQL should not be found in the toolcache, but found ${allCodeqlVersions}`); - } - console.log('No versions of CodeQL found in the toolcache'); + run: | + cd ./../action + npx tsx ./pr-checks/toolcache.ts absent + - id: init uses: ./../action/init with: - languages: javascript + # Request multiple languages so this check uses the combined bundle. + languages: javascript,python tools: ${{ steps.prepare-test.outputs.tools-url }} + - uses: ./../action/analyze with: output: ${{ runner.temp }}/results upload-database: false + - name: Check CodeQL is installed within the toolcache - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 - with: - script: | - const toolcache = require('@actions/tool-cache'); - const allCodeqlVersions = toolcache.findAllVersions('CodeQL'); - console.log(`Found CodeQL versions: ${allCodeqlVersions}`); - if (allCodeqlVersions.length === 0) { - throw new Error('CodeQL not found in toolcache'); - } - if (allCodeqlVersions.length > 1) { - throw new Error('Multiple CodeQL versions found in toolcache'); - } + run: | + cd ./../action + npx tsx ./pr-checks/toolcache.ts installed -n 1 diff --git a/pr-checks/checks/config-export.yml b/pr-checks/checks/config-export.yml index 93c6407355..205754151f 100644 --- a/pr-checks/checks/config-export.yml +++ b/pr-checks/checks/config-export.yml @@ -14,7 +14,7 @@ steps: output: "${{ runner.temp }}/results" upload-database: false - name: Upload SARIF - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: config-export-${{ matrix.os }}-${{ matrix.version }}.sarif.json path: "${{ runner.temp }}/results/javascript.sarif" diff --git a/pr-checks/checks/diagnostics-export.yml b/pr-checks/checks/diagnostics-export.yml index 61b9ae5efc..0548531b93 100644 --- a/pr-checks/checks/diagnostics-export.yml +++ b/pr-checks/checks/diagnostics-export.yml @@ -5,6 +5,7 @@ versions: - nightly-latest env: CODEQL_ACTION_EXPORT_DIAGNOSTICS: true +installNode: true steps: - uses: ./../action/init id: init @@ -27,58 +28,15 @@ steps: output: "${{ runner.temp }}/results" upload-database: false - name: Upload SARIF - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: diagnostics-export-${{ matrix.os }}-${{ matrix.version }}.sarif.json path: "${{ runner.temp }}/results/javascript.sarif" retention-days: 7 + - name: Check diagnostics appear in SARIF - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: SARIF_PATH: "${{ runner.temp }}/results/javascript.sarif" - with: - script: | - const fs = require('fs'); - - function checkStatusPageNotification(n) { - const expectedMessage = 'Plaintext message'; - if (n.message.text !== expectedMessage) { - core.setFailed(`Expected the status page diagnostic to have the message '${expectedMessage}', but found '${n.message.text}'.`); - } - if (n.locations.length !== 1) { - core.setFailed(`Expected the status page diagnostic to have exactly 1 location, but found ${n.locations.length}.`); - } - } - - const sarif = JSON.parse(fs.readFileSync(process.env['SARIF_PATH'], 'utf8')); - const run = sarif.runs[0]; - - const toolExecutionNotifications = run.invocations[0].toolExecutionNotifications; - const statusPageNotifications = toolExecutionNotifications.filter(n => - n.descriptor.id === 'lang/diagnostics/example' && n.properties?.visibility?.statusPage - ); - if (statusPageNotifications.length !== 1) { - core.setFailed( - 'Expected exactly one status page reporting descriptor for this diagnostic in the ' + - `'runs[].invocations[].toolExecutionNotifications[]' SARIF property, but found ` + - `${statusPageNotifications.length}. All notification reporting descriptors: ` + - `${JSON.stringify(toolExecutionNotifications)}.` - ); - } - checkStatusPageNotification(statusPageNotifications[0]); - - const notifications = run.tool.driver.notifications; - const diagnosticNotification = notifications.filter(n => - n.id === 'lang/diagnostics/example' && n.name === 'lang/diagnostics/example' && - n.fullDescription.text === 'Diagnostic name' - ); - if (diagnosticNotification.length !== 1) { - core.setFailed( - 'Expected exactly one notification for this diagnostic in the ' + - `'runs[].tool.driver.notifications[]' SARIF property, but found ` + - `${diagnosticNotification.length}. All notifications: ` + - `${JSON.stringify(notifications)}.` - ); - } - - core.info('Finished diagnostic export test'); + run: | + cd ../action + npx tsx ./pr-checks/check-diagnostics.ts diff --git a/pr-checks/checks/diagnostics-without-db.yml b/pr-checks/checks/diagnostics-without-db.yml new file mode 100644 index 0000000000..a7c47a3d73 --- /dev/null +++ b/pr-checks/checks/diagnostics-without-db.yml @@ -0,0 +1,72 @@ +name: "Diagnostic export without database" +description: "Tests that temporary diagnostics are correctly included in the failed SARIF." +versions: + # Overridden by the FF in the `init` step below. + - linked +installNode: true + +env: + # Allow the failed SARIF file to be generated. + CODEQL_ACTION_SKIP_GENERATE_FAILED_SARIF: false + # But don't actually upload it. + CODEQL_ACTION_SKIP_SARIF_UPLOAD: true + # Mark telemetry for this workflow so it can be treated separately. + CODEQL_ACTION_TESTING_ENVIRONMENT: codeql-action-pr-checks + +steps: + # We deliberately need to make this step fail before the database is initialised, but after + # some diagnostic has been produced. The simplest way to do that right now is to: + # + # - Produce a diagnostic before the db is initialised by forcing the use of a nightly release + # with the `CODEQL_ACTION_FORCE_NIGHTLY` feature flag. + # - Cause `init` to abort because we are attempting to analyse Swift on a non-macOS runner. + # + - name: Initialise failing analysis + id: init + uses: ./../action/init + continue-on-error: true + env: + CODEQL_ACTION_FORCE_NIGHTLY: true + with: + languages: swift + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Analyze + uses: ./analyze + # In a real workflow, this step wouldn't run. Since we used `continue-on-error` + # above, we manually disable it with an `if` condition. Having this step is required + # for the init post-action because it checks the workflow definition for e.g. the + # `category` input. Without this step, that part of the init post-action would fail. + if: false + with: + category: "/test-codeql-version:${{ matrix.version }}" + + - name: Check diagnostics appear on disk + env: + DIAGNOSTICS_DIR: "${{ runner.temp }}/codeql-action-temp-diagnostics/" + run: | + cd ../action + npx tsx ./pr-checks/diagnostics-without-db.ts +validationJobs: + diagnostics-without-db-validation: + checkout: true + installNode: true + steps: + - name: Download workflow artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: test-mode-sarif-* + path: sarif + + - name: List artifact contents + run: ls -laR ./sarif + + - name: Check diagnostics appear in SARIF + env: + SARIF_PATH: "./sarif/codeql-failed-run.sarif" + DIAGNOSTIC_ID: "codeql-action/forced-nightly-cli" + DIAGNOSTIC_NAME: "A nightly release of CodeQL was used" + EXPECTED_LOCATIONS: "0" + EXPECTED_MESSAGE: | + GitHub configured this analysis to use a nightly release of CodeQL to allow you to preview changes from an upcoming release. + run: npx tsx ./pr-checks/check-diagnostics.ts diff --git a/pr-checks/checks/export-file-baseline-information.yml b/pr-checks/checks/export-file-baseline-information.yml index c5d5d12dda..c83c3626e8 100644 --- a/pr-checks/checks/export-file-baseline-information.yml +++ b/pr-checks/checks/export-file-baseline-information.yml @@ -17,13 +17,18 @@ steps: with: languages: javascript tools: ${{ steps.prepare-test.outputs.tools-url }} + # To balance speed and coverage, analyze only JavaScript but use the combined bundle so + # baseline information is reported for every language in the multi-language repository. A + # custom configuration prevents per-language bundles from being used. + config: | + paths-ignore: [] - name: Build code run: ./build.sh - uses: ./../action/analyze with: output: "${{ runner.temp }}/results" - name: Upload SARIF - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: with-baseline-information-${{ matrix.os }}-${{ matrix.version }}.sarif.json path: "${{ runner.temp }}/results/javascript.sarif" diff --git a/pr-checks/checks/init-with-registries.yml b/pr-checks/checks/init-with-registries.yml index 69e2188de2..ffa5f4d128 100644 --- a/pr-checks/checks/init-with-registries.yml +++ b/pr-checks/checks/init-with-registries.yml @@ -23,9 +23,9 @@ steps: config-file: ./.github/codeql/codeql-config-registries.yml languages: javascript registries: | - - url: "https://ghcr.io/v2/" - packages: "*/*" - token: "${{ secrets.GITHUB_TOKEN }}" + - url: "https://ghcr.io/v2/" + packages: "*/*" + token: "${{ secrets.GITHUB_TOKEN }}" - name: Verify packages installed run: | diff --git a/pr-checks/checks/job-run-uuid-sarif.yml b/pr-checks/checks/job-run-uuid-sarif.yml index b86725d944..879da226c2 100644 --- a/pr-checks/checks/job-run-uuid-sarif.yml +++ b/pr-checks/checks/job-run-uuid-sarif.yml @@ -12,7 +12,7 @@ steps: with: output: "${{ runner.temp }}/results" - name: Upload SARIF - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: ${{ matrix.os }}-${{ matrix.version }}.sarif.json path: "${{ runner.temp }}/results/javascript.sarif" diff --git a/pr-checks/checks/linux-arm64.yml b/pr-checks/checks/linux-arm64.yml new file mode 100644 index 0000000000..29d3eea41e --- /dev/null +++ b/pr-checks/checks/linux-arm64.yml @@ -0,0 +1,35 @@ +name: "Linux Arm64" +description: "An end-to-end integration test running on a Linux Arm64 runner, checking that the native linux-arm64 CodeQL bundle is downloaded and can analyze interpreted and compiled code" +operatingSystems: + - os: ubuntu + runner-image: ubuntu-24.04-arm +# The native linux-arm64 CodeQL bundle is only available in recent CLI releases, so we restrict this +# check to `nightly-latest`, which is guaranteed to ship it. Older stable versions do not have an +# arm64 asset, and `prepare-test` would resolve an x64 bundle URL for them on this runner. +versions: + - nightly-latest +installGo: true +installDotNet: true +# The set of languages CodeQL supports on this platform, excluding Swift (macOS only). +env: + LANGUAGES: cpp,csharp,go,java,javascript,python,ruby +steps: + - uses: ./../action/init + with: + languages: ${{ env.LANGUAGES }} + tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Build code + run: ./build.sh + - uses: ./../action/analyze + with: + upload-database: false + - name: Assert databases exist + run: | + cd "$RUNNER_TEMP/codeql_databases" + for lang in ${LANGUAGES//,/ }; do + if [[ ! -d "$lang" ]]; then + echo "Did not find a database for $lang" + exit 1 + fi + echo "Found database for $lang" + done diff --git a/pr-checks/checks/multi-language-autodetect.yml b/pr-checks/checks/multi-language-autodetect.yml index b57e90ab4c..135fc36727 100644 --- a/pr-checks/checks/multi-language-autodetect.yml +++ b/pr-checks/checks/multi-language-autodetect.yml @@ -3,14 +3,13 @@ description: "An end-to-end integration test of a multi-language repository usin operatingSystems: - ubuntu - os: macos - runner-image: macos-latest-xlarge + runner-image: macos-26-xlarge # Older CodeQL CLI versions only support Swift up to 6.1, which requires Xcode 16. That is # not available on macOS 26, so run these versions on macOS 15 where we select Xcode 16 # below. See https://github.com/actions/runner-images/issues/14167. - os: macos runner-image: macos-15-xlarge codeql-versions: - - stable-v2.19.4 - stable-v2.20.7 - stable-v2.21.4 - stable-v2.22.4 @@ -19,13 +18,14 @@ env: installGo: true installDotNet: true steps: - - name: Install Python 3.13 for older CLI versions - # We need Python 3.13 for older CLI versions because they are not compatible with Python 3.14 or newer. + - name: Install Python 3.13.15 for older CLI versions + # Older CLI versions don't work with Python 3.13.16 or newer because their Python extractor + # imports `importlib._bootstrap._ERR_MSG`, which those Python versions no longer define. # See https://github.com/github/codeql-action/pull/3212 if: matrix.version != 'nightly-latest' && matrix.version != 'linked' - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: - python-version: "3.13" + python-version: "3.13.15" - name: Use Xcode 16 # Only the older CodeQL CLI versions need Xcode 16, and these run on macOS 15. diff --git a/pr-checks/checks/overlay-init-fallback.yml b/pr-checks/checks/overlay-init-fallback.yml index 26d8c85672..48b9f19b18 100644 --- a/pr-checks/checks/overlay-init-fallback.yml +++ b/pr-checks/checks/overlay-init-fallback.yml @@ -6,7 +6,7 @@ versions: steps: - uses: ./../action/init with: - languages: actions # Any language without overlay support will do + languages: actions # Any language without overlay support will do tools: ${{ steps.prepare-test.outputs.tools-url }} env: CODEQL_OVERLAY_DATABASE_MODE: overlay-base diff --git a/pr-checks/checks/per-language-bundle-validation.yml b/pr-checks/checks/per-language-bundle-validation.yml new file mode 100644 index 0000000000..b84c15494d --- /dev/null +++ b/pr-checks/checks/per-language-bundle-validation.yml @@ -0,0 +1,118 @@ +name: Per-language bundles +description: Validates extraction and analysis using each per-language CodeQL bundle. +matrix: + include: + - language: actions + os: ubuntu-26.04 + version: linked + # Actions also needs the JavaScript extractor. + expected-extractors: actions javascript + - language: cpp + os: ubuntu-26.04 + version: linked + build-mode: manual + build-command: gcc -o main main.c + - language: csharp + os: ubuntu-26.04 + version: linked + build-mode: none + - language: go + os: ubuntu-26.04 + version: linked + build-mode: autobuild + - language: java + os: ubuntu-26.04 + version: linked + build-mode: none + - language: javascript + os: ubuntu-26.04 + version: linked + - language: python + os: ubuntu-26.04 + version: linked + - language: ruby + os: ubuntu-26.04 + version: linked + - language: rust + os: ubuntu-26.04 + version: linked + - language: swift + os: macos-26-xlarge + version: linked + build-mode: autobuild +installNode: true +steps: + - name: Remove CodeQL from toolcache + run: | + cd ./../action + npx tsx ./pr-checks/toolcache.ts clear + - uses: ./../action/init + id: init + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix['build-mode'] }} + tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Check that the bundle contains only the expected extractors + env: + CODEQL_PATH: ${{ steps.init.outputs.codeql-path }} + LANGUAGE: ${{ matrix.language }} + EXPECTED_EXTRACTORS: ${{ matrix['expected-extractors'] || matrix.language }} + run: | + extractors="$("$CODEQL_PATH" resolve languages --format=json | jq -r 'keys[]')" + echo "Extractors in the bundle:" + echo "$extractors" + echo "Expected: $EXPECTED_EXTRACTORS" + + for expected in $EXPECTED_EXTRACTORS; do + if ! echo "$extractors" | grep -qx "$expected"; then + echo "::error::The ${LANGUAGE} bundle does not contain the ${expected} extractor." + exit 1 + fi + done + + # If the bundle contained extractors beyond those the language needs, then it would not + # have been trimmed, and this job would be silently validating the combined bundle. + for other in actions cpp csharp go java javascript python ruby rust swift; do + if echo "$EXPECTED_EXTRACTORS" | grep -qw "$other"; then + continue + fi + if echo "$extractors" | grep -qx "$other"; then + echo "::error::The ${LANGUAGE} bundle also contains the ${other} extractor, so it is not trimmed." + exit 1 + fi + done + - name: Check that the bundle was not added to the toolcache + env: + CODEQL_PATH: ${{ steps.init.outputs.codeql-path }} + run: | + # A bundle that is missing most of its extractors must never be left in the toolcache, + # where a later job analyzing a different language could pick it up. Per-language bundles + # must instead be extracted under the runner's temporary directory. + echo "CodeQL is at $CODEQL_PATH" + if [[ "$CODEQL_PATH" == "$RUNNER_TOOL_CACHE"/* ]]; then + echo "::error::The per-language bundle was added to the toolcache at $CODEQL_PATH." + exit 1 + fi + if [[ "$CODEQL_PATH" != "$RUNNER_TEMP"/* ]]; then + echo "::error::Expected the per-language bundle to be extracted under $RUNNER_TEMP, but found it at $CODEQL_PATH." + exit 1 + fi + - name: Build code + if: matrix['build-command'] + run: ${{ matrix['build-command'] }} + - uses: ./../action/analyze + id: analysis + with: + upload-database: false + - name: Check that a database was created for the language + env: + DB_LOCATIONS: ${{ steps.analysis.outputs.db-locations }} + LANGUAGE: ${{ matrix.language }} + run: | + database="$(echo "$DB_LOCATIONS" | jq -r --arg lang "$LANGUAGE" '.[$lang] // empty')" + if [ -z "$database" ] || [ ! -d "$database" ]; then + echo "::error::No CodeQL database was created for ${LANGUAGE}." + echo "Databases: $DB_LOCATIONS" + exit 1 + fi + echo "Created a ${LANGUAGE} database at ${database}." diff --git a/pr-checks/checks/rubocop-multi-language.yml b/pr-checks/checks/rubocop-multi-language.yml deleted file mode 100644 index 37c5d36e90..0000000000 --- a/pr-checks/checks/rubocop-multi-language.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: "RuboCop multi-language" -description: "Tests using RuboCop to analyze a multi-language repository and then using the CodeQL Action to upload the resulting SARIF" -# This check doesn't use CodeQL, so the `version` matrix variable is unused. -versions: - - default -steps: - - name: Set up Ruby - uses: ruby/setup-ruby@95ef2b042f9d7a56d8268cba8559e2842e2ad01b # v1.321.0 - with: - ruby-version: 2.6 - - name: Install Code Scanning integration - run: bundle add code-scanning-rubocop --version 0.3.0 --skip-install - - name: Install dependencies - run: bundle install - - name: RuboCop run - run: | - bash -c " - bundle exec rubocop --require code_scanning --format CodeScanning::SarifFormatter -o rubocop.sarif - [[ $? -ne 2 ]] - " - - uses: ./../action/upload-sarif - with: - sarif_file: rubocop.sarif diff --git a/pr-checks/checks/rust.yml b/pr-checks/checks/rust.yml index 8589ba80e5..e0b91ae9ce 100644 --- a/pr-checks/checks/rust.yml +++ b/pr-checks/checks/rust.yml @@ -1,8 +1,8 @@ name: "Rust analysis" description: "Tests creation of a Rust database" versions: - # experimental rust support introduced, requires action to set `CODEQL_ENABLE_EXPERIMENTAL_FEATURES` - - stable-v2.19.4 + # oldest CodeQL version supported by the Action, where Rust support is experimental and requires the Action to set `CODEQL_ENABLE_EXPERIMENTAL_FEATURES` + - stable-v2.20.7 # first public preview version - stable-v2.22.1 - linked diff --git a/pr-checks/checks/submit-sarif-failure.yml b/pr-checks/checks/submit-sarif-failure.yml index c33e1322f7..ea156ca931 100644 --- a/pr-checks/checks/submit-sarif-failure.yml +++ b/pr-checks/checks/submit-sarif-failure.yml @@ -35,7 +35,9 @@ steps: run: exit 1 - uses: ./analyze # In a real workflow, this step wouldn't run. Since we used `continue-on-error` - # above, we manually disable it with an `if` condition. + # above, we manually disable it with an `if` condition. Having this step is required + # for the init post-action because it checks the workflow definition for e.g. the + # `category` input. Without this step, that part of the init post-action would fail. if: false with: category: "/test-codeql-version:${{ matrix.version }}" diff --git a/pr-checks/checks/swift-autobuild.yml b/pr-checks/checks/swift-autobuild.yml index 393857cd2c..8087e1aeef 100644 --- a/pr-checks/checks/swift-autobuild.yml +++ b/pr-checks/checks/swift-autobuild.yml @@ -4,7 +4,7 @@ versions: - nightly-latest operatingSystems: - os: macos - runner-image: macos-latest-xlarge + runner-image: macos-26-xlarge steps: - uses: ./../action/init id: init diff --git a/pr-checks/checks/swift-custom-build.yml b/pr-checks/checks/swift-custom-build.yml index a2d04421b8..a10c0a6ed7 100644 --- a/pr-checks/checks/swift-custom-build.yml +++ b/pr-checks/checks/swift-custom-build.yml @@ -5,7 +5,8 @@ versions: - default - nightly-latest operatingSystems: - - macos + - os: macos + runner-image: macos-26-xlarge installGo: true installDotNet: true env: diff --git a/pr-checks/checks/unsupported-macos.yml b/pr-checks/checks/unsupported-macos.yml new file mode 100644 index 0000000000..f5388f1d68 --- /dev/null +++ b/pr-checks/checks/unsupported-macos.yml @@ -0,0 +1,67 @@ +name: "Unsupported macOS" +description: "Tests that unsupported macOS versions are detected and result in appropriate diagnostics." +versions: + - linked + - nightly-latest +installNode: true + +operatingSystems: + - os: macos + runner-image: xcode-27 + +env: + # Allow the failed SARIF file to be generated. + CODEQL_ACTION_SKIP_GENERATE_FAILED_SARIF: false + # But don't actually upload it. + CODEQL_ACTION_SKIP_SARIF_UPLOAD: true + # Mark telemetry for this workflow so it can be treated separately. + CODEQL_ACTION_TESTING_ENVIRONMENT: codeql-action-pr-checks + +steps: + - name: Check xcode_select_link + run: | + readlink /private/var/db/xcode_select_link + file -h /private/var/db/xcode_select_link + + - uses: ./../action/init + id: init + continue-on-error: true + env: + CODEQL_ACTION_CHECK_UNSUPPORTED_TRACED_ANALYSIS: true + CODEQL_ACTION_ABORT_UNSUPPORTED_TRACED_ANALYSIS: true + with: + languages: swift + tools: ${{ steps.prepare-test.outputs.tools-url }} + + - name: Analyze + # We could run `analyze` here from `./../analyze`, but `getAnalyzeActionName` in `workflow.ts` + # can't cope with that unless we introduce a different testing environment. Since this step + # would just fail on `xcode-27` anyway, we just skip it instead. + if: false + uses: ./analyze + with: + category: "/test-codeql-version:${{ matrix.version }}" + +validationJobs: + unsupported-macos-sarif-checks: + checkout: true + installNode: true + steps: + - name: Download workflow artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: test-mode-sarif-* + path: sarif + + - name: List artifact contents + run: ls -laR ./sarif + + - name: Check diagnostics appear in SARIF + env: + SARIF_PATH: "./sarif/" + DIAGNOSTIC_ID: "codeql-action/unsupported-traced-analysis-macos" + DIAGNOSTIC_NAME: "Traced analysis is not supported on this version of macOS" + EXPECTED_LOCATIONS: "0" + EXPECTED_MESSAGE: | + Traced analysis is not supported on macOS 27 or above. + run: npx tsx ./pr-checks/check-diagnostics.ts diff --git a/pr-checks/checks/upload-ref-sha-input.yml b/pr-checks/checks/upload-ref-sha-input.yml index 9700827151..7a737c7def 100644 --- a/pr-checks/checks/upload-ref-sha-input.yml +++ b/pr-checks/checks/upload-ref-sha-input.yml @@ -15,10 +15,10 @@ steps: # Generate some SARIF we can upload with the upload-sarif step - uses: ./../action/analyze with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" upload: never - uses: ./../action/upload-sarif with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" diff --git a/pr-checks/checks/upload-sarif.yml b/pr-checks/checks/upload-sarif.yml index 8056a5179c..205bdf0a29 100644 --- a/pr-checks/checks/upload-sarif.yml +++ b/pr-checks/checks/upload-sarif.yml @@ -19,8 +19,8 @@ steps: # Generate some SARIF we can upload with the upload-sarif step - uses: ./../action/analyze with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" upload: never output: ${{ runner.temp }}/results @@ -29,8 +29,8 @@ steps: uses: ./../action/upload-sarif id: upload-sarif with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" sarif_file: ${{ runner.temp }}/results category: | ${{ github.workflow }}:upload-sarif/analysis-kinds:${{ matrix.analysis-kinds }}/os:${{ matrix.os }}/version:${{ matrix.version }}/test:all-files/ @@ -46,8 +46,8 @@ steps: id: upload-single-sarif-code-scanning if: contains(matrix.analysis-kinds, 'code-scanning') with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" sarif_file: ${{ runner.temp }}/results/javascript.sarif category: | ${{ github.workflow }}:upload-sarif/analysis-kinds:${{ matrix.analysis-kinds }}/os:${{ matrix.os }}/version:${{ matrix.version }}/test:single-code-scanning/ @@ -59,8 +59,8 @@ steps: id: upload-single-sarif-code-quality if: contains(matrix.analysis-kinds, 'code-quality') with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" sarif_file: ${{ runner.temp }}/results/javascript.quality.sarif category: | ${{ github.workflow }}:upload-sarif/analysis-kinds:${{ matrix.analysis-kinds }}/os:${{ matrix.os }}/version:${{ matrix.version }}/test:single-code-quality/ @@ -76,8 +76,8 @@ steps: id: upload-single-non-sarif if: contains(matrix.analysis-kinds, 'code-scanning') with: - ref: 'refs/heads/main' - sha: '5e235361806c361d4d3f8859e3c897658025a9a2' + ref: "refs/heads/main" + sha: "5e235361806c361d4d3f8859e3c897658025a9a2" sarif_file: ${{ runner.temp }}/results/javascript.sarif.json category: | ${{ github.workflow }}:upload-sarif/analysis-kinds:${{ matrix.analysis-kinds }}/os:${{ matrix.os }}/version:${{ matrix.version }}/test:non-sarif/ diff --git a/pr-checks/command.ts b/pr-checks/command.ts new file mode 100644 index 0000000000..459265c0d6 --- /dev/null +++ b/pr-checks/command.ts @@ -0,0 +1,81 @@ +import { execFileSync, ExecFileSyncOptions } from "node:child_process"; + +import { DryRunOption, REPO_ROOT } from "./config"; + +/** Options for {@link runCommand}. */ +export interface RunCommandOptions extends DryRunOption { + /** Options for `execFileSync`. */ + execOptions?: ExecFileSyncOptions; +} + +/** + * Runs a command, streaming output to the console by default. + * + * @param command The name of the command to run. + * @param args The arguments for the command. + * @throws When the process exits with a non-zero exit code. + * @param options How to run the command. + */ +export function runCommand( + command: string, + args: string[], + options?: RunCommandOptions, +) { + if (!options?.dryRun) { + console.log(`Running \`${command} ${args.join(" ")}\`.`); + return execFileSync(command, args, { + stdio: "inherit", + cwd: REPO_ROOT, + ...options?.execOptions, + }); + } else { + console.info( + `[DRY RUN] Would have executed '${command} ${args.join(" ")}'`, + ); + return ""; + } +} + +/** Options for {@link runGit}. */ +export interface RunGitOptions extends DryRunOption { + /** When true, non-zero exit codes will not throw. */ + allowNonZeroExitCode?: boolean; +} + +/** + * Runs `git` with the given `args` and returns the stdout. + * + * @param args - Arguments to pass to `git`. + * @param options - Optional settings. + * @throws If `git` does not exit successfully, unless + * `options.allowNonZeroExitCode` is `true`. + * @returns The trimmed stdout output. + */ +export function runGit(args: string[], options?: RunGitOptions): string { + const execOptions: ExecFileSyncOptions = { + encoding: "utf8", + stdio: ["pipe", "pipe", "pipe"], + }; + + try { + const result = runCommand("git", args, { + dryRun: options?.dryRun, + execOptions, + }) as string; + return result.trimEnd(); + } catch (error: unknown) { + if (options?.allowNonZeroExitCode) { + // execFileSync throws an object with `stdout` when the process exits + // with a non-zero code. + const execError = error as { stdout?: Buffer | string }; + if (typeof execError.stdout === "string") { + return execError.stdout.trimEnd(); + } + if (Buffer.isBuffer(execError.stdout)) { + return execError.stdout.toString("utf8").trimEnd(); + } + return ""; + } + throw error; + } +} diff --git a/pr-checks/config.ts b/pr-checks/config.ts index 356fe665f9..a7228bb566 100644 --- a/pr-checks/config.ts +++ b/pr-checks/config.ts @@ -1,4 +1,9 @@ import path from "path"; +import { fileURLToPath } from "url"; + +// For backwards-compatibility. +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); /** The oldest supported major version of the CodeQL Action. */ export const OLDEST_SUPPORTED_MAJOR_VERSION = 3; @@ -18,11 +23,20 @@ export const PACKAGE_JSON = path.join(REPO_ROOT, "package.json"); /** The path of the changelog. */ export const CHANGELOG_FILE = path.join(REPO_ROOT, "CHANGELOG.md"); +/** The path to the unreleased change-notes directory. */ +export const CHANGENOTES_DIR = path.join(REPO_ROOT, "unreleased-change-notes"); + /** The path to the esbuild metadata file. */ export const BUNDLE_METADATA_FILE = path.join(REPO_ROOT, "meta.json"); /** The `src` directory. */ -const SOURCE_ROOT = path.join(REPO_ROOT, "src"); +export const SOURCE_ROOT = path.join(REPO_ROOT, "src"); + +/** The `lib` directory. */ +export const LIB_ROOT = path.join(REPO_ROOT, "lib"); + +/** The path to `defaults.json`. */ +export const DEFAULTS_FILE = path.join(SOURCE_ROOT, "defaults.json"); /** The path to the built-in languages file. */ export const BUILTIN_LANGUAGES_FILE = path.join( diff --git a/pr-checks/diagnostics-without-db.ts b/pr-checks/diagnostics-without-db.ts new file mode 100644 index 0000000000..b276260f9d --- /dev/null +++ b/pr-checks/diagnostics-without-db.ts @@ -0,0 +1,48 @@ +import * as fs from "fs"; +import * as path from "path"; + +import * as core from "@actions/core"; + +import type * as diagnostics from "../src/diagnostics"; + +const DIAGNOSTIC_ID = "codeql-action/forced-nightly-cli"; +const diagnosticDirectory = process.env["DIAGNOSTICS_DIR"]; + +if (diagnosticDirectory === undefined) { + throw new Error("DIAGNOSTICS_DIR is undefined."); +} + +const paths = fs + .readdirSync(diagnosticDirectory, { + recursive: true, + encoding: "utf-8", + }) + .filter((p) => p.endsWith(".json")); + +core.info(`Found ${paths.length} paths in '${diagnosticDirectory}'.`); +core.info(`Searching for a diagnostic with id '${DIAGNOSTIC_ID}'...`); + +let found = false; +for (const diagnosticPath of paths) { + if (path.extname(diagnosticPath) !== ".json") { + core.info(`Skipping ${diagnosticPath}.`); + continue; + } + core.info(`Found ${diagnosticPath}.`); + + const contents = JSON.parse( + fs.readFileSync(path.resolve(diagnosticDirectory, diagnosticPath), "utf-8"), + ) as diagnostics.DiagnosticMessage; + + if (contents.source.id === DIAGNOSTIC_ID) { + core.info( + `Found '${DIAGNOSTIC_ID}' in '${diagnosticPath}'. Skipping remaining files.`, + ); + found = true; + break; + } +} + +if (!found) { + throw new Error(`Didn't find '${DIAGNOSTIC_ID}' diagnostic.`); +} diff --git a/pr-checks/excluded.yml b/pr-checks/excluded.yml index 1a5262fc0b..bac0b4acee 100644 --- a/pr-checks/excluded.yml +++ b/pr-checks/excluded.yml @@ -5,6 +5,8 @@ contains: - "test-setup-python-scripts" - "update" - "Update" + # Matrix-ed job; the name starts with this + - "Create backport" is: - "Agent" - "check-expected-release-files" @@ -15,4 +17,10 @@ is: - "Label PR with size" - "Post repo size comment" - "Prepare" + - "Release info" - "Upload results" + - "Update release branch" + # These checks are known not to run on every PR (for example, some release + # PRs), so requiring them would block the PRs they don't run on. + - "github-advanced-security" + - "License compliance check" diff --git a/pr-checks/package.json b/pr-checks/package.json index 84ac183f72..3ad65382f5 100644 --- a/pr-checks/package.json +++ b/pr-checks/package.json @@ -1,17 +1,27 @@ { "private": true, - "description": "Dependencies for the sync.ts", + "description": "Dependencies for codeql-action scripts", + "type": "module", + "scripts": { + "typecheck": "tsc --noEmit", + "test": "npx tsx --test", + "checks": "npm run typecheck && npm run test" + }, "dependencies": { "@actions/core": "^2.0.3", "@actions/github": "^8.0.1", - "@octokit/core": "^7.0.7", - "@octokit/plugin-paginate-rest": ">=9.2.2", - "@octokit/plugin-rest-endpoint-methods": "^17.0.0", + "@actions/tool-cache": "^3.0.1", + "@octokit/core": "^7.0.8", + "@octokit/plugin-paginate-rest": ">=16.0.0", + "@octokit/plugin-rest-endpoint-methods": "^18.0.0", + "glob": "^14.0.3", + "lite-matter": "^0.1.2", + "mdast-util-from-markdown": "^2.1.0", "semver": "^7.8.5", - "yaml": "^2.9.0" + "yaml": "^2.9.1" }, "devDependencies": { - "@types/node": "^20.19.43", - "tsx": "^4.23.12" + "@types/node": "^24.19.0", + "tsx": "^4.23.15" } } diff --git a/pr-checks/prepare-changelog.ts b/pr-checks/prepare-changelog.ts index 0c89699fc8..7ddf185202 100755 --- a/pr-checks/prepare-changelog.ts +++ b/pr-checks/prepare-changelog.ts @@ -77,6 +77,6 @@ function main() { } // Only call `main` if this script was run directly. -if (require.main === module) { +if (import.meta.main) { process.exit(main()); } diff --git a/pr-checks/release-branches.ts b/pr-checks/release-branches.ts index d0b4702018..04ea087334 100755 --- a/pr-checks/release-branches.ts +++ b/pr-checks/release-branches.ts @@ -116,6 +116,6 @@ async function main() { } // Only call `main` if this script was run directly. -if (require.main === module) { +if (import.meta.main) { void main(); } diff --git a/pr-checks/rollback-changelog.ts b/pr-checks/rollback-changelog.ts index 15a37b1b7c..9a744dc9fc 100755 --- a/pr-checks/rollback-changelog.ts +++ b/pr-checks/rollback-changelog.ts @@ -79,6 +79,6 @@ function main() { } // Only call `main` if this script was run directly. -if (require.main === module) { +if (import.meta.main) { process.exit(main()); } diff --git a/pr-checks/sync-back.test.ts b/pr-checks/sync-back.test.ts index 52d4c98f3f..142487449f 100755 --- a/pr-checks/sync-back.test.ts +++ b/pr-checks/sync-back.test.ts @@ -56,9 +56,18 @@ jobs: const result = scanGeneratedWorkflows(workflowDir); - assert.equal(result["actions/checkout"], "v4"); - assert.equal(result["actions/setup-node"], "v5"); - assert.equal(result["actions/setup-go"], "v6"); + assert.deepEqual( + result.actionVersions["actions/checkout"], + new Set(["v4"]), + ); + assert.deepEqual( + result.actionVersions["actions/setup-node"], + new Set(["v5"]), + ); + assert.deepEqual( + result.actionVersions["actions/setup-go"], + new Set(["v6"]), + ); }); await it("scanning workflows with version comments", () => { @@ -78,12 +87,18 @@ jobs: const result = scanGeneratedWorkflows(workflowDir); - assert.equal(result["actions/checkout"], "v4"); - assert.equal( - result["ruby/setup-ruby"], - "44511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0", + assert.deepEqual( + result.actionVersions["actions/checkout"], + new Set(["v4"]), + ); + assert.deepEqual( + result.actionVersions["ruby/setup-ruby"], + new Set(["44511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0"]), + ); + assert.deepEqual( + result.actionVersions["actions/setup-python"], + new Set(["v6 # Latest Python"]), ); - assert.equal(result["actions/setup-python"], "v6 # Latest Python"); }); await it("ignores local actions", () => { @@ -103,9 +118,15 @@ jobs: const result = scanGeneratedWorkflows(workflowDir); - assert.equal(result["actions/checkout"], "v4"); - assert.equal("./.github/actions/local-action" in result, false); - assert.equal("./another-local-action" in result, false); + assert.deepEqual( + result.actionVersions["actions/checkout"], + new Set(["v4"]), + ); + assert.equal( + "./.github/actions/local-action" in result.actionVersions, + false, + ); + assert.equal("./another-local-action" in result.actionVersions, false); }); }); @@ -128,8 +149,8 @@ const steps = [ fs.writeFileSync(syncTsPath, syncTsContent); const actionVersions = { - "actions/setup-node": "v5", - "actions/setup-go": "v6", + "actions/setup-node": new Set(["v5"]), + "actions/setup-go": new Set(["v6"]), }; const result = updateSyncTs(syncTsPath, actionVersions); @@ -155,7 +176,7 @@ const steps = [ fs.writeFileSync(syncTsPath, syncTsContent); const actionVersions = { - "actions/setup-node": "v5 # Latest version", + "actions/setup-node": new Set(["v5 # Latest version"]), }; const result = updateSyncTs(syncTsPath, actionVersions); @@ -182,7 +203,7 @@ const steps = [ fs.writeFileSync(syncTsPath, syncTsContent); const actionVersions = { - "actions/setup-node": "v5", + "actions/setup-node": new Set(["v5"]), }; const result = updateSyncTs(syncTsPath, actionVersions); @@ -206,7 +227,9 @@ const steps = [ fs.writeFileSync(syncTsPath, syncTsContent); const actionVersions = { - "actions/setup-node": "48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0", + "actions/setup-node": new Set([ + "48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0", + ]), }; const result = updateSyncTs(syncTsPath, actionVersions); @@ -244,8 +267,9 @@ steps: "actions/checkout": "v4", "actions/setup-node": "v5 # Latest", }; + const byWorkflow = { ["test.yml"]: actionVersions }; - const result = updateTemplateFiles(checksDir, actionVersions); + const result = updateTemplateFiles(checksDir, byWorkflow); assert.equal(result.length, 1); assert.ok(result.includes(templatePath)); @@ -269,8 +293,9 @@ steps: const actionVersions = { "ruby/setup-ruby": "55511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0", }; + const byWorkflow = { ["test.yml"]: actionVersions }; - const result = updateTemplateFiles(checksDir, actionVersions); + const result = updateTemplateFiles(checksDir, byWorkflow); assert.equal(result.length, 1); const updatedContent = fs.readFileSync(templatePath, "utf8"); diff --git a/pr-checks/sync-back.ts b/pr-checks/sync-back.ts index bb442b2fe1..7028864672 100755 --- a/pr-checks/sync-back.ts +++ b/pr-checks/sync-back.ts @@ -21,21 +21,45 @@ import * as fs from "fs"; import { parseArgs } from "node:util"; import * as path from "path"; -const THIS_DIR = __dirname; -const CHECKS_DIR = path.join(THIS_DIR, "checks"); -const WORKFLOW_DIR = path.join(THIS_DIR, "..", ".github", "workflows"); -const SYNC_TS_PATH = path.join(THIS_DIR, "sync.ts"); +import { PR_CHECKS_DIR, REPO_ROOT } from "./config"; + +const CHECKS_DIR = path.join(PR_CHECKS_DIR, "checks"); +const WORKFLOW_DIR = path.join(REPO_ROOT, ".github", "workflows"); +const SYNC_TS_PATH = path.join(PR_CHECKS_DIR, "sync.ts"); + +/** Type alias for action names. */ +type ActionName = string; + +/** Type alias for action versions. May include a comment. */ +type ActionVersion = string; + +/** Mappings of {@link ActionName}s to {@link ActionVersion}s. */ +type ActionVersions = Record; + +/** Mappings of workflow names to {@link ActionVersions}. */ +type ActionVersionsByWorkflow = Record; + +/** The result of {@link scanGeneratedWorkflows}. */ +type ScanWorkflowResult = { + /** A mapping of {@link ActionName}s to all encountered {@link ActionVersion}s. */ + actionVersions: Record>; + + /** A mapping of workflow names to {@link ActionVersions}. */ + actionVersionsByWorkflow: ActionVersionsByWorkflow; +}; /** * Scan generated workflow files to extract the latest action versions. * * @param workflowDir - Path to .github/workflows directory - * @returns Map from action names to their latest versions (including comments) + * + * @returns A {@link ScanWorkflowResult} object containing information about the extracted action versions. */ export function scanGeneratedWorkflows( workflowDir: string, -): Record { - const actionVersions: Record = {}; +): ScanWorkflowResult { + const actionVersionsByWorkflow: ActionVersionsByWorkflow = {}; + const actionVersions: Record> = {}; const generatedFiles = fs .readdirSync(workflowDir) @@ -45,6 +69,10 @@ export function scanGeneratedWorkflows( for (const filePath of generatedFiles) { const content = fs.readFileSync(filePath, "utf8"); + // Get the basename of the workflow and drop the leading `__` from it. + const workflowName = path.basename(filePath).slice(2); + actionVersionsByWorkflow[workflowName] = {}; + // Find all action uses in the file, including potential comments // This pattern captures: action_name@version_with_possible_comment const pattern = /uses:\s+([^/\s]+\/[^@\s]+)@([^@\n]+)/g; @@ -56,13 +84,26 @@ export function scanGeneratedWorkflows( // Only track non-local actions (those with / but not starting with ./) if (!actionName.startsWith("./")) { - // Assume that version numbers are consistent (this should be the case on a Dependabot update PR) - actionVersions[actionName] = versionWithComment; + // Record the version of the action for this workflow. + actionVersionsByWorkflow[workflowName][actionName] = versionWithComment; + + // Record this version for the action so that we can write it to `sync.ts` if needed. + // Usually we'd expect there to be exactly one version per action across all workflows, + // but sometimes these can go out-of-sync if e.g. a workflow is added in a branch and a + // Dependabot PR is merged in the meantime that changes the version of an action that is + // used in the new workflow. Different versions of the same action across different + // workflows is not fundamentally a problem, but we may need to pick one for `sync.ts` + // so we warn there if we have multiple versions of an action. + if (actionVersions[actionName] === undefined) { + actionVersions[actionName] = new Set([versionWithComment]); + } else if (!actionVersions[actionName].has(versionWithComment)) { + actionVersions[actionName].add(versionWithComment); + } } } } - return actionVersions; + return { actionVersions, actionVersionsByWorkflow }; } /** @@ -78,7 +119,7 @@ export function scanGeneratedWorkflows( */ export function updateSyncTs( syncTsPath: string, - actionVersions: Record, + actionVersions: Record>, ): boolean { if (!fs.existsSync(syncTsPath)) { throw new Error(`Could not find ${syncTsPath}`); @@ -88,9 +129,18 @@ export function updateSyncTs( const originalContent = content; // Update hardcoded action versions - for (const [actionName, versionWithComment] of Object.entries( + for (const [actionName, versionsWithComments] of Object.entries( actionVersions, )) { + // We usually expect `versionsWithComments` to contain one version. If there are multiple, + // we arbitrarily pick one and warn about it. + const versionsWithCommentsArray = Array.from(versionsWithComments); + const versionWithComment = versionsWithCommentsArray[0]; + if (versionsWithComments.size > 1) { + console.warn( + `Inconsistent versions for ${actionName}. Arbitrarily picking '${versionWithComment}'. All found: ${versionsWithCommentsArray.join(", ")}`, + ); + } // Split the scanned value into the ref (e.g. a commit SHA) and the optional // trailing version comment (e.g. `v6.0.3`). const ref = versionWithComment.includes("#") @@ -137,12 +187,12 @@ export function updateSyncTs( * Update action versions in template files in pr-checks/checks/ * * @param checksDir - Path to pr-checks/checks directory - * @param actionVersions - Map of action names to versions (may include comments) + * @param actionVersionsByWorkflow - Map of workflows to maps of action names to versions (may include comments) * @returns List of files that were modified */ export function updateTemplateFiles( checksDir: string, - actionVersions: Record, + actionVersionsByWorkflow: ActionVersionsByWorkflow, ): string[] { const modifiedFiles: string[] = []; @@ -155,6 +205,16 @@ export function updateTemplateFiles( let content = fs.readFileSync(filePath, "utf8"); const originalContent = content; + const workflowName = path.basename(filePath); + const actionVersions = actionVersionsByWorkflow[workflowName]; + + if (actionVersions === undefined) { + console.info( + `Found no action versions for workflow template '${filePath}'.`, + ); + continue; + } + // Update action versions for (const [actionName, versionWithComment] of Object.entries( actionVersions, @@ -190,12 +250,15 @@ function main(): number { const verbose = values.verbose ?? false; console.info("Scanning generated workflows for latest action versions..."); - const actionVersions = scanGeneratedWorkflows(WORKFLOW_DIR); + const { actionVersions, actionVersionsByWorkflow } = + scanGeneratedWorkflows(WORKFLOW_DIR); if (verbose) { console.info("Found action versions:"); - for (const [action, version] of Object.entries(actionVersions)) { - console.info(` ${action}@${version}`); + for (const [action, versions] of Object.entries(actionVersions)) { + for (const version of versions) { + console.info(` ${action}@${version}`); + } } } @@ -214,7 +277,10 @@ function main(): number { } // Update template files - const templateModified = updateTemplateFiles(CHECKS_DIR, actionVersions); + const templateModified = updateTemplateFiles( + CHECKS_DIR, + actionVersionsByWorkflow, + ); modifiedFiles.push(...templateModified); if (modifiedFiles.length > 0) { @@ -232,6 +298,6 @@ function main(): number { } // Only call `main` if this script was run directly. -if (require.main === module) { +if (import.meta.main) { process.exit(main()); } diff --git a/pr-checks/sync-checks.ts b/pr-checks/sync-checks.ts index afebc5831e..435b3a29e8 100755 --- a/pr-checks/sync-checks.ts +++ b/pr-checks/sync-checks.ts @@ -342,6 +342,6 @@ async function main(): Promise { } // Only call `main` if this script was run directly. -if (require.main === module) { +if (import.meta.main) { void main(); } diff --git a/pr-checks/sync.sh b/pr-checks/sync.sh index c059594493..dd0e0b4680 100755 --- a/pr-checks/sync.sh +++ b/pr-checks/sync.sh @@ -4,12 +4,19 @@ set -e cd "$(dirname "$0")" # Run `npm ci` in CI or `npm install` otherwise. +# +# `pr-checks` is an npm workspace of the repository root and the two share a single hoisted +# `node_modules` directory. Running npm from this directory puts it in workspace mode, where it +# ignores the root project's own dependencies by default. `npm ci` would then rebuild the shared +# `node_modules` with only this workspace's dependencies, removing the root's ones, which breaks +# anything that imports from `src` (such as `sync.ts` itself). `--include-workspace-root` keeps the +# root project's dependencies in the installed tree. if [ "$GITHUB_ACTIONS" = "true" ]; then echo "In Actions, running 'npm ci' for 'sync.ts'..." - npm ci + npm ci --include-workspace-root else echo "Running 'npm install' for 'sync.ts'..." - npm install --no-audit --no-fund + npm install --no-audit --no-fund --include-workspace-root fi npx tsx sync.ts diff --git a/pr-checks/sync.ts b/pr-checks/sync.ts index 9dcce16fe5..ec8d5a57c3 100755 --- a/pr-checks/sync.ts +++ b/pr-checks/sync.ts @@ -7,6 +7,8 @@ import * as yaml from "yaml"; import { BuiltInLanguage } from "../src/languages"; +import { PR_CHECKS_DIR, REPO_ROOT } from "./config"; + /** * Returns a `uses` value for `action` pinned to a commit SHA, with the * human-readable version recorded in a trailing comment. @@ -41,6 +43,13 @@ type WorkflowInputs = Partial>; /** An operating system identifier. */ type OperatingSystemIdentifier = "ubuntu" | "macos" | "windows"; +/** Mapping from {@link OperatingSystemIdentifier} to default runner image labels. */ +const DEFAULT_RUNNER_IMAGES: Record = { + ubuntu: "ubuntu-26.04", + macos: "macos-26", + windows: "windows-2025", +}; + /** * Represents an operating system matrix entry for a generated PR check workflow. * @@ -79,6 +88,8 @@ interface Specification extends JobSpecification { useAllPlatformBundle?: string; /** Values for the `analysis-kinds` matrix dimension. */ analysisKinds?: string[]; + /** Overrides the generated job matrix using GitHub Actions matrix syntax. */ + matrix?: Record; /** Container image configuration for the job. */ container?: any; @@ -86,7 +97,7 @@ interface Specification extends JobSpecification { services?: any; /** Additional jobs to run after the main PR check job. */ - validationJobs?: Record; + validationJobs?: Record; /** If set, this check is part of a named collection that gets its own caller workflow. */ collection?: string; @@ -118,6 +129,10 @@ interface JobSpecification { installYq?: boolean; } +type ValidationJobSpecification = JobSpecification & { + checkout?: boolean; +}; + /** Describes language/framework-specific steps and inputs. */ interface LanguageSetup { specProperty: keyof JobSpecification; @@ -129,11 +144,17 @@ interface LanguageSetup { /** Describes partial mappings from built-in languages to their specific setup information. */ type LanguageSetups = Partial>; -// The default set of CodeQL Bundle versions to use for the PR checks. +/** A type representing version identifiers. */ +type Version = + | "default" + | "linked" + | "nightly-latest" + // This is an approximation, but sufficient validation for our needs here. + | `stable-v${number}.${number}.${number}`; + +/** The default set of CodeQL Bundle versions to use for the PR checks. */ const defaultTestVersions = [ // The oldest supported CodeQL version. If bumping, update `CODEQL_MINIMUM_VERSION` in `codeql.ts` - "stable-v2.19.4", - // The last CodeQL release in the 2.20 series. "stable-v2.20.7", // The last CodeQL release in the 2.21 series. "stable-v2.21.4", @@ -143,6 +164,8 @@ const defaultTestVersions = [ "stable-v2.23.9", // The last CodeQL release in the 2.24 series. "stable-v2.24.3", + // The last CodeQL release in the 2.25 series. + "stable-v2.25.6", // The default version of CodeQL for Dotcom, as determined by feature flags. "default", // The version of CodeQL shipped with the Action in `defaults.json`. During the release process @@ -151,7 +174,10 @@ const defaultTestVersions = [ "linked", // A nightly build directly from the our private repo, built in the last 24 hours. "nightly-latest", -]; +] as const satisfies Version[]; + +/** A type representing the default test versions. */ +type DefaultTestVersion = (typeof defaultTestVersions)[number]; /** The default versions we use for languages / frameworks, if not specified as a workflow input. */ const defaultLanguageVersions = { @@ -211,14 +237,20 @@ const languageSetups: LanguageSetups = { name: "Install Node.js", uses: pinnedUses( "actions/setup-node", - "820762786026740c76f36085b0efc47a31fe5020", - "v7.0.0", + "949feb2413d6458794dcd2491c4babbbce0c15c1", + "v7.1.0", ), with: { "node-version": defaultLanguageVersions.javascript, cache: "npm", }, }, + // Install a new enough version of `npm` to understand `min-release-age` + // that is still compatible with Node 20. + { + name: "Install newer npm", + run: "npm install -g npm@11.19.1", + }, { name: "Install dependencies", run: "npm ci", @@ -253,8 +285,8 @@ const languageSetups: LanguageSetups = { name: "Install Java", uses: pinnedUses( "actions/setup-java", - "b6effb05e454b25005698d916606bdc6ffcbf961", - "v5.7.0", + "b843ebf9b913146b38da2eaa7aeddf76074ae1ad", + "v6.1.0", ), with: { "java-version": `\${{ inputs.java-version || '${defaultLanguageVersions.java}' }}`, @@ -271,8 +303,8 @@ const languageSetups: LanguageSetups = { name: "Install Python", uses: pinnedUses( "actions/setup-python", - "5fda3b95a4ea91299a34e894583c3862153e4b97", - "v7.0.0", + "6d4fd22b20465ccc0f7354476588e8df7c9ca0e0", + "v7.1.0", ), with: { "python-version": `\${{ inputs.python-version || '${defaultLanguageVersions.python}' }}`, @@ -299,14 +331,15 @@ const languageSetups: LanguageSetups = { }, }; -// This is essentially an arbitrary version of `yq`, which happened to be the one that -// `choco` fetched when we moved away from using that here. -// See https://github.com/github/codeql-action/pull/3423 +/** + * This is essentially an arbitrary version of `yq`, which happened to be the one that + * `choco` fetched when we moved away from using that here. + * See https://github.com/github/codeql-action/pull/3423 + */ const YQ_VERSION = "v4.50.1"; -const THIS_DIR = __dirname; -const CHECKS_DIR = path.join(THIS_DIR, "checks"); -const OUTPUT_DIR = path.join(THIS_DIR, "..", ".github", "workflows"); +const CHECKS_DIR = path.join(PR_CHECKS_DIR, "checks"); +const OUTPUT_DIR = path.join(REPO_ROOT, ".github", "workflows"); /** * Loads and parses a YAML file. @@ -337,7 +370,7 @@ function writeYaml(filePath: string, workflow: any): void { }); const yamlStr = yaml.stringify(workflowDoc, { aliasDuplicateObjects: false, - singleQuote: true, + singleQuote: false, lineWidth: 0, }); fs.writeFileSync(filePath, stripTrailingWhitespace(header + yamlStr), "utf8"); @@ -388,12 +421,6 @@ function generateJobMatrix( ); } - const defaultRunnerImages = [ - "ubuntu-latest", - "macos-latest", - "windows-latest", - ]; - for (const operatingSystemConfig of operatingSystems) { const operatingSystem = typeof operatingSystemConfig === "string" @@ -423,16 +450,29 @@ function generateJobMatrix( const runnerImagesForOs = typeof operatingSystemConfig === "string" || operatingSystemConfig["runner-image"] === undefined - ? defaultRunnerImages.filter((image) => + ? Object.values(DEFAULT_RUNNER_IMAGES).filter((image) => image.startsWith(operatingSystem), ) : [operatingSystemConfig["runner-image"]]; for (const runnerImage of runnerImagesForOs) { - matrix.push({ - os: runnerImage, - version, - }); + // stable-v2.20.7 requires an older version of Java than the default on `ubuntu-latest`. + // We could install that older version on the newer runners, or use the older runner. + // We do the latter here. This can be removed once we stop supporting `v2.20.7`. + // Since this is typed as `DefaultTestVersion`, it will become an error once `stable-v2.20.7` + // is removed from `defaultTestVersions`. + const requiresOlderRunnerImage: DefaultTestVersion = "stable-v2.20.7"; + if ( + runnerImage === DEFAULT_RUNNER_IMAGES["ubuntu"] && + version === requiresOlderRunnerImage + ) { + matrix.push({ os: "ubuntu-24.04", version }); + } else { + matrix.push({ + os: runnerImage, + version, + }); + } } } } @@ -453,6 +493,20 @@ function generateJobMatrix( return matrix; } +/** + * Gets the `actions/checkout` step. + */ +function getCheckoutStep(): Step { + return { + name: "Check out repository", + uses: pinnedUses( + "actions/checkout", + "3d3c42e5aac5ba805825da76410c181273ba90b1", + "v7.0.1", + ), + }; +} + /** * Retrieves setup steps and additional input definitions based on specific languages or frameworks * that are requested by the `checkSpecification`. @@ -512,9 +566,6 @@ function generateJob( specDocument: yaml.Document, checkSpecification: Specification, ) { - const matrix: Array> = - generateJobMatrix(checkSpecification); - const useAllPlatformBundle = checkSpecification.useAllPlatformBundle ? checkSpecification.useAllPlatformBundle : "false"; @@ -525,14 +576,7 @@ function generateJob( // Construct the workflow steps needed for this check. const steps: Step[] = [ - { - name: "Check out repository", - uses: pinnedUses( - "actions/checkout", - "3d3c42e5aac5ba805825da76410c181273ba90b1", - "v7.0.1", - ), - }, + getCheckoutStep(), ...setupInfo.steps, { name: "Prepare test", @@ -551,24 +595,14 @@ function generateJob( // Extract the sequence of steps from the YAML document to persist as much formatting as possible. const specSteps = specDocument.get("steps") as yaml.YAMLSeq; - // A handful of workflow specifications use double quotes for values, while we generally use single quotes. - // This replaces double quotes with single quotes for consistency. - yaml.visit(specSteps, { - Scalar(_key, node) { - if (node.type === "QUOTE_DOUBLE") { - node.type = "QUOTE_SINGLE"; - } - }, - }); - // Add the generated steps in front of the ones from the specification. specSteps.items.unshift(...steps); const checkJob: Record = { strategy: { "fail-fast": false, - matrix: { - include: matrix, + matrix: checkSpecification.matrix ?? { + include: generateJobMatrix(checkSpecification), }, }, name: checkSpecification.name, @@ -603,13 +637,16 @@ function generateJob( /** Generates a validation job. */ function generateValidationJob( specDocument: yaml.Document, - jobSpecification: JobSpecification, + jobSpecification: ValidationJobSpecification, checkName: string, name: string, ) { // Determine which languages or frameworks have to be installed. const { inputs, steps } = getSetupSteps(jobSpecification); + // Construct a checkout step if requested. + const checkoutStep = jobSpecification.checkout ? [getCheckoutStep()] : []; + // Extract the sequence of steps from the YAML document to persist as much formatting as possible. const specSteps = specDocument.getIn([ "validationJobs", @@ -618,18 +655,20 @@ function generateValidationJob( ]) as yaml.YAMLSeq; // Add the generated steps in front of the ones from the specification. - specSteps.items.unshift(...steps); + specSteps.items.unshift(...checkoutStep, ...steps); + + const baseCondition = "github.triggering_actor != 'dependabot[bot]'"; const validationJob: Record = { name: jobSpecification.name, - if: "github.triggering_actor != 'dependabot[bot]'", + if: baseCondition, needs: [checkName], permissions: { contents: "read", "security-events": "read", }, "timeout-minutes": 5, - "runs-on": "ubuntu-slim", + "runs-on": DEFAULT_RUNNER_IMAGES["ubuntu"], steps: specSteps, }; @@ -753,7 +792,7 @@ function main(): void { } const cron = new yaml.Scalar("0 5 * * *"); - cron.type = yaml.Scalar.QUOTE_SINGLE; + cron.type = yaml.Scalar.QUOTE_DOUBLE; const workflow = { name: `PR Check - ${checkSpecification.name}`, diff --git a/pr-checks/toolcache.ts b/pr-checks/toolcache.ts new file mode 100755 index 0000000000..aa7d9afc19 --- /dev/null +++ b/pr-checks/toolcache.ts @@ -0,0 +1,94 @@ +#!/usr/bin/env npx tsx + +/** + * Provides utility commands for working with the Actions toolcache in PR checks. + */ + +import fs from "fs"; +import { parseArgs } from "node:util"; +import path from "path"; + +import * as core from "@actions/core"; +import * as toolcache from "@actions/tool-cache"; + +function removeCodeQLFromToolcache() { + const toolcachePath = process.env["RUNNER_TOOL_CACHE"]; + + if (toolcachePath === undefined) { + throw new Error("Expected RUNNER_TOOL_CACHE to be defined"); + } + + const codeqlPath = path.join(toolcachePath, "CodeQL"); + fs.rmSync(codeqlPath, { recursive: true }); + + core.info(`Removed '${codeqlPath}' from the toolcache.`); +} + +function findCodeQL() { + return toolcache.findAllVersions("CodeQL"); +} + +function checkNoCodeQLInToolcache() { + const allCodeqlVersions = findCodeQL(); + if (allCodeqlVersions.length !== 0) { + throw new Error( + `CodeQL should not be found in the toolcache, but found ${allCodeqlVersions}`, + ); + } + core.info("No versions of CodeQL found in the toolcache"); +} + +function hasCodeQLInToolcache(expectedNumber?: string) { + const expected = + expectedNumber !== undefined + ? Number.parseInt(expectedNumber, 10) + : undefined; + + const allCodeqlVersions = findCodeQL(); + if (allCodeqlVersions.length === 0) { + throw new Error("CodeQL not found in toolcache"); + } + + core.info(`Found CodeQL versions: ${allCodeqlVersions.join(", ")}`); + if (expected !== undefined && allCodeqlVersions.length !== expected) { + throw new Error( + `Expected ${expected} versions of CodeQL in the toolcache, but found ${allCodeqlVersions.length}`, + ); + } +} + +function main() { + const { positionals, values } = parseArgs({ + options: { + // The number of expected versions in the toolcache. + "expected-version-count": { type: "string", short: "n" }, + }, + allowPositionals: true, + }); + + if (positionals.length < 1) { + throw new Error("Command not specified."); + } + + const cmd = positionals[0]; + + switch (cmd.trim().toLowerCase()) { + case "clear": + removeCodeQLFromToolcache(); + return; + case "absent": + checkNoCodeQLInToolcache(); + return; + case "installed": + hasCodeQLInToolcache(values["expected-version-count"]); + return; + default: + throw new Error(`Unknown command '${cmd}'.`); + } +} + +try { + main(); +} catch (err) { + core.setFailed(err instanceof Error ? err.message : String(err)); +} diff --git a/pr-checks/tsconfig.json b/pr-checks/tsconfig.json index b010827cf5..f75a95289b 100644 --- a/pr-checks/tsconfig.json +++ b/pr-checks/tsconfig.json @@ -6,8 +6,15 @@ "module": "preserve", "rootDir": "..", "sourceMap": false, - "noEmit": true, + "noEmit": true }, - "include": ["./*.ts", "../src/**/*.ts"], - "exclude": ["node_modules"] + "include": ["./**/*.ts", "../src/**/*.ts"], + "exclude": [ + "node_modules", + "../src/testdata/**", + "../src/**/*.test.ts", + "../src/testing-utils.ts", + "../src/json/testing-util.ts", + "../src/feature-flags/testing-util.ts" + ] } diff --git a/pr-checks/update-ghes-versions.ts b/pr-checks/update-ghes-versions.ts index 055424dff1..03b53c5dee 100755 --- a/pr-checks/update-ghes-versions.ts +++ b/pr-checks/update-ghes-versions.ts @@ -238,6 +238,6 @@ function main() { } // Only call `main` if this script was run directly. -if (require.main === module) { +if (import.meta.main) { main(); } diff --git a/pr-checks/update-release-branch.ts b/pr-checks/update-release-branch.ts index 088da59281..ca76603a32 100755 --- a/pr-checks/update-release-branch.ts +++ b/pr-checks/update-release-branch.ts @@ -18,12 +18,14 @@ * [--dry-run] */ -import { execFileSync, type ExecFileSyncOptions } from "node:child_process"; +import { execFileSync } from "node:child_process"; import { parseArgs } from "node:util"; import { type ApiClient, getApiClient } from "./api-client"; import * as changelog from "./changelog"; -import { DryRunOption, REPO_ROOT } from "./config"; +import { transferChangenotesToChangelog } from "./changenotes"; +import { runCommand, runGit } from "./command"; +import { CHANGELOG_FILE, CHANGENOTES_DIR } from "./config"; import { getCurrentVersion, replaceVersionInPackageJson, @@ -65,84 +67,6 @@ export function getGitHubToken(): string { throw new Error("Missing GitHub token. Set GITHUB_TOKEN or GH_TOKEN."); } -/** Options for {@link runCommand}. */ -export interface RunCommandOptions extends DryRunOption { - /** Options for `execFileSync`. */ - execOptions?: ExecFileSyncOptions; -} - -/** - * Runs a command, streaming output to the console by default. - * - * @param command The name of the command to run. - * @param args The arguments for the command. - * @throws When the process exits with a non-zero exit code. - * @param options How to run the command. - */ -export function runCommand( - command: string, - args: string[], - options?: RunCommandOptions, -) { - if (!options?.dryRun) { - console.log(`Running \`${command} ${args.join(" ")}\`.`); - return execFileSync(command, args, { - stdio: "inherit", - cwd: REPO_ROOT, - ...options?.execOptions, - }); - } else { - console.info( - `[DRY RUN] Would have executed '${command} ${args.join(" ")}'`, - ); - return ""; - } -} - -/** Options for {@link runGit}. */ -export interface RunGitOptions extends DryRunOption { - /** When true, non-zero exit codes will not throw. */ - allowNonZeroExitCode?: boolean; -} - -/** - * Runs `git` with the given `args` and returns the stdout. - * - * @param args - Arguments to pass to `git`. - * @param options - Optional settings. - * @throws If `git` does not exit successfully, unless - * `options.allowNonZeroExitCode` is `true`. - * @returns The trimmed stdout output. - */ -export function runGit(args: string[], options?: RunGitOptions): string { - const execOptions: ExecFileSyncOptions = { - encoding: "utf8", - stdio: ["pipe", "pipe", "pipe"], - }; - - try { - const result = runCommand("git", args, { - dryRun: options?.dryRun, - execOptions, - }) as string; - return result.trimEnd(); - } catch (error: unknown) { - if (options?.allowNonZeroExitCode) { - // execFileSync throws an object with `stdout` when the process exits - // with a non-zero code. - const execError = error as { stdout?: Buffer | string }; - if (typeof execError.stdout === "string") { - return execError.stdout.trimEnd(); - } - if (Buffer.isBuffer(execError.stdout)) { - return execError.stdout.toString("utf8").trimEnd(); - } - return ""; - } - throw error; - } -} - /** Returns true if the given branch exists on the origin remote. */ export function branchExistsOnRemote(branchName: string): boolean { const result = runGit(["ls-remote", "--heads", ORIGIN, branchName]); @@ -693,11 +617,14 @@ export async function prepareNewBranch( console.log("Updating changelog"); changelog.withChangelog( - (contents) => changelog.setVersionAndDate(version, contents), + (contents) => { + const populatedContents = transferChangenotesToChangelog(contents); + return changelog.setVersionAndDate(version, populatedContents); + }, { ...options, initChangelog: true }, ); - runGit(["add", "CHANGELOG.md"], { + runGit(["add", CHANGELOG_FILE, CHANGENOTES_DIR], { dryRun: options.dryRun, }); runGit(["commit", "-m", `Update changelog for v${version}`], { @@ -835,6 +762,6 @@ async function main(): Promise { } // Only call `main` if this script was run directly. -if (require.main === module) { +if (import.meta.main) { void main(); } diff --git a/queries/default-setup-environment-variables.ql b/queries/default-setup-environment-variables.ql index 9f677dfb9b..3032cefe07 100644 --- a/queries/default-setup-environment-variables.ql +++ b/queries/default-setup-environment-variables.ql @@ -23,7 +23,8 @@ predicate isSafeForDefaultSetup(string envVar) { "GITHUB_BASE_REF", "GITHUB_EVENT_NAME", "GITHUB_JOB", "GITHUB_RUN_ATTEMPT", "GITHUB_RUN_ID", "GITHUB_SHA", "GITHUB_REPOSITORY", "GITHUB_SERVER_URL", "GITHUB_TOKEN", "GITHUB_WORKFLOW", "GITHUB_WORKSPACE", "GOFLAGS", "ImageVersion", "JAVA_TOOL_OPTIONS", "RUNNER_ARCH", - "RUNNER_ENVIRONMENT", "RUNNER_NAME", "RUNNER_OS", "RUNNER_TEMP", "RUNNER_TOOL_CACHE" + "RUNNER_ENVIRONMENT", "RUNNER_NAME", "RUNNER_OS", "RUNNER_TEMP", "RUNNER_TOOL_CACHE", + "NODE_ENV" ] } diff --git a/resolve-environment/action.yml b/resolve-environment/action.yml index b93efb20d5..5e03ecac4b 100644 --- a/resolve-environment/action.yml +++ b/resolve-environment/action.yml @@ -1,6 +1,6 @@ -name: 'CodeQL: Resolve Build Environment' -description: '[Experimental] Attempt to infer a build environment suitable for automatic builds' -author: 'GitHub' +name: "CodeQL: Resolve Build Environment" +description: "[Experimental] Attempt to infer a build environment suitable for automatic builds" +author: "GitHub" inputs: token: description: "GitHub token to use for authenticating with this instance of GitHub. The token must be the built-in GitHub Actions token, and the workflow must have the `security-events: write` permission. Most of the time it is advisable to avoid specifying this input so that the workflow falls back to using the default value." @@ -22,4 +22,4 @@ outputs: description: The inferred build environment configuration. runs: using: node24 - main: '../lib/resolve-environment-entry.js' + main: "../lib/resolve-environment-entry.js" diff --git a/setup-codeql/action.yml b/setup-codeql/action.yml index 8d13eeaff0..8d9c5a0883 100644 --- a/setup-codeql/action.yml +++ b/setup-codeql/action.yml @@ -1,6 +1,6 @@ -name: 'CodeQL: Setup' -description: 'Installs the CodeQL CLI' -author: 'GitHub' +name: "CodeQL: Setup" +description: "Installs the CodeQL CLI" +author: "GitHub" inputs: tools: description: >- @@ -21,22 +21,19 @@ inputs: required: false languages: description: >- - A comma-separated list of CodeQL languages that will be analyzed in subsequent - `github/codeql-action/init` and `github/codeql-action/analyze` invocations. If specified, the - Action may use this list to select a CodeQL CLI version that is best suited to analyzing those - languages, for example by preferring a version that has a cached overlay-base database for the - specified languages. This input is not remembered and must also be passed to - `github/codeql-action/init`. + A comma-separated list of CodeQL languages that the installed CodeQL CLI will be used to + analyze. If specified, the Action may use this list to select a CodeQL CLI version that is + best suited to analyzing those languages, for example by preferring a version that has a + cached overlay-base database for the specified languages. required: false analysis-kinds: description: >- - [Internal] A comma-separated list of analysis kinds that subsequent - `github/codeql-action/init` invocations will enable. If specified, the Action may use this - list to select a CodeQL CLI version that is best suited to those analysis kinds. This input is - not remembered and must also be passed to `github/codeql-action/init`. + [Internal] A comma-separated list of analysis kinds that the installed CodeQL CLI will be used + for. If specified, the Action may use this list to select a CodeQL CLI version that is best + suited to those analysis kinds. Available options are the same as for the `analysis-kinds` input on the `init` Action. - default: 'code-scanning' + default: "code-scanning" required: true token: description: GitHub token to use for authenticating with this instance of GitHub. @@ -55,4 +52,4 @@ outputs: description: The version of the CodeQL binary that was installed. runs: using: node24 - main: '../lib/setup-codeql-entry.js' + main: "../lib/setup-codeql-entry.js" diff --git a/src/action-common.test.ts b/src/action-common.test.ts index fc2e0a9aaa..449300a8d2 100644 --- a/src/action-common.test.ts +++ b/src/action-common.test.ts @@ -19,6 +19,24 @@ import { getErrorMessage } from "./util"; setupTests(test); +for (const [key, displayName] of Object.entries( + statusReport.ACTION_DISPLAY_NAMES, +)) { + test(`getDisplayActionName - '${displayName}' instead of '${key}'`, (t) => { + t.is(statusReport.getDisplayActionName(key as ActionName), displayName); + }); +} + +test("getDisplayActionName - returns action name", (t) => { + for (const actionName of Object.values(ActionName)) { + if (statusReport.ACTION_DISPLAY_NAMES[actionName]) { + continue; + } + + t.is(statusReport.getDisplayActionName(actionName), actionName); + } +}); + interface RunInActionsTestOpts { runFn?: () => Promise; expectedErrorMessage?: string; diff --git a/src/action-common.ts b/src/action-common.ts index 95323e7f2a..efb0bd97a0 100644 --- a/src/action-common.ts +++ b/src/action-common.ts @@ -1,3 +1,5 @@ +import * as os from "os"; + import * as core from "@actions/core"; import { ActionsEnv, getActionsEnv } from "./actions-util"; @@ -13,12 +15,20 @@ import { } from "./status-report"; import { getEnv, getErrorMessage, wrapError } from "./util"; +export type { Logger } from "./logging"; + /** Base state that is available to an Action on startup. */ export interface BaseState { /** The name of the Action. */ name: ActionName; /** When the Action was started. */ startedAt: Date; + /** The platform the Action is running on. */ + platform: NodeJS.Platform; + /** The architecture of the host. */ + arch: NodeJS.Architecture; + /** The version of the operating system. */ + osRelease: string; } /** Describes different state features that an Action may have. */ @@ -52,6 +62,29 @@ export interface FeatureState { /** Identifies a type of state an Action may have. */ export type StateFeature = keyof FeatureState; +/** + * The `Env` feature implies the availability of the `ReadOnlyEnv` feature. + * + * If `T` is `Env`, this returns `Env | ReadOnlyEnv`. + * Otherwise, it is the identity and returns T. + */ +type ImpliedFeatures = T extends "Env" + ? "Env" | "ReadOnlyEnv" + : T; + +/** + * Given an object type `Obj`, this tries to lookup a corresponding `StateFeature` + * to which the object type belongs in `FeatureState`. Resolves to `never` if there + * is no match. + */ +type FeatureNameFor = { + [K in StateFeature]: [Obj] extends [FeatureState[K]] + ? [FeatureState[K]] extends [Obj] + ? K + : never + : never; +}[StateFeature]; + /** Constructs the intersection of all state types identifies by `Fs`. */ export type FieldsOf = Fs extends [] ? Record @@ -62,8 +95,54 @@ export type FieldsOf = Fs extends [] ? FeatureState[Head] & FieldsOf : never; +/** + * Symbol used for a field in `ActionState` that carries the type array of state features. + * This is a Symbol so that it doesn't clash with any property names we might want to have. + */ +const stateFeatures = Symbol(); + /** Describes the state of an Action that has access to the state corresponding to `Fs`. */ -export type ActionState = FieldsOf; +export type ActionState = FieldsOf & { + /** + * When given a chance, TypeScript will simplify an `ActionState` type as much as possible, + * which results in a concrete object type that doesn't mention `Fs`. + * + * That causes problems for functions which accept `ActionState` values, but need to know the + * feature keys `Fs`. This property here explicitly captures `Fs` in the concrete object type + * that results from simplifying `ActionState`. + * + * This is a function rather than a field, because we want to be able to provide values of type + * `ActionState` to functions expecting `ActionState` where `As` is a subset of `Fs`. + * + * Since function types are contravariant in the types of their parameters, using a function + * type here allows that to happen. + * + * Because the field is optional, we don't have to explicitly provide a value + * for it anywhere while the type is still inferred. + * + * `Fs[number]` returns the union of all features in `Fs`. We wrap it in `ImpliedFeatures` + * so that `Env` is expanded into `Env | ReadOnlyEnv`, allowing functions that expect the + * `ReadOnlyEnv` feature to be provided with an `ActionState` that has the `Env` feature + * without requiring this to be made explicit. + */ + readonly [stateFeatures]?: (ts: ImpliedFeatures) => void; +}; + +/** Extends `state` with an `extra` feature. */ +export function extendActionState< + // In first position, so that it can be explicitly provided if `FeatureNameFor` + // should not work on `extra`. + F extends StateFeature, + Fs extends readonly StateFeature[], + E extends FeatureState[F], +>( + state: ActionState, + extra: E, +): ActionState<[...Fs, FeatureNameFor & F]> { + return { ...state, ...extra } as unknown as ActionState< + [...Fs, FeatureNameFor & F] + >; +} /** The type of an Action's main entry point. This is a function that is provided * with a basic `ActionState` object with features that are always available. @@ -98,6 +177,9 @@ export async function runInActions(action: Action) { const actionState = { name: action.name, startedAt, + platform: process.platform, + arch: process.arch, + osRelease: os.release(), logger, env, actions: actionsEnv, diff --git a/src/actions-util.test.ts b/src/actions-util.test.ts index 3940cf7551..1c10b06bfd 100644 --- a/src/actions-util.test.ts +++ b/src/actions-util.test.ts @@ -7,12 +7,12 @@ import { isAnalyzingPullRequest, isDefaultSetup, isDynamicWorkflow, + printDebugLogs, } from "./actions-util"; import { computeAutomationID } from "./api-client"; import { EnvVar } from "./environment"; -import { getRunnerLogger } from "./logging"; -import { setupTests } from "./testing-utils"; -import { initializeEnvironment } from "./util"; +import { getTestEnv, RecordingLogger, setupTests } from "./testing-utils"; +import { withTmpDir } from "./util"; setupTests(test); @@ -100,6 +100,21 @@ test("computeAutomationID()", async (t) => { ); }); +test("printDebugLogs - doesn't throw when config doesn't have needed properties", async (t) => { + const logger = new RecordingLogger(); + await t.notThrowsAsync(printDebugLogs(logger, {})); + await t.notThrowsAsync(printDebugLogs(logger, { languages: [] })); + await t.notThrowsAsync(printDebugLogs(logger, { dbLocation: "nowhere" })); +}); + +test("printDebugLogs - doesn't throw when language db doesn't exist", async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + await t.notThrowsAsync( + printDebugLogs(logger, { dbLocation: tmpDir, languages: ["javascript"] }), + ); + })); + test.serial("getPullRequestBranches() with pull request context", (t) => { withMockedContext( { @@ -212,8 +227,9 @@ test.serial( ); test.serial("initializeEnvironment", (t) => { - initializeEnvironment("1.2.3"); - t.deepEqual(process.env[EnvVar.VERSION], "1.2.3"); + const env = getTestEnv(); + env.initialise("1.2.3"); + t.deepEqual(env.getOptional(EnvVar.VERSION), "1.2.3"); }); test.serial("fixCodeQualityCategory", (t) => { @@ -222,7 +238,7 @@ test.serial("fixCodeQualityCategory", (t) => { GITHUB_EVENT_NAME: "dynamic", }, () => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); // Categories that should get adjusted. t.is(fixCodeQualityCategory(logger, "/language:c#"), "/language:csharp"); diff --git a/src/actions-util.ts b/src/actions-util.ts index dd5124620d..abd29a0522 100644 --- a/src/actions-util.ts +++ b/src/actions-util.ts @@ -6,14 +6,15 @@ import * as toolrunner from "@actions/exec/lib/toolrunner"; import * as github from "@actions/github"; import * as io from "@actions/io"; -import type { Config } from "./config-utils"; -import { Env, EnvVar, ActionsEnvVars } from "./environment"; +import { hasConfigKey, type Config } from "./config/action-config"; +import { Env, EnvVar, ActionsEnvVars, ReadOnlyEnv } from "./environment"; import { Logger } from "./logging"; import { doesDirectoryExist, getCodeQLDatabasePath, ConfigurationError, getEnv, + getErrorMessage, } from "./util"; /** @@ -29,7 +30,6 @@ declare const __CODEQL_ACTION_VERSION__: string; export interface ActionsEnv { getRequiredInput: (name: string) => string; getOptionalInput: (name: string) => string | undefined; - exportVariable: (name: string, value: string) => void; } /** @@ -39,7 +39,6 @@ export function getActionsEnv(): ActionsEnv { return { getRequiredInput, getOptionalInput, - exportVariable: core.exportVariable, }; } @@ -73,7 +72,7 @@ export const getOptionalInput = function (name: string): string | undefined { * directory that has been set in `CODEQL_ACTION_TEMP` by e.g. a previous step, or the * value of `RUNNER_TEMP` otherwise. */ -export function getTemporaryDirectory(env: Env = getEnv()): string { +export function getTemporaryDirectory(env: ReadOnlyEnv = getEnv()): string { return ( env.getOptional(EnvVar.TEMP) ?? env.getRequired(ActionsEnvVars.RUNNER_TEMP) ); @@ -94,7 +93,7 @@ export function getActionVersion(): string { * * This will be "dynamic" for default setup workflow runs. */ -export function getWorkflowEventName(env: Env = getEnv()) { +export function getWorkflowEventName(env: ReadOnlyEnv = getEnv()) { return env.getRequired(ActionsEnvVars.GITHUB_EVENT_NAME); } @@ -102,7 +101,7 @@ export function getWorkflowEventName(env: Env = getEnv()) { * Returns whether the current workflow is executing a local copy of the Action, e.g. we're running * a workflow on the codeql-action repo itself. */ -export function isRunningLocalAction(env: Env = getEnv()): boolean { +export function isRunningLocalAction(env: ReadOnlyEnv = getEnv()): boolean { const relativeScriptPath = getRelativeScriptPath(env); return ( relativeScriptPath.startsWith("..") || path.isAbsolute(relativeScriptPath) @@ -114,14 +113,14 @@ export function isRunningLocalAction(env: Env = getEnv()): boolean { * * This can be used to get the Action's name or tell if we're running a local Action. */ -function getRelativeScriptPath(env: Env): string { +function getRelativeScriptPath(env: ReadOnlyEnv): string { const runnerTemp = env.getRequired(ActionsEnvVars.RUNNER_TEMP); const actionsDirectory = path.join(path.dirname(runnerTemp), "_actions"); return path.relative(actionsDirectory, __filename); } /** Returns the contents of `GITHUB_EVENT_PATH` as a JSON object. */ -export function getWorkflowEvent(env: Env = getEnv()): any { +export function getWorkflowEvent(env: ReadOnlyEnv = getEnv()): any { const eventJsonFile = env.getRequired(ActionsEnvVars.GITHUB_EVENT_PATH); try { return JSON.parse(fs.readFileSync(eventJsonFile, "utf-8")); @@ -132,28 +131,38 @@ export function getWorkflowEvent(env: Env = getEnv()): any { } } -export async function printDebugLogs(config: Config) { +export async function printDebugLogs(logger: Logger, config: Partial) { + if ( + !hasConfigKey(config, "languages") || + !hasConfigKey(config, "dbLocation") + ) { + logger.debug( + `Not printing debug logs, because the configuration does not include the 'languages' or 'dbLocation' fields.`, + ); + return; + } + for (const language of config.languages) { const databaseDirectory = getCodeQLDatabasePath(config, language); const logsDirectory = path.join(databaseDirectory, "log"); if (!doesDirectoryExist(logsDirectory)) { - core.info(`Directory ${logsDirectory} does not exist.`); + logger.info(`Directory ${logsDirectory} does not exist.`); continue; // Skip this language database. } const walkLogFiles = (dir: string) => { const entries = fs.readdirSync(dir, { withFileTypes: true }); if (entries.length === 0) { - core.info(`No debug logs found at directory ${logsDirectory}.`); + logger.info(`No debug logs found at directory ${logsDirectory}.`); } for (const entry of entries) { if (entry.isFile()) { const absolutePath = path.resolve(dir, entry.name); - core.startGroup( + logger.startGroup( `CodeQL Debug Logs - ${language} - ${entry.name} from file at path ${absolutePath}`, ); - process.stdout.write(fs.readFileSync(absolutePath)); - core.endGroup(); + logger.info(fs.readFileSync(absolutePath, "utf-8")); + logger.endGroup(); } else if (entry.isDirectory()) { walkLogFiles(path.resolve(dir, entry.name)); } @@ -283,6 +292,19 @@ export function isSelfHostedRunner(env: Env = getEnv()) { return env.getOptional(ActionsEnvVars.RUNNER_ENVIRONMENT) === "self-hosted"; } +/** + * Whether the job is running on a runner that GitHub hosts, and whose toolcache is therefore thrown + * away once the job has finished. + * + * Unlike `looksLikeHostedRunner`, this is based on what the service reports for the job rather than + * on how the runner's filesystem happens to be laid out, so it does not match self-hosted runners + * that are configured to resemble hosted ones, such as those that mount a persistent volume at + * `/opt/hostedtoolcache`. + */ +export function isGitHubHostedRunner(env: ReadOnlyEnv = getEnv()) { + return env.getOptional(ActionsEnvVars.RUNNER_ENVIRONMENT) === "github-hosted"; +} + /** Determines whether the workflow trigger is `dynamic`. */ export function isDynamicWorkflow(env: Env = getEnv()): boolean { return getWorkflowEventName(env) === "dynamic"; @@ -339,9 +361,10 @@ const MAX_STDERR_BUFFER_SIZE = 20000; * Runs a CLI tool. * * @returns Standard output produced by the tool. - * @throws A `CommandInvocationError` if the tool exits with a non-zero status code. + * @throws A {@link CommandInvocationError} if the tool exits with a non-zero status code. */ export async function runTool( + env: ReadOnlyEnv, cmd: string, args: string[] = [], opts: { stdin?: string; noStreamStdout?: boolean } = {}, @@ -352,6 +375,7 @@ export async function runTool( process.stdout.write(`[command]${cmd} ${args.join(" ")}\n`); } const exitCode = await new toolrunner.ToolRunner(cmd, args, { + env: env.getDefined(), ignoreReturnCode: true, listeners: { stdout: (data: Buffer) => { @@ -399,14 +423,23 @@ export const persistInputs = function (env: Env = getEnv()) { /** * Restores all inputs to the action from the persisted state. */ -export const restoreInputs = function () { - const persistedInputs = core.getState(persistedInputsKey); - if (persistedInputs) { - for (const [name, value] of JSON.parse(persistedInputs)) { - process.env[name] = value; +export function restoreInputs(logger: Logger) { + try { + const persistedInputsValue = core.getState(persistedInputsKey); + if (persistedInputsValue) { + const persistedInputs = JSON.parse(persistedInputsValue); + + for (const [name, value] of persistedInputs) { + process.env[name] = value; + } } + } catch (err) { + logger.error(`Unable to restore inputs: ${getErrorMessage(err)}`); + throw new Error( + "Failed to restore inputs from the state set by this action's main execution.", + ); } -}; +} export interface PullRequestBranches { base: string; diff --git a/src/analyses.test.ts b/src/analyses.test.ts index 9d0a9eb3e0..b9d182618a 100644 --- a/src/analyses.test.ts +++ b/src/analyses.test.ts @@ -15,7 +15,6 @@ import { supportedAnalysisKinds, } from "./analyses"; import { EnvVar } from "./environment"; -import { getRunnerLogger } from "./logging"; import { createFeatures, RecordingLogger, @@ -65,7 +64,7 @@ test.serial( .withArgs("analysis-kinds") .returns("code-scanning,code-quality"); const result = await getAnalysisKinds( - getRunnerLogger(true), + new RecordingLogger(), features, true, ); @@ -139,7 +138,7 @@ test.serial( const optionalInputStub = sinon.stub(actionsUtil, "getOptionalInput"); optionalInputStub.withArgs("quality-queries").returns("code-quality"); const result = await getAnalysisKinds( - getRunnerLogger(true), + new RecordingLogger(), features, true, ); @@ -155,7 +154,7 @@ test.serial( const requiredInputStub = sinon.stub(actionsUtil, "getRequiredInput"); requiredInputStub.withArgs("analysis-kinds").returns("no-such-thing"); await t.throwsAsync( - getAnalysisKinds(getRunnerLogger(true), features, true), + getAnalysisKinds(new RecordingLogger(), features, true), ); }, ); @@ -181,7 +180,7 @@ for (let i = 0; i < analysisKinds.length; i++) { .withArgs("analysis-kinds") .returns([analysisKind, otherAnalysis].join(",")); const result = await getAnalysisKinds( - getRunnerLogger(true), + new RecordingLogger(), features, true, ); @@ -199,7 +198,7 @@ for (let i = 0; i < analysisKinds.length; i++) { .withArgs("analysis-kinds") .returns([analysisKind, otherAnalysis].join(",")); await t.throwsAsync( - getAnalysisKinds(getRunnerLogger(true), features, true), + getAnalysisKinds(new RecordingLogger(), features, true), { instanceOf: ConfigurationError, message: `${analysisKind} and ${otherAnalysis} cannot be enabled at the same time`, diff --git a/src/analyze-action-post.ts b/src/analyze-action-post.ts index 732b52af19..a8d6dc4331 100644 --- a/src/analyze-action-post.ts +++ b/src/analyze-action-post.ts @@ -9,7 +9,6 @@ import * as core from "@actions/core"; import * as actionsUtil from "./actions-util"; import { getGitHubVersion } from "./api-client"; -import { getCodeQL } from "./codeql"; import { getConfig } from "./config-utils"; import * as debugArtifacts from "./debug-artifacts"; import { @@ -25,8 +24,8 @@ export async function runWrapper() { // possible, and only use safe functions outside. try { - actionsUtil.restoreInputs(); const logger = getActionsLogger(); + actionsUtil.restoreInputs(logger); const gitHubVersion = await getGitHubVersion(); checkGitHubVersionInRange(gitHubVersion, logger); @@ -38,12 +37,9 @@ export async function runWrapper() { logger, ); if (config !== undefined) { - const codeql = await getCodeQL(logger, config.codeQLCmd); - const version = await codeql.getVersion(); await debugArtifacts.uploadCombinedSarifArtifacts( logger, config.gitHubVersion.type, - version.version, ); } } diff --git a/src/analyze-action.test.ts b/src/analyze-action.test.ts index 923908a641..ffba5a03dc 100644 --- a/src/analyze-action.test.ts +++ b/src/analyze-action.test.ts @@ -45,6 +45,7 @@ test.serial( requiredInputStub.withArgs("token").returns("fake-token"); requiredInputStub.withArgs("upload-database").returns("false"); requiredInputStub.withArgs("output").returns("out"); + requiredInputStub.withArgs("checkout_path").returns(""); const optionalInputStub = sinon.stub(actionsUtil, "getOptionalInput"); optionalInputStub.withArgs("expect-error").returns("false"); sinon.stub(api, "getGitHubVersion").resolves(gitHubVersion); @@ -104,6 +105,7 @@ test.serial( requiredInputStub.withArgs("token").returns("fake-token"); requiredInputStub.withArgs("upload-database").returns("false"); requiredInputStub.withArgs("output").returns("out"); + requiredInputStub.withArgs("checkout_path").returns(""); const optionalInputStub = sinon.stub(actionsUtil, "getOptionalInput"); optionalInputStub.withArgs("expect-error").returns("false"); sinon.stub(api, "getGitHubVersion").resolves(gitHubVersion); diff --git a/src/analyze-action.ts b/src/analyze-action.ts index c3c2e40e7f..3c038e62db 100644 --- a/src/analyze-action.ts +++ b/src/analyze-action.ts @@ -4,12 +4,18 @@ import { performance } from "perf_hooks"; import * as core from "@actions/core"; -import { Action, ActionState, runInActions } from "./action-common"; +import { + Action, + ActionState, + extendActionState, + runInActions, +} from "./action-common"; import * as actionsUtil from "./actions-util"; import * as analyses from "./analyses"; import { CodeQLAnalysisError, dbIsFinalized, + determineCheckoutPath, QueriesStatusReport, runFinalize, runQueries, @@ -44,9 +50,8 @@ import { StatusReportBase, } from "./status-report"; import { - cleanupTrapCaches, - TrapCacheCleanupStatusReport, uploadTrapCaches, + warnIfTrapCacheCleanupEnvVarIsSet, } from "./trap-caching"; import * as uploadLib from "./upload-lib"; import { UploadResult } from "./upload-lib"; @@ -54,13 +59,10 @@ import { postProcessAndUploadSarif } from "./upload-sarif"; import * as util from "./util"; interface AnalysisStatusReport - extends uploadLib.UploadStatusReport, - QueriesStatusReport {} + extends uploadLib.UploadStatusReport, QueriesStatusReport {} interface FinishStatusReport - extends StatusReportBase, - DatabaseCreationTimings, - AnalysisStatusReport { + extends StatusReportBase, DatabaseCreationTimings, AnalysisStatusReport { dependency_caching_upload_results?: DependencyCacheUploadStatusReport; database_upload_results: DatabaseUploadResult[]; } @@ -80,7 +82,6 @@ async function sendStatusReport( trapCacheUploadTime: number | undefined, dbCreationTimings: DatabaseCreationTimings | undefined, didUploadTrapCaches: boolean, - trapCacheCleanup: TrapCacheCleanupStatusReport | undefined, dependencyCacheResults: DependencyCacheUploadStatusReport | undefined, databaseUploadResults: DatabaseUploadResult[], logger: Logger, @@ -101,7 +102,6 @@ async function sendStatusReport( ...statusReportBase, ...(stats || {}), ...(dbCreationTimings || {}), - ...(trapCacheCleanup || {}), dependency_caching_upload_results: dependencyCacheResults, database_upload_results: databaseUploadResults, }; @@ -212,17 +212,17 @@ async function runAutobuildIfLegacyGoWorkflow(config: Config, logger: Logger) { await runAutobuild(config, BuiltInLanguage.go, logger); } -async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { +async function run(action: ActionState<["Base", "Logger", "Env", "Actions"]>) { // To capture errors appropriately, keep as much code within the try-catch as // possible, and only use safe functions outside. + const startedAt = action.startedAt; + const logger = action.logger; let uploadResults: - | Partial> - | undefined = undefined; + Partial> | undefined = + undefined; let runStats: QueriesStatusReport | undefined = undefined; let config: Config | undefined = undefined; - let trapCacheCleanupTelemetry: TrapCacheCleanupStatusReport | undefined = - undefined; let trapCacheUploadTime: number | undefined = undefined; let dbCreationTimings: DatabaseCreationTimings | undefined = undefined; let didUploadTrapCaches = false; @@ -230,7 +230,7 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { let databaseUploadResults: DatabaseUploadResult[] = []; try { - util.initializeEnvironment(actionsUtil.getActionVersion()); + action.env.initialise(actionsUtil.getActionVersion()); // Make inputs accessible in the `post` step, details at // https://github.com/github/codeql-action/issues/2553 @@ -263,17 +263,6 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { ); } - // Unset the CODEQL_PROXY_* environment variables when using older CodeQL - // CLIs, as they are not needed and can cause issues. - if ( - process.env.CODEQL_PROXY_HOST === "" && - !(await util.codeQlVersionAtLeast(codeql, "2.20.7")) - ) { - delete process.env.CODEQL_PROXY_HOST; - delete process.env.CODEQL_PROXY_PORT; - delete process.env.CODEQL_PROXY_CA_CERTIFICATE; - } - if (actionsUtil.getOptionalInput("cleanup-level")) { logger.info( "The 'cleanup-level' input is ignored since the CodeQL Action now automatically " + @@ -281,9 +270,11 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { ); } + warnIfTrapCacheCleanupEnvVarIsSet(action); + const apiDetails = getApiDetails(); const outputDir = actionsUtil.getRequiredInput("output"); - core.exportVariable(EnvVar.SARIF_RESULTS_OUTPUT_DIR, outputDir); + action.env.export(EnvVar.SARIF_RESULTS_OUTPUT_DIR, outputDir); const threads = util.getThreadsFlag( actionsUtil.getOptionalInput("threads") || process.env["CODEQL_THREADS"], logger, @@ -307,8 +298,13 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { logger, ); + const checkoutPath = await determineCheckoutPath(action, config); + // Setup diff informed analysis if needed (based on whether init created the file) - const diffRangePackDir = await setupDiffInformedQueryRun(logger); + const diffRangePackDir = await setupDiffInformedQueryRun( + logger, + checkoutPath, + ); await warnIfGoInstalledAfterInit(config, logger); await runAutobuildIfLegacyGoWorkflow(config, logger); @@ -354,12 +350,12 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { actionsUtil.getOptionalInput("upload"), ); if (runStats) { - const checkoutPath = actionsUtil.getRequiredInput("checkout_path"); const category = actionsUtil.getOptionalInput("category"); uploadResults = await postProcessAndUploadSarif( logger, features, + config, uploadKind, checkoutPath, outputDir, @@ -388,18 +384,25 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { // Possibly upload the overlay-base database to actions cache. // Note: Take care with the ordering of this call since databases may be cleaned up // at the `overlay` level. - await cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger); + await cleanupAndUploadOverlayBaseDatabaseToCache( + codeql, + config, + logger, + checkoutPath, + ); + + const actionWithFeatures = extendActionState(action, { features }); // Possibly upload the database bundles for remote queries. // Note: Take care with the ordering of this call since databases may be cleaned up // at the `overlay` or `clear` level. databaseUploadResults = await cleanupAndUploadDatabases( + actionWithFeatures, repositoryNwo, codeql, config, apiDetails, - features, - logger, + checkoutPath, ); // Possibly upload the TRAP caches for later re-use @@ -407,13 +410,6 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { didUploadTrapCaches = await uploadTrapCaches(codeql, config, logger); trapCacheUploadTime = performance.now() - trapCacheUploadStartTime; - // Clean up TRAP caches - trapCacheCleanupTelemetry = await cleanupTrapCaches( - config, - features, - logger, - ); - // Store dependency cache(s) if dependency caching is enabled. if (shouldStoreCache(config.dependencyCachingEnabled)) { dependencyCacheResults = await uploadDependencyCaches( @@ -425,8 +421,10 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { } // We don't upload results in test mode, so don't wait for processing - if (util.isInTestMode()) { - logger.debug("In test mode. Waiting for processing is disabled."); + if (util.shouldSkipSarifUpload()) { + logger.debug( + "SARIF upload is disabled and nothing was uploaded, so we do not need to wait for processing to finish.", + ); } else if ( uploadResults?.[analyses.AnalysisKind.CodeScanning] !== undefined && actionsUtil.getRequiredInput("wait-for-processing") === "true" @@ -443,7 +441,7 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { `expect-error input was set to true but no error was thrown.`, ); } - core.exportVariable(EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY, "true"); + action.env.export(EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY, "true"); } catch (unwrappedError) { const error = util.wrapError(unwrappedError); if ( @@ -463,7 +461,6 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, - trapCacheCleanupTelemetry, dependencyCacheResults, databaseUploadResults, logger, @@ -486,7 +483,6 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, - trapCacheCleanupTelemetry, dependencyCacheResults, databaseUploadResults, logger, @@ -500,7 +496,6 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, - trapCacheCleanupTelemetry, dependencyCacheResults, databaseUploadResults, logger, @@ -514,7 +509,6 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, - trapCacheCleanupTelemetry, dependencyCacheResults, databaseUploadResults, logger, diff --git a/src/analyze.test.ts b/src/analyze.test.ts index 7523d239bf..c9f0608811 100644 --- a/src/analyze.test.ts +++ b/src/analyze.test.ts @@ -7,26 +7,114 @@ import * as sinon from "sinon"; import { CodeQuality, CodeScanning, RiskAssessment } from "./analyses"; import { runQueries, - defaultSuites, resolveQuerySuiteAlias, addSarifExtension, diffRangeExtensionPackContents, + determineCheckoutPath, } from "./analyze"; import { createStubCodeQL } from "./codeql"; +import { defaultSuites } from "./config/db-config"; import { Feature } from "./feature-flags"; +import * as gitUtils from "./git-utils"; import { BuiltInLanguage } from "./languages"; -import { getRunnerLogger } from "./logging"; import { setupTests, setupActionsVars, createFeatures, createTestConfig, + RecordingLogger, + callee, } from "./testing-utils"; import * as uploadLib from "./upload-lib"; import * as util from "./util"; setupTests(test); +test.serial( + "determineCheckoutPath - logs when checkout_path is not in a work tree", + async (t) => { + const expectedPath = path.resolve("/checkout/path"); + const target = callee(determineCheckoutPath) + .withActions((actions) => { + sinon + .stub(actions, "getRequiredInput") + .withArgs("checkout_path") + .returns(expectedPath); + }) + .withArgs(createTestConfig({})); + sinon.stub(gitUtils, "getGitRoot").resolves(undefined); + + await target + .logs(t, "is not in the work tree of a git repository") + .passes(t.is, expectedPath); + }, +); + +test.serial( + "determineCheckoutPath - logs when checkout_path is not a repo root", + async (t) => { + const expectedPath = path.resolve("/checkout/path"); + const target = callee(determineCheckoutPath) + .withActions((actions) => { + sinon + .stub(actions, "getRequiredInput") + .withArgs("checkout_path") + .returns(expectedPath); + }) + .withArgs(createTestConfig({})); + sinon.stub(gitUtils, "getGitRoot").resolves("/checkout"); + + await target + .logs(t, "is not the root of the repository") + .passes(t.is, expectedPath); + }, +); + +test.serial( + "determineCheckoutPath - logs when checkout_path is not the same as repo root in config", + async (t) => { + const expectedPath = path.resolve("/checkout/path"); + const target = callee(determineCheckoutPath) + .withActions((actions) => { + sinon + .stub(actions, "getRequiredInput") + .withArgs("checkout_path") + .returns(expectedPath); + }) + .withArgs(createTestConfig({ repositoryRoot: "/some/other/path" })); + sinon.stub(gitUtils, "getGitRoot").resolves(expectedPath); + + await target + .logs(t, "does not match that found by the 'codeql-action/init' step") + .passes(t.is, expectedPath); + }, +); + +test.serial( + "determineCheckoutPath - doesn't log any of the messages when all is as expected", + async (t) => { + const expectedPath = path.resolve("/checkout/path"); + const target = callee(determineCheckoutPath) + .withActions((actions) => { + sinon + .stub(actions, "getRequiredInput") + .withArgs("checkout_path") + .returns(expectedPath); + }) + .withArgs(createTestConfig({ repositoryRoot: expectedPath })); + sinon.stub(gitUtils, "getGitRoot").resolves(expectedPath); + + await target + .notLogs( + t, + "is not in the work tree of a git repository", + "is not the root of the repository", + "does not match that found by the 'codeql-action/init' step", + ) + .passes(t.is, expectedPath); + }, +); + /** * Checks the status report produced by the analyze Action. * @@ -107,7 +195,7 @@ test.serial("status report fields", async (t) => { undefined, codeql, config, - getRunnerLogger(true), + new RecordingLogger(), createFeatures([Feature.QaTelemetryEnabled]), ); t.deepEqual(Object.keys(statusReport).sort(), [ diff --git a/src/analyze.ts b/src/analyze.ts index 411477b597..692d2ef1db 100644 --- a/src/analyze.ts +++ b/src/analyze.ts @@ -5,10 +5,13 @@ import { performance } from "perf_hooks"; import * as io from "@actions/io"; import * as yaml from "js-yaml"; -import { getTemporaryDirectory, getRequiredInput } from "./actions-util"; +import type { ActionState } from "./action-common"; +import { getTemporaryDirectory } from "./actions-util"; import * as analyses from "./analyses"; import { setupCppAutobuild } from "./autobuild"; import { type CodeQL } from "./codeql"; +import type { ActionConfig } from "./config/action-config"; +import { defaultSuites } from "./config/db-config"; import * as configUtils from "./config-utils"; import { getCsharpTempDependencyDir, @@ -21,6 +24,7 @@ import { } from "./diff-informed-analysis-utils"; import { EnvVar } from "./environment"; import { FeatureEnablement, Feature } from "./feature-flags"; +import { getGitRoot } from "./git-utils"; import { BuiltInLanguage, Language } from "./languages"; import { Logger, withGroupAsync } from "./logging"; import { OverlayDatabaseMode } from "./overlay/overlay-database-mode"; @@ -50,7 +54,9 @@ type RunQueriesDurationStatusReport = { * The "builtin" designation is now outdated with the move to CLI config parsing: this is the time * taken to run _all_ the queries. */ - [L in BuiltInLanguageKey as `analyze_builtin_queries_${L}_duration_ms`]?: number; + [ + L in BuiltInLanguageKey as `analyze_builtin_queries_${L}_duration_ms` + ]?: number; }; type InterpretResultsDurationStatusReport = { @@ -59,8 +65,7 @@ type InterpretResultsDurationStatusReport = { }; export interface QueriesStatusReport - extends RunQueriesDurationStatusReport, - InterpretResultsDurationStatusReport { + extends RunQueriesDurationStatusReport, InterpretResultsDurationStatusReport { /** * Whether the analysis is diff-informed (in the sense that the action generates a diff-range data * extension for the analysis, regardless of whether the data extension is actually used by queries). @@ -85,6 +90,58 @@ export interface QueriesStatusReport event_reports?: EventReport[]; } +/** + * Determines the path at which the repository being analysed is checked out at. + * Returns the value of the required `checkout_path` input and validates that it + * refers to the root of a repository. + * + * @param action The action state. + * @param config The CodeQL Action configuration state. + */ +export async function determineCheckoutPath( + action: ActionState<["Logger", "Actions"]>, + config: configUtils.Config, +) { + const checkoutPathInput = action.actions.getRequiredInput("checkout_path"); + + // Try to obtain the root path of the repository and validate that it matches the input. + const absCheckoutPathInput = path.resolve(checkoutPathInput); + const repositoryRoot = await getGitRoot(absCheckoutPathInput); + + if (repositoryRoot === undefined) { + action.logger.warning( + [ + `The directory at '${absCheckoutPathInput}' is not in the work tree of a git repository.`, + "If the repository being analyzed is checked out elsewhere,", + "you must explicitly set the 'checkout_path' input for the 'codeql-action/analyze' step to", + "the checkout path.", + ].join(" "), + ); + } else if (repositoryRoot !== absCheckoutPathInput) { + action.logger.warning( + [ + `The directory at '${absCheckoutPathInput}' is not the root of the repository ('${repositoryRoot}').`, + "Set the 'checkout_path' input for the 'codeql-action/analyze' step to the root path of the checkout.", + ].join(" "), + ); + } else if ( + config.repositoryRoot !== undefined && + repositoryRoot !== config.repositoryRoot + ) { + // The repository root that was persisted by the `init` step doesn't match the one we have found here. + action.logger.warning( + [ + `The repository path at '${repositoryRoot}' does not match that found by the 'codeql-action/init' step: '${config.repositoryRoot}'.`, + "Ensure that the 'checkout_path' input for the 'codeql-action/analyze' step is set to the path of the same repository that", + "the 'codeql-action/init' step determined. This is either the GitHub Actions workspace or the repository root corresponding to", + "the 'source-root' input if that was provided.", + ].join(" "), + ); + } + + return absCheckoutPathInput; +} + async function setupPythonExtractor(logger: Logger) { const codeqlPython = process.env["CODEQL_PYTHON"]; if (codeqlPython === undefined || codeqlPython.length === 0) { @@ -123,7 +180,7 @@ export async function runExtraction( language === BuiltInLanguage.cpp && config.buildMode === BuildMode.Autobuild ) { - await setupCppAutobuild(codeql, logger); + await setupCppAutobuild(logger); } // The Java and C# `build-mode: none` extractors place dependencies in the @@ -170,7 +227,7 @@ async function shouldExtractLanguage( } export function dbIsFinalized( - config: configUtils.Config, + config: ActionConfig<"dbLocation">, language: Language, logger: Logger, ) { @@ -233,6 +290,7 @@ async function finalizeDatabaseCreation( */ export async function setupDiffInformedQueryRun( logger: Logger, + checkoutPath: string, ): Promise { return await withGroupAsync( "Generating diff range extension pack", @@ -245,7 +303,6 @@ export async function setupDiffInformedQueryRun( return undefined; } - const checkoutPath = getRequiredInput("checkout_path"); const packDir = writeDiffRangeDataExtensionPack( logger, diffRanges, @@ -263,8 +320,7 @@ export function diffRangeExtensionPackContents( ranges: DiffThunkRange[], checkoutPath: string, ): string { - const header = ` -extensions: + const header = `extensions: - addsTo: pack: codeql/util extensible: restrictAlertsTo @@ -285,7 +341,7 @@ extensions: // characters are escaped, and that the path is always rendered as a // quoted string on a single line. return ( - ` - [${yaml.dump(filename, { forceQuotes: true, quoteStyle: "single" }).trim()}, ` + + ` - [${yaml.dump(filename, { forceQuotes: true, quoteStyle: "double" }).trim()}, ` + `${range.startLine}, ${range.endLine}]\n` ); }) @@ -357,15 +413,6 @@ dataExtensions: return diffRangeDir; } -// A set of default query suite names that are understood by the CLI. -export const defaultSuites: Set = new Set([ - "security-experimental", - "security-extended", - "security-and-quality", - "code-quality", - "code-scanning", -]); - /** * If `maybeSuite` is the name of a default query suite, it is resolved into the corresponding * query suite name for the given `language`. Otherwise, `maybeSuite` is returned as is. diff --git a/src/api-client.test.ts b/src/api-client.test.ts index ae8c6269b1..34ebd52e9d 100644 --- a/src/api-client.test.ts +++ b/src/api-client.test.ts @@ -7,14 +7,21 @@ import { ProxyAgent } from "undici"; import * as actionsUtil from "./actions-util"; import * as api from "./api-client"; import { DO_NOT_RETRY_STATUSES } from "./api-client"; -import { ActionsEnvVars, RegistryProxyVars } from "./environment"; -import { callee, getTestEnv, setupTests } from "./testing-utils"; +import { ActionsEnvVars, RegistryProxyVars, getEnv } from "./environment"; +import { GITHUB_DOTCOM_API_URL, GITHUB_DOTCOM_URL } from "./github"; +import { + callee, + getTestEnv, + RecordingLogger, + SAMPLE_DOTCOM_API_DETAILS, + setupTests, +} from "./testing-utils"; import * as util from "./util"; setupTests(test); test.beforeEach(() => { - util.initializeEnvironment(actionsUtil.getActionVersion()); + getEnv().initialise(actionsUtil.getActionVersion()); }); test.serial("getApiClient", async (t) => { @@ -111,103 +118,115 @@ test.serial("getGitHubVersion for GHEC-DR", async (t) => { t.deepEqual({ type: util.GitHubVariant.GHEC_DR }, gheDotcom); }); -test.serial( - "wrapApiConfigurationError correctly wraps specific configuration errors", - (t) => { +test("wrapApiConfigurationError doesn't wrap errors it isn't supposed to", (t) => { + const unwrappedErrors = [ // We don't reclassify arbitrary errors - const arbitraryError = new Error("arbitrary error"); - let res = api.wrapApiConfigurationError(arbitraryError); - t.is(res, arbitraryError); - - // Same goes for arbitrary errors - const configError = new util.ConfigurationError("arbitrary error"); - res = api.wrapApiConfigurationError(configError); - t.is(res, configError); - - // If an HTTP error doesn't contain a specific error message, we don't - // wrap is an an API error. - const httpError = new util.HTTPError("arbitrary HTTP error", 456); - res = api.wrapApiConfigurationError(httpError); - t.is(res, httpError); - - // For other HTTP errors, we wrap them as Configuration errors if they contain - // specific error messages. - const httpNotFoundError = new util.HTTPError("commit not found", 404); - res = api.wrapApiConfigurationError(httpNotFoundError); - t.deepEqual(res, new util.ConfigurationError("commit not found")); - - const refNotFoundError = new util.HTTPError( - "ref 'refs/heads/jitsi' not found in this repository - https://docs.github.com/rest", - 404, - ); - res = api.wrapApiConfigurationError(refNotFoundError); - t.deepEqual( - res, - new util.ConfigurationError( - "ref 'refs/heads/jitsi' not found in this repository - https://docs.github.com/rest", - ), - ); + new Error("arbitrary error"), + // Same goes for arbitrary strings + "arbitrary error", + // If an HTTP error doesn't contain a specific error message, we don't wrap it. + new util.HTTPError("arbitrary HTTP error", 456), + ]; - const apiRateLimitError = new util.HTTPError( - "API rate limit exceeded for installation", - 403, - ); - res = api.wrapApiConfigurationError(apiRateLimitError); - t.deepEqual( + for (const unwrappedError of unwrappedErrors) { + const res = api.wrapApiConfigurationError(unwrappedError); + t.is( res, - new util.ConfigurationError("API rate limit exceeded for installation"), + unwrappedError, + `${util.getErrorMessage(unwrappedError)} should not be wrapped by wrapApiConfigurationError`, ); + } +}); - const tokenSuggestionMessage = - "Please check that your token is valid and has the required permissions: contents: read, security-events: write"; - const badCredentialsError = new util.HTTPError("Bad credentials", 401); - res = api.wrapApiConfigurationError(badCredentialsError); - t.deepEqual(res, new util.ConfigurationError(tokenSuggestionMessage)); +test("wrapApiConfigurationError correctly wraps specific configuration errors", (t) => { + // For other HTTP errors, we wrap them as Configuration errors if they contain + // specific error messages. + const httpNotFoundError = new util.HTTPError("commit not found", 404); + const refNotFoundError = new util.HTTPError( + "ref 'refs/heads/jitsi' not found in this repository - https://docs.github.com/rest", + 404, + ); + const apiRateLimitError = new util.HTTPError( + "API rate limit exceeded for installation", + 403, + ); + const resourceNotAccessibleError = new util.HTTPError( + "Resource not accessible by integration", + 403, + ); + const errorsToWrap = [ + httpNotFoundError, + refNotFoundError, + apiRateLimitError, + resourceNotAccessibleError, + ]; + + for (const errorToWrap of errorsToWrap) { + const res = api.wrapApiConfigurationError(errorToWrap); + t.deepEqual(res, new util.ConfigurationError(errorToWrap.message)); + } +}); + +test("wrapApiConfigurationError wraps token errors", async (t) => { + const tokenSuggestionMessage = + "Please check that your token is valid and has the required permissions: contents: read, security-events: write"; + const badCredentialsError = new util.HTTPError("Bad credentials", 401); + const notFoundError = new util.HTTPError("Not Found", 404); + const errorsToWrap = [badCredentialsError, notFoundError]; - const notFoundError = new util.HTTPError("Not Found", 404); - res = api.wrapApiConfigurationError(notFoundError); + for (const errorToWrap of errorsToWrap) { + const res = api.wrapApiConfigurationError(errorToWrap); t.deepEqual(res, new util.ConfigurationError(tokenSuggestionMessage)); + } +}); - const resourceNotAccessibleError = new util.HTTPError( - "Resource not accessible by integration", - 403, - ); - res = api.wrapApiConfigurationError(resourceNotAccessibleError); - t.deepEqual( - res, - new util.ConfigurationError("Resource not accessible by integration"), - ); +test("wrapApiConfigurationError wraps enablement errors", async (t) => { + // Enablement errors. + const enablementErrorMessages = [ + "Code Security must be enabled for this repository to use code scanning", + "Advanced Security must be enabled for this repository to use code scanning", + "Code Scanning is not enabled for this repository. Please enable code scanning in the repository settings.", + "Code quality is not enabled for this repository. Please enable code quality in the repository settings.", + ]; + const transforms = [ + (msg: string) => msg, + (msg: string) => msg.toLowerCase(), + (msg: string) => msg.toLocaleUpperCase(), + ]; - // Enablement errors. - const enablementErrorMessages = [ - "Code Security must be enabled for this repository to use code scanning", - "Advanced Security must be enabled for this repository to use code scanning", - "Code Scanning is not enabled for this repository. Please enable code scanning in the repository settings.", - "Code quality is not enabled for this repository. Please enable code quality in the repository settings.", - ]; - const transforms = [ - (msg: string) => msg, - (msg: string) => msg.toLowerCase(), - (msg: string) => msg.toLocaleUpperCase(), - ]; - - for (const enablementErrorMessage of enablementErrorMessages) { - for (const transform of transforms) { - const enablementError = new util.HTTPError( - transform(enablementErrorMessage), - 403, - ); - res = api.wrapApiConfigurationError(enablementError); - t.deepEqual( - res, - new util.ConfigurationError( - api.getFeatureEnablementError(enablementError.message), - ), - ); - } + for (const enablementErrorMessage of enablementErrorMessages) { + for (const transform of transforms) { + const enablementError = new util.HTTPError( + transform(enablementErrorMessage), + 403, + ); + const res = api.wrapApiConfigurationError(enablementError); + t.deepEqual( + res, + new util.ConfigurationError( + api.getFeatureEnablementError(enablementError.message), + ), + ); } - }, -); + } +}); + +test("wrapApiConfigurationError doesn't double-wrap errors", async (t) => { + // This test checks that errors don't get wrapped a second time if `wrapApiConfigurationError` + // is called on an error that was already wrapped by a previous call to `wrapApiConfigurationError`. + // Start by calling `wrapApiConfigurationError` on an unwrapped error that should be wrapped: + const unwrappedError = new util.HTTPError("commit not found", 404); + const wrappedError = api.wrapApiConfigurationError(unwrappedError); + + // Sanity-check that it was wrapped, as expected. + t.deepEqual( + wrappedError, + new util.ConfigurationError(unwrappedError.message), + ); + + // The result of the second call should be exactly `wrappedError`: + t.is(api.wrapApiConfigurationError(wrappedError), wrappedError); +}); test("getRegistryProxy - returns undefined if the proxy is not configured", async (t) => { const target = callee(api.getRegistryProxy).withArgs(); @@ -272,3 +291,87 @@ test("makeProxyRequestOptions - returns fetch with custom proxy", async (t) => { githubUtils.defaults.request, ); }); + +test.serial( + "getApiClientWithExternalAuth constructs clients with or without tokens", + (t) => { + t.notThrows(() => { + api.getApiClientWithExternalAuth(SAMPLE_DOTCOM_API_DETAILS); + api.getApiClientWithExternalAuth({ + ...SAMPLE_DOTCOM_API_DETAILS, + auth: undefined, + }); + }); + }, +); + +test("getAuthorizationHeaderFor - returns undefined if there's no token", (t) => { + const logger = new RecordingLogger(); + + t.is( + api.getAuthorizationHeaderFor( + logger, + { ...SAMPLE_DOTCOM_API_DETAILS, auth: undefined }, + `${GITHUB_DOTCOM_URL}/github`, + ), + undefined, + ); + t.is( + api.getAuthorizationHeaderFor( + logger, + { ...SAMPLE_DOTCOM_API_DETAILS, auth: "" }, + `${GITHUB_DOTCOM_URL}/github`, + ), + undefined, + ); + t.is( + api.getAuthorizationHeaderFor( + logger, + { ...SAMPLE_DOTCOM_API_DETAILS, auth: " " }, + `${GITHUB_DOTCOM_URL}/github`, + ), + undefined, + ); +}); + +test("getAuthorizationHeaderFor - returns header value with token if url is allowed", (t) => { + const logger = new RecordingLogger(); + + t.is( + api.getAuthorizationHeaderFor( + logger, + SAMPLE_DOTCOM_API_DETAILS, + `${GITHUB_DOTCOM_URL}/github`, + ), + `token ${SAMPLE_DOTCOM_API_DETAILS.auth}`, + ); + t.is( + api.getAuthorizationHeaderFor( + logger, + SAMPLE_DOTCOM_API_DETAILS, + `${GITHUB_DOTCOM_API_URL}/github`, + ), + `token ${SAMPLE_DOTCOM_API_DETAILS.auth}`, + ); +}); + +test("getAuthorizationHeaderFor - returns undefined if url is not allowed", (t) => { + const logger = new RecordingLogger(); + + t.is( + api.getAuthorizationHeaderFor( + logger, + SAMPLE_DOTCOM_API_DETAILS, + `https://localhost/github`, + ), + undefined, + ); + t.is( + api.getAuthorizationHeaderFor( + logger, + SAMPLE_DOTCOM_API_DETAILS, + `https://api.localhost/github`, + ), + undefined, + ); +}); diff --git a/src/api-client.ts b/src/api-client.ts index ba800a2587..8a456c1696 100644 --- a/src/api-client.ts +++ b/src/api-client.ts @@ -1,8 +1,6 @@ import * as core from "@actions/core"; import * as githubUtils from "@actions/github/lib/utils"; -import { type Octokit } from "@octokit/core"; -import { type PaginateInterface } from "@octokit/plugin-paginate-rest"; -import { type Api } from "@octokit/plugin-rest-endpoint-methods"; +import type { OctokitOptions } from "@octokit/core"; import * as retry from "@octokit/plugin-retry"; import { RequestRequestOptions } from "@octokit/types"; import { @@ -15,25 +13,32 @@ import { import type { ActionState } from "./action-common"; import { getActionVersion, getRequiredInput } from "./actions-util"; import { - ActionsEnvVars, EnvVar, ReadOnlyEnv, RegistryProxyVars, getEnv, + exportEnvVar, } from "./environment"; +import { + getCurrentInstance, + GITHUB_DOTCOM_URL, + parseGitHubUrl, + type GitHubApiCombinedDetails, + type GitHubApiDetails, +} from "./github"; import { Logger } from "./logging"; import { getRepositoryNwo, RepositoryNwo } from "./repository"; import { asHTTPError, ConfigurationError, getRequiredEnvParam, - GITHUB_DOTCOM_URL, GitHubVariant, GitHubVersion, - parseGitHubUrl, parseMatrixInput, } from "./util"; +export type { GitHubApiDetails, GitHubApiCombinedDetails } from "./github"; + const GITHUB_ENTERPRISE_VERSION_HEADER = "x-github-enterprise-version"; /** @@ -45,21 +50,6 @@ const GITHUB_ENTERPRISE_VERSION_HEADER = "x-github-enterprise-version"; */ export const DO_NOT_RETRY_STATUSES = [400, 410, 422, 451]; -export type GitHubApiCombinedDetails = GitHubApiDetails & - GitHubApiExternalRepoDetails; - -export interface GitHubApiDetails { - auth: string; - url: string; - apiURL: string | undefined; -} - -export interface GitHubApiExternalRepoDetails { - externalRepoAuth?: string; - url: string; - apiURL: string | undefined; -} - /** * Gets the configuration for the private registry authentication proxy, * if it is available in the environment. @@ -128,7 +118,7 @@ export function makeProxyRequestOptions( } /** The type of GitHub API client we use. */ -export type ApiClient = Octokit & Api & { paginate: PaginateInterface }; +export type ApiClient = InstanceType; /** Options for `createApiClientWithDetails`. */ interface CreateApiClientOptions { @@ -141,37 +131,60 @@ function createApiClientWithDetails( { allowExternal = false, proxy = undefined }: CreateApiClientOptions = {}, ): ApiClient { const auth = - (allowExternal && apiDetails.externalRepoAuth) || apiDetails.auth; + allowExternal && apiDetails.externalRepoAuth !== undefined + ? apiDetails.externalRepoAuth + : apiDetails.auth; const retryingOctokit = githubUtils.GitHub.plugin(retry.retry); const requestOptions = makeProxyRequestOptions(proxy); - return new retryingOctokit( - githubUtils.getOctokitOptions(auth, { - baseUrl: apiDetails.apiURL, - userAgent: `CodeQL-Action/${getActionVersion()}`, - log: { - debug: core.debug, - info: core.info, - warn: core.warning, - error: core.error, - }, - request: requestOptions, - retry: { - doNotRetry: DO_NOT_RETRY_STATUSES, - }, - }), - ); + + const opts: OctokitOptions = { + auth: + auth !== undefined && auth.trim() !== "" ? `token ${auth}` : undefined, + baseUrl: apiDetails.apiURL, + userAgent: `CodeQL-Action/${getActionVersion()}`, + log: { + debug: core.debug, + info: core.info, + warn: core.warning, + error: core.error, + }, + request: requestOptions, + retry: { + doNotRetry: DO_NOT_RETRY_STATUSES, + }, + }; + + return new retryingOctokit(opts); } +/** + * Gets a `GitHubApiDetails` object describing the GitHub instance we are currently running on. + * + * @param env The environment variables to read. + */ export function getApiDetails(env: ReadOnlyEnv = getEnv()): GitHubApiDetails { return { auth: getRequiredInput("token"), - url: env.getRequired(ActionsEnvVars.GITHUB_SERVER_URL), - apiURL: env.getRequired(ActionsEnvVars.GITHUB_API_URL), + ...getCurrentInstance(env), }; } -export function getApiClient(env: ReadOnlyEnv = getEnv()) { - return createApiClientWithDetails(getApiDetails(env)); +/** + * Constructs an {@link ApiClient} using {@link apiDetails}. + * + * If {@link apiDetails} is not specified, then the GitHub instance URLs and auth token + * are taken from {@link env}. + * + * If {@link env} is not specified, then the process environment is used. + * + * @param env The environment to obtain the GitHub instance URLs from. + * @param apiDetails The {@link GitHubApiDetails} to construct the {@link ApiClient} for. + */ +export function getApiClient( + env: ReadOnlyEnv = getEnv(), + apiDetails?: GitHubApiDetails, +) { + return createApiClientWithDetails(apiDetails ?? getApiDetails(env)); } export function getApiClientWithExternalAuth( @@ -196,6 +209,12 @@ export function getAuthorizationHeaderFor( apiDetails: GitHubApiDetails, url: string, ): string | undefined { + // We don't have to check the `url` if we don't have a token to begin with. + const token = apiDetails.auth?.trim(); + if (token === undefined || token === "") { + return undefined; + } + // We only want to provide an authorization header if we are downloading // from the same GitHub instance the Action is running on. // This avoids leaking Enterprise tokens to dotcom. @@ -204,7 +223,7 @@ export function getAuthorizationHeaderFor( (apiDetails.apiURL && url.startsWith(`${apiDetails.apiURL}/`)) ) { logger.debug(`Providing an authorization token.`); - return `token ${apiDetails.auth}`; + return `token ${token}`; } logger.debug(`Not using an authorization token.`); @@ -222,25 +241,31 @@ export async function getGitHubVersionFromApi( return { type: GitHubVariant.DOTCOM }; } - // Doesn't strictly have to be the meta endpoint as we're only - // using the response headers which are available on every request. - // - // See https://docs.github.com/en/rest/meta/meta#get-github-meta-information. - // eslint-disable-next-line @typescript-eslint/no-unsafe-call - const response = await apiClient.rest.meta.get(); + try { + // Doesn't strictly have to be the meta endpoint as we're only + // using the response headers which are available on every request. + // + // See https://docs.github.com/en/rest/meta/meta#get-github-meta-information. + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + const response = await apiClient.rest.meta.get(); + + // This happens on dotcom, although we expect to have already returned in that + // case. This can also serve as a fallback in cases we haven't foreseen. + if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === undefined) { + return { type: GitHubVariant.DOTCOM }; + } - // This happens on dotcom, although we expect to have already returned in that - // case. This can also serve as a fallback in cases we haven't foreseen. - if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === undefined) { - return { type: GitHubVariant.DOTCOM }; - } + if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === "ghe.com") { + return { type: GitHubVariant.GHEC_DR }; + } - if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === "ghe.com") { - return { type: GitHubVariant.GHEC_DR }; + const version = response.headers[ + GITHUB_ENTERPRISE_VERSION_HEADER + ] as string; + return { type: GitHubVariant.GHES, version }; + } catch (err) { + throw wrapApiConfigurationError(err); } - - const version = response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] as string; - return { type: GitHubVariant.GHES, version }; } /** @@ -252,9 +277,10 @@ export async function getGitHubVersionFromApi( */ export async function getGitHubVersion(): Promise { if (cachedGitHubVersion === undefined) { + const apiDetails = getApiDetails(); cachedGitHubVersion = await getGitHubVersionFromApi( - getApiClient(), - getApiDetails(), + createApiClientWithDetails(apiDetails), + apiDetails, ); } return cachedGitHubVersion; @@ -312,7 +338,7 @@ export async function getAnalysisKey(): Promise { const jobName = getRequiredEnvParam("GITHUB_JOB"); analysisKey = `${workflowPath}:${jobName}`; - core.exportVariable(EnvVar.ANALYSIS_KEY, analysisKey); + exportEnvVar(EnvVar.ANALYSIS_KEY, analysisKey); return analysisKey; } @@ -375,21 +401,6 @@ export async function listActionsCaches( ); } -/** - * Delete an Actions cache item by its ID. - * - * See https://docs.github.com/en/rest/actions/cache#delete-a-github-actions-cache-for-a-repository-using-a-cache-id. - */ -export async function deleteActionsCache(id: number) { - const repositoryNwo = getRepositoryNwo(); - - await getApiClient().rest.actions.deleteActionsCacheById({ - owner: repositoryNwo.owner, - repo: repositoryNwo.repo, - cache_id: id, - }); -} - /** * Retrieve all custom repository properties. * @@ -417,7 +428,14 @@ export function getFeatureEnablementError(message: string): string { return `Please verify that the necessary features are enabled: ${message}`; } -export function wrapApiConfigurationError(e: unknown) { +/** + * Decides whether `e` is a known error returned by the GitHub API that we should + * classify as a `ConfigurationError`. + * + * @param e The error to classify. + * @returns Either `e` or a corresponding `ConfigurationError`. + */ +export function wrapApiConfigurationError(e: T): T | ConfigurationError { const httpError = asHTTPError(e); if (httpError !== undefined) { if ( diff --git a/src/api-compatibility.json b/src/api-compatibility.json index aa7840e384..83ff180db0 100644 --- a/src/api-compatibility.json +++ b/src/api-compatibility.json @@ -1 +1 @@ -{"maximumVersion":"3.23","minimumVersion":"3.17"} +{"maximumVersion":"3.23","minimumVersion":"3.19"} diff --git a/src/artifact-scanner.test.ts b/src/artifact-scanner.test.ts index 56f99e1138..50c0d3fd22 100644 --- a/src/artifact-scanner.test.ts +++ b/src/artifact-scanner.test.ts @@ -10,12 +10,12 @@ import { scanArtifactsForTokens, TokenType, } from "./artifact-scanner"; -import { getRunnerLogger } from "./logging"; import { checkExpectedLogMessages, getRecordingLogger, LoggedMessage, makeTestToken, + RecordingLogger, } from "./testing-utils"; test("makeTestToken", (t) => { @@ -121,7 +121,7 @@ for (const { type, value, checkPattern } of testTokens) { } test("scanArtifactsForTokens handles files without tokens", async (t) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "scanner-test-")); try { diff --git a/src/autobuild-action.ts b/src/autobuild-action.ts index 9fa8016578..3e2eb1a3f2 100644 --- a/src/autobuild-action.ts +++ b/src/autobuild-action.ts @@ -10,7 +10,7 @@ import { getGitHubVersion } from "./api-client"; import { determineAutobuildLanguages, runAutobuild } from "./autobuild"; import { getCodeQL } from "./codeql"; import { Config, getConfig } from "./config-utils"; -import { EnvVar } from "./environment"; +import { EnvVar, type Env } from "./environment"; import { Language } from "./languages"; import { Logger } from "./logging"; import { @@ -26,7 +26,6 @@ import { checkDiskUsage, checkGitHubVersionInRange, ConfigurationError, - initializeEnvironment, wrapError, } from "./util"; @@ -38,6 +37,7 @@ interface AutobuildStatusReport extends StatusReportBase { } async function sendCompletedStatusReport( + env: Env, config: Config | undefined, logger: Logger, startedAt: Date, @@ -45,7 +45,7 @@ async function sendCompletedStatusReport( failingLanguage?: string, cause?: Error, ) { - initializeEnvironment(getActionVersion()); + env.initialise(getActionVersion()); const status = getActionsStatus(cause, failingLanguage); const statusReportBase = await createStatusReportBase( @@ -68,7 +68,11 @@ async function sendCompletedStatusReport( } } -async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { +async function run({ + startedAt, + env, + logger, +}: ActionState<["Base", "Env", "Logger"]>) { // To capture errors appropriately, keep as much code within the try-catch as // possible, and only use safe functions outside. @@ -125,6 +129,7 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { `We were unable to automatically build your code. Please replace the call to the autobuild action with your custom build steps. ${error.message}`, ); await sendCompletedStatusReport( + env, config, logger, startedAt, @@ -135,9 +140,15 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { return; } - core.exportVariable(EnvVar.AUTOBUILD_DID_COMPLETE_SUCCESSFULLY, "true"); + env.export(EnvVar.AUTOBUILD_DID_COMPLETE_SUCCESSFULLY, "true"); - await sendCompletedStatusReport(config, logger, startedAt, languages ?? []); + await sendCompletedStatusReport( + env, + config, + logger, + startedAt, + languages ?? [], + ); } /** Defines the `autobuild` Action. */ diff --git a/src/autobuild.ts b/src/autobuild.ts index 49b790102d..44f6abd0c7 100644 --- a/src/autobuild.ts +++ b/src/autobuild.ts @@ -1,11 +1,9 @@ -import * as core from "@actions/core"; - import { getTemporaryDirectory, getWorkflowEventName } from "./actions-util"; import { getGitHubVersion } from "./api-client"; import { CodeQL, getCodeQL } from "./codeql"; import * as configUtils from "./config-utils"; import { DocUrl } from "./doc-url"; -import { ActionsEnvVars, EnvVar } from "./environment"; +import { ActionsEnvVars, EnvVar, exportEnvVar } from "./environment"; import { Feature, featureConfig, initFeatures } from "./feature-flags"; import { BuiltInLanguage, Language } from "./languages"; import { Logger } from "./logging"; @@ -112,7 +110,7 @@ export async function determineAutobuildLanguages( return languages; } -export async function setupCppAutobuild(codeql: CodeQL, logger: Logger) { +export async function setupCppAutobuild(logger: Logger) { const envVar = featureConfig[Feature.CppDependencyInstallation].envVar; const featureName = "C++ automatic installation of dependencies"; const gitHubVersion = await getGitHubVersion(); @@ -123,7 +121,7 @@ export async function setupCppAutobuild(codeql: CodeQL, logger: Logger) { getTemporaryDirectory(), logger, ); - if (await features.getValue(Feature.CppDependencyInstallation, codeql)) { + if (await features.getValue(Feature.CppDependencyInstallation)) { // disable autoinstall on self-hosted runners unless explicitly requested if ( process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] === "self-hosted" && @@ -136,16 +134,16 @@ export async function setupCppAutobuild(codeql: CodeQL, logger: Logger) { : "" }`, ); - core.exportVariable(envVar, "false"); + exportEnvVar(envVar, "false"); } else { logger.info( `Enabling ${featureName}. This can be disabled by setting the ${envVar} environment variable to 'false'. See ${DocUrl.DEFINE_ENV_VARIABLES} for more information.`, ); - core.exportVariable(envVar, "true"); + exportEnvVar(envVar, "true"); } } else { logger.info(`Disabling ${featureName}.`); - core.exportVariable(envVar, "false"); + exportEnvVar(envVar, "false"); } } @@ -157,7 +155,7 @@ export async function runAutobuild( logger.startGroup(`Attempting to automatically build ${language} code`); const codeQL = await getCodeQL(logger, config.codeQLCmd); if (language === BuiltInLanguage.cpp) { - await setupCppAutobuild(codeQL, logger); + await setupCppAutobuild(logger); } if (config.buildMode) { await codeQL.extractUsingBuildMode(config, language); @@ -165,7 +163,7 @@ export async function runAutobuild( await codeQL.runAutobuild(config, language); } if (language === BuiltInLanguage.go) { - core.exportVariable(EnvVar.DID_AUTOBUILD_GOLANG, "true"); + exportEnvVar(EnvVar.DID_AUTOBUILD_GOLANG, "true"); } logger.endGroup(); } diff --git a/src/caching-utils.ts b/src/caching-utils.ts index 33dac7cfb4..d5cdb84452 100644 --- a/src/caching-utils.ts +++ b/src/caching-utils.ts @@ -5,7 +5,7 @@ import * as core from "@actions/core"; import { getOptionalInput, isDefaultSetup } from "./actions-util"; import { EnvVar } from "./environment"; import { Logger } from "./logging"; -import { isHostedRunner, tryGetFolderBytes } from "./util"; +import { looksLikeHostedRunner, tryGetFolderBytes } from "./util"; /** * Returns the total size of all the specified paths. @@ -109,7 +109,7 @@ export function getDependencyCachingEnabled(): CachingKind { if (dependencyCaching !== undefined) return getCachingKind(dependencyCaching); // On self-hosted runners which may have dependencies installed centrally, disable caching by default - if (!isHostedRunner()) return CachingKind.None; + if (!looksLikeHostedRunner()) return CachingKind.None; // Disable in advanced workflows by default. if (!isDefaultSetup()) return CachingKind.None; diff --git a/src/cli-errors.test.ts b/src/cli-errors.test.ts index 9e2d7dc799..bb0e1b5d91 100644 --- a/src/cli-errors.test.ts +++ b/src/cli-errors.test.ts @@ -128,7 +128,6 @@ test("CliError constructor with empty stderr", (t) => { for (const [platform, arch] of [ ["weird_plat", "x64"], - ["linux", "arm64"], ["win32", "arm64"], ]) { test.serial( @@ -157,20 +156,34 @@ for (const [platform, arch] of [ ); } -test("wrapCliConfigurationError - supported platform", (t) => { - const commandError = new CommandInvocationError( - "codeql", - ["version"], - 1, - "Some error", - ); - const cliError = new CliError(commandError); +for (const [platform, arch] of [ + ["linux", "x64"], + ["linux", "arm64"], + ["win32", "x64"], + ["darwin", "x64"], + ["darwin", "arm64"], +]) { + test.serial( + `wrapCliConfigurationError - ${platform}/${arch} supported`, + (t) => { + sinon.stub(process, "platform").value(platform); + sinon.stub(process, "arch").value(arch); + const commandError = new CommandInvocationError( + "codeql", + ["version"], + 1, + "Some error", + ); + const cliError = new CliError(commandError); - const wrappedError = wrapCliConfigurationError(cliError); + const wrappedError = wrapCliConfigurationError(cliError); - // Should return the original error since platform is supported - t.is(wrappedError, cliError); -}); + // Should return the original error since the platform is supported, rather + // than replacing it with the unsupported-platform ConfigurationError. + t.is(wrappedError, cliError); + }, + ); +} test("wrapCliConfigurationError - autobuild error", (t) => { const commandError = new CommandInvocationError( diff --git a/src/cli-errors.ts b/src/cli-errors.ts index 84ec1aa4e6..608413002c 100644 --- a/src/cli-errors.ts +++ b/src/cli-errors.ts @@ -8,6 +8,7 @@ import { ConfigurationError } from "./util"; const SUPPORTED_PLATFORMS = [ ["linux", "x64"], + ["linux", "arm64"], ["win32", "x64"], ["darwin", "x64"], ["darwin", "arm64"], diff --git a/src/cli/output-cache.test.ts b/src/cli/output-cache.test.ts index d8d8629303..ed49dab09d 100644 --- a/src/cli/output-cache.test.ts +++ b/src/cli/output-cache.test.ts @@ -3,33 +3,31 @@ import path from "path"; import test from "ava"; -import { EnvVar } from "../environment"; -import { getRunnerLogger } from "../logging"; -import { getTestEnv, setupTests } from "../testing-utils"; +import { RecordingLogger, setupTests } from "../testing-utils"; import * as util from "../util"; -import * as outputCache from "./output-cache"; +import { getCachedCodeQlVersion } from "./output-cache"; setupTests(test); -const logger = getRunnerLogger(true); +const logger = new RecordingLogger(); test.serial( "getCachedCodeQlVersion reuses a version persisted by an earlier step", async (t) => { await util.withTmpDir(async (tmpDir: string) => { - const cacheFile = path.join(tmpDir, "codeql-action-command-cache.json"); + const cacheFilePath = path.join(tmpDir, "cache.json"); + fs.writeFileSync( - cacheFile, + cacheFilePath, JSON.stringify({ cmd: "/path/to/codeql", entries: { version: { version: "2.20.0" } }, }), "utf8", ); - const env = getTestEnv({ [EnvVar.TEMP]: tmpDir }); t.deepEqual( - outputCache.getCachedCodeQlVersion(logger, env, "/path/to/codeql"), + getCachedCodeQlVersion(logger, cacheFilePath, "/path/to/codeql"), { version: "2.20.0", }, @@ -42,18 +40,17 @@ test.serial( "getCachedCodeQlVersion ignores a persisted version from a different CLI", async (t) => { await util.withTmpDir(async (tmpDir: string) => { - const cacheFile = path.join(tmpDir, "version.json"); + const cacheFilePath = path.join(tmpDir, "cache.json"); fs.writeFileSync( - cacheFile, + cacheFilePath, JSON.stringify({ cmd: "/path/to/other-codeql", - version: { version: "2.20.0" }, + entries: { version: { version: "2.20.0" } }, }), "utf8", ); - const env = getTestEnv({ [EnvVar.TEMP]: tmpDir }); t.is( - outputCache.getCachedCodeQlVersion(logger, env, "/path/to/codeql"), + getCachedCodeQlVersion(logger, cacheFilePath, "/path/to/codeql"), undefined, ); }); @@ -64,11 +61,10 @@ test.serial( "getCachedCodeQlVersion ignores a malformed persisted value", async (t) => { await util.withTmpDir(async (tmpDir: string) => { - const cacheFile = path.join(tmpDir, "version.json"); - fs.writeFileSync(cacheFile, "not valid json", "utf8"); - const env = getTestEnv({ [EnvVar.TEMP]: tmpDir }); + const cacheFilePath = path.join(tmpDir, "cache.json"); + fs.writeFileSync(cacheFilePath, "not valid json", "utf8"); t.is( - outputCache.getCachedCodeQlVersion(logger, env, "/path/to/codeql"), + getCachedCodeQlVersion(logger, cacheFilePath, "/path/to/codeql"), undefined, ); }); @@ -79,9 +75,7 @@ test.serial( "getCachedCodeQlVersion ignores a persisted value with the wrong structure", async (t) => { await util.withTmpDir(async (tmpDir: string) => { - const cacheFile = path.join(tmpDir, "version.json"); - const env = getTestEnv({ [EnvVar.TEMP]: tmpDir }); - + const cacheFilePath = path.join(tmpDir, "cache.json"); const testValues = [ { cmd: "/path/to/codeql" }, { entries: { version: { version: "2.20.0" } } }, @@ -104,9 +98,9 @@ test.serial( ].map((v) => JSON.stringify(v)); for (const value of testValues) { - fs.writeFileSync(cacheFile, value, "utf8"); + fs.writeFileSync(cacheFilePath, value, "utf8"); t.is( - outputCache.getCachedCodeQlVersion(logger, env, "/path/to/codeql"), + getCachedCodeQlVersion(logger, cacheFilePath, "/path/to/codeql"), undefined, value, ); @@ -117,10 +111,10 @@ test.serial( test.serial("getCachedCodeQlVersion ignores non-existent file", async (t) => { await util.withTmpDir(async (tmpDir: string) => { - const env = getTestEnv({ [EnvVar.TEMP]: tmpDir }); + const cacheFilePath = path.join(tmpDir, "cache.json"); t.notThrows(() => { t.is( - outputCache.getCachedCodeQlVersion(logger, env, "/path/to/codeql"), + getCachedCodeQlVersion(logger, cacheFilePath, "/path/to/codeql"), undefined, ); }); diff --git a/src/cli/output-cache.ts b/src/cli/output-cache.ts index 8bf8c27abe..209df575db 100644 --- a/src/cli/output-cache.ts +++ b/src/cli/output-cache.ts @@ -2,10 +2,11 @@ import * as fs from "fs"; import path from "path"; import { getTemporaryDirectory } from "../actions-util"; -import { Env } from "../environment"; +import { ReadOnlyEnv } from "../environment"; +import * as json from "../json"; import { Logger } from "../logging"; -import type { VersionInfo } from "./types"; +import { VersionInfo, versionInfoBaseSchema } from "./types"; /** * The keys of the command cache. Each key corresponds to a command whose output we cache. @@ -13,12 +14,19 @@ import type { VersionInfo } from "./types"; export type CommandCacheKey = string; /** - * The type of the command cache that is persisted to disk. + * The JSON schema of the command cache that is persisted to disk. */ -export interface OutputCache { - cmd: string; - entries: Record; -} +const outputCacheSchema = { + cmd: json.string, + entries: json.object({}), +} as const satisfies json.Schema; + +/** + * The type that describes the command cache that is persisted to disk. + */ +export type OutputCache = json.FromSchema & { + entries: { version: VersionInfo }; +}; /** * The name of the temporary file that backs the on-disk cache of @@ -43,18 +51,18 @@ export function resetCachedCodeQlVersion(): void { * Returns the path to the temporary file that backs the * on-disk cache of CLI responses between workflow steps. */ -function getCommandCacheFilePath(env: Env): string { +export function getCommandCacheFilePath(env: ReadOnlyEnv): string { return path.join(getTemporaryDirectory(env), COMMAND_CACHE_FILENAME); } /** * Caches the CodeQL CLI version both in-memory and on disk. - * @param env The environment variables to use. + * @param cacheFilePath The path to the cache file. * @param cmd The path to the CodeQL CLI. * @param version The version information to cache. */ export function cacheCodeQlVersion( - env: Env, + cacheFilePath: string, cmd: string, version: VersionInfo, ): void { @@ -70,22 +78,18 @@ export function cacheCodeQlVersion( // processes, can reuse it rather than invoking `codeql version` again. We // record the CLI path so that a different step using a different CodeQL bundle // doesn't pick up a stale version. - fs.writeFileSync( - getCommandCacheFilePath(env), - JSON.stringify(outputCache), - "utf8", - ); + fs.writeFileSync(cacheFilePath, JSON.stringify(outputCache), "utf8"); } /** * Returns the cached CodeQL CLI version, if any. * @param logger The logger to use for logging messages. - * @param env The environment variables to use. + * @param cacheFilePath The path to the cache file. * @param cmd The path to the CodeQL CLI. */ export function getCachedCodeQlVersion( logger: Logger, - env: Env, + cacheFilePath: string, cmd?: string, ): undefined | VersionInfo { if (cachedCodeQlVersion !== undefined) { @@ -96,11 +100,9 @@ export function getCachedCodeQlVersion( // invokes `codeql version` instead. let serialized: string; try { - serialized = fs.readFileSync(getCommandCacheFilePath(env), "utf8"); + serialized = fs.readFileSync(cacheFilePath, "utf8"); } catch (e) { - logger.debug( - `Cannot read CLI-cache file ${getCommandCacheFilePath(env)}: ${e}`, - ); + logger.debug(`Cannot read CLI-cache file ${cacheFilePath}: ${e}`); return undefined; } let persisted: unknown; @@ -127,17 +129,7 @@ export function getCachedCodeQlVersion( * @param x The value to test */ function isVersionInfo(x: unknown): x is VersionInfo { - const candidate = x as Partial | null; - return ( - typeof candidate === "object" && - candidate !== null && - typeof candidate.version === "string" && - (candidate.features === undefined || - (typeof candidate.features === "object" && - candidate.features !== null)) && - (candidate.overlayVersion === undefined || - typeof candidate.overlayVersion === "number") - ); + return json.isObject(x) && json.validateSchema(versionInfoBaseSchema, x); } /** @@ -145,12 +137,10 @@ function isVersionInfo(x: unknown): x is VersionInfo { * @param x The value to test */ function isOutputCache(x: unknown): x is OutputCache { - const candidate = x as Partial | null; return ( - typeof candidate === "object" && - candidate !== null && - typeof candidate.cmd === "string" && - candidate.entries !== undefined && - isVersionInfo(candidate.entries.version) + json.isObject(x) && + json.validateSchema(outputCacheSchema, x) && + json.isObject<{ version: unknown }>(x.entries) && + isVersionInfo(x.entries.version) ); } diff --git a/src/cli/types.ts b/src/cli/types.ts index ad48ff29b4..71d8d14c2f 100644 --- a/src/cli/types.ts +++ b/src/cli/types.ts @@ -1,6 +1,11 @@ -export interface VersionInfo { - version: string; - features?: { [name: string]: boolean }; +import * as json from "../json"; + +/** + * The JSON schema of the expected output of the `codeql version` command. + */ +export const versionInfoBaseSchema = { + version: json.string, + features: json.optional(json.object({})), /** * The overlay version helps deal with backward incompatible changes for * overlay analysis. When a precompiled query pack reports the same overlay @@ -9,5 +14,17 @@ export interface VersionInfo { * or if either the pack or the CLI does not report an overlay version, * we need to revert to non-overlay analysis. */ - overlayVersion?: number; -} + overlayVersion: json.optional(json.number), +} as const satisfies json.Schema; + +/** + * The base type that describes the expected output of the `codeql version` command. + */ +export type VersionInfoBase = json.FromSchema; + +/** + * The full type that describes the expected output of the `codeql version` command. + */ +export type VersionInfo = Omit & { + features?: { [name: string]: boolean }; +}; diff --git a/src/codeql-bundle.test.ts b/src/codeql-bundle.test.ts new file mode 100644 index 0000000000..e528ee76fd --- /dev/null +++ b/src/codeql-bundle.test.ts @@ -0,0 +1,75 @@ +import test from "ava"; + +import { getCodeQLBundleFromUrl, getCodeQLBundleName } from "./codeql-bundle"; +import { BuiltInLanguage } from "./languages"; +import { BundlePlatform } from "./platform"; + +test("getCodeQLBundleName returns a per-language bundle name only when a language is specified", (t) => { + t.is( + getCodeQLBundleName("zstd", BundlePlatform.Linux64, BuiltInLanguage.java), + "codeql-bundle-java-linux64.tar.zst", + ); + t.is( + getCodeQLBundleName("zstd", BundlePlatform.Linux64), + "codeql-bundle-linux64.tar.zst", + ); +}); + +test("getCodeQLBundleName names the Swift bundle for macOS", (t) => { + t.is( + getCodeQLBundleName("zstd", BundlePlatform.Osx64, BuiltInLanguage.swift), + "codeql-bundle-swift-osx64.tar.zst", + ); +}); + +for (const [assetName, language] of [ + ["codeql-bundle-java-linux64.tar.zst", BuiltInLanguage.java], + ["codeql-bundle-swift-osx64.tar.zst", BuiltInLanguage.swift], + // Recognize unpublished language/platform combinations to keep them out of the toolcache. + ["codeql-bundle-csharp-win64.tar.gz", BuiltInLanguage.csharp], + ["codeql-bundle-java-kotlin-linux64.tar.zst", BuiltInLanguage.java], + ["codeql-bundle-%70ython-linux64.tar.zst", BuiltInLanguage.python], +] as const) { + test(`getCodeQLBundleFromUrl identifies ${assetName} without adding a fallback`, (t) => { + const url = `https://github.com/github/codeql-action/releases/download/codeql-bundle-v1.2.3/${assetName}`; + t.deepEqual(getCodeQLBundleFromUrl(url), { + kind: "per-language", + url, + language, + }); + }); +} + +test("getCodeQLBundleFromUrl preserves encoding, query parameters and fragments", (t) => { + const url = + "https://github.com/github/codeql-action/releases/download/codeql-bundle-v1.2.3/codeql-bundle-%70ython-linux64.tar.zst?download=1#asset"; + t.deepEqual(getCodeQLBundleFromUrl(url), { + kind: "per-language", + url, + language: BuiltInLanguage.python, + }); +}); + +test("getCodeQLBundleFromUrl treats unrecognized assets as combined bundles", (t) => { + for (const name of [ + "codeql-bundle-linux64.tar.zst", + "codeql-bundle-osx64.tar.gz", + "codeql-bundle-win64.tar.zst", + // The all-platform bundle. + "codeql-bundle.tar.gz", + // A platform we do not publish per-language bundles for, whose name also contains a hyphen. + "codeql-bundle-linux-arm64.tar.zst", + // Not a language we know about. + "codeql-bundle-cobol-linux64.tar.zst", + // A name we cannot decode must not be mistaken for a language either. + "codeql-bundle-%zz-linux64.tar.zst", + ]) { + const url = `https://github.com/github/codeql-action/releases/download/codeql-bundle-v1.2.3/${name}`; + t.deepEqual(getCodeQLBundleFromUrl(url), { kind: "combined", url }); + } +}); + +test("getCodeQLBundleFromUrl preserves URLs it cannot parse", (t) => { + const url = "not a url"; + t.deepEqual(getCodeQLBundleFromUrl(url), { kind: "combined", url }); +}); diff --git a/src/codeql-bundle.ts b/src/codeql-bundle.ts new file mode 100644 index 0000000000..2d262c848e --- /dev/null +++ b/src/codeql-bundle.ts @@ -0,0 +1,71 @@ +import { BuiltInLanguage, parseBuiltInLanguage } from "./languages"; +import { BundlePlatform } from "./platform"; +import type { CompressionMethod } from "./tar"; + +/** Describes the contents and location of a downloadable CodeQL bundle. */ +export type CodeQLBundle = + | { kind: "combined"; url: string } + | { + kind: "per-language"; + url: string; + language: BuiltInLanguage; + /** Only set when the Action selected the bundle, allowing a same-version fallback. */ + combinedBundleURL?: string; + }; + +/** A resolved download, including its bundle identity and version. */ +export interface CodeQLDownloadSource { + /** Distinguishes downloads from local archives and cached installations. */ + sourceType: "download"; + /** The bundle to download. */ + bundle: CodeQLBundle; + /** The compression format of the bundle archive. */ + compressionMethod: CompressionMethod; + /** Bundle version of the tools, if known. */ + bundleVersion?: string; + /** Requested CLI version, if known. */ + cliVersion?: string; + /** Resolved version for telemetry, independent of whether the bundle can be cached. */ + toolsVersion: string; +} + +/** Returns the exact bundle asset name for a platform and optional language. */ +export function getCodeQLBundleName( + compressionMethod: CompressionMethod, + platform: BundlePlatform | undefined, + language?: BuiltInLanguage, +): string { + const extensions: Record = { + gzip: ".tar.gz", + zstd: ".tar.zst", + }; + const extension = extensions[compressionMethod]; + if (platform === undefined) { + return `codeql-bundle${extension}`; + } + if (language !== undefined) { + return `codeql-bundle-${language}-${platform}${extension}`; + } + return `codeql-bundle-${platform}${extension}`; +} + +const PER_LANGUAGE_BUNDLE_NAME = + /^codeql-bundle-(.+)-(?:linux64|osx64|win64)\.tar\.(?:gz|zst)$/; + +/** Classifies an explicit tools URL without changing it or adding a fallback. */ +export function getCodeQLBundleFromUrl(url: string): CodeQLBundle { + let assetName: string; + try { + const pathname = new URL(url).pathname; + // URL-encoded names must not bypass the toolcache safeguard. + assetName = decodeURIComponent(pathname.split("/").pop() ?? ""); + } catch { + return { kind: "combined", url }; + } + + const match = assetName.match(PER_LANGUAGE_BUNDLE_NAME); + const language = match ? parseBuiltInLanguage(match[1]) : undefined; + return language === undefined + ? { kind: "combined", url } + : { kind: "per-language", url, language }; +} diff --git a/src/codeql.test.ts b/src/codeql.test.ts index df4bafe295..d39b9a60d5 100644 --- a/src/codeql.test.ts +++ b/src/codeql.test.ts @@ -21,8 +21,8 @@ import { import type { Config } from "./config-utils"; import * as defaults from "./defaults.json"; import { DocUrl } from "./doc-url"; +import { getEnv } from "./environment"; import { BuiltInLanguage } from "./languages"; -import { getRunnerLogger } from "./logging"; import { ToolsSource } from "./setup-codeql"; import { setupTests, @@ -34,17 +34,18 @@ import { makeVersionInfo, createTestConfig, makeMacro, + getCodeQLForTesting, + RecordingLogger, } from "./testing-utils"; import { ToolsDownloadStatusReport } from "./tools-download"; import * as util from "./util"; -import { initializeEnvironment } from "./util"; setupTests(test); let stubConfig: Config; test.beforeEach(() => { - initializeEnvironment("1.2.3"); + getEnv().initialise("1.2.3"); stubConfig = createTestConfig({ languages: [BuiltInLanguage.cpp], @@ -90,7 +91,7 @@ async function installIntoToolcache({ tmpDir: string; }) { const url = mockBundleDownloadApi({ apiDetails, isPinned, tagName }); - await codeql.setupCodeQL( + return await codeql.setupCodeQL( cliVersion !== undefined ? undefined : url, apiDetails, tmpDir, @@ -99,9 +100,10 @@ async function installIntoToolcache({ ? { enabledVersions: [{ cliVersion, tagName }] } : SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion createFeatures([]), - getRunnerLogger(true), + new RecordingLogger(), false, ); } @@ -125,7 +127,7 @@ function mockReleaseApi({ }); } -function mockApiDetails(apiDetails: GitHubApiDetails) { +function mockApiDetails(apiDetails: Required) { // This is a workaround to mock `api.getApiDetails()` since it doesn't seem to be possible to // mock this directly. The difficulty is that `getApiDetails()` is called locally in // `api-client.ts`, but `sinon.stub(api, "getApiDetails")` only affects calls to @@ -139,7 +141,7 @@ function mockApiDetails(apiDetails: GitHubApiDetails) { } async function stubCodeql(): Promise { - const codeqlObject = await codeql.getCodeQLForTesting(); + const codeqlObject = await getCodeQLForTesting(); sinon.stub(codeqlObject, "getVersion").resolves(makeVersionInfo("2.17.6")); sinon .stub(codeqlObject, "isTracedLanguage") @@ -172,9 +174,10 @@ test.serial( util.GitHubVariant.DOTCOM, SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion features, - getRunnerLogger(true), + new RecordingLogger(), false, ); @@ -207,9 +210,10 @@ test.serial( util.GitHubVariant.DOTCOM, SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion features, - getRunnerLogger(true), + new RecordingLogger(), false, ); @@ -246,9 +250,10 @@ test.serial( util.GitHubVariant.DOTCOM, SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion features, - getRunnerLogger(true), + new RecordingLogger(), false, ); t.assert(toolcache.find("CodeQL", "0.0.0-20200610")); @@ -259,6 +264,65 @@ test.serial( }, ); +for (const { cliVersion, tagName, expectedToolcacheVersion } of [ + { + cliVersion: "2.21.0", + tagName: "codeql-bundle-20240101", + expectedToolcacheVersion: "2.21.0", + }, + { + cliVersion: "2.21.0-rc.1", + tagName: "codeql-bundle-20240101", + expectedToolcacheVersion: "0.0.0-20240101", + }, + { + cliVersion: "2.21.0+20240101", + tagName: "codeql-bundle-20240101", + expectedToolcacheVersion: "0.0.0-20240101", + }, + { + cliVersion: "2.21.0", + tagName: "custom-release", + expectedToolcacheVersion: undefined, + }, +]) { + test.serial( + `preserves CLI version ${cliVersion} when installing ${tagName}`, + async (t) => { + await util.withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + + const result = await installIntoToolcache({ + cliVersion, + isPinned: false, + tagName, + tmpDir, + }); + + t.is(result.toolsVersion, cliVersion); + t.is(result.toolsSource, ToolsSource.Download); + t.true( + Number.isInteger(result.toolsDownloadStatusReport?.totalDurationMs), + ); + t.deepEqual( + toolcache.findAllVersions("CodeQL"), + expectedToolcacheVersion === undefined + ? [] + : [expectedToolcacheVersion], + ); + if (expectedToolcacheVersion !== undefined) { + const cachedFolder = toolcache.find( + "CodeQL", + expectedToolcacheVersion, + ); + t.truthy(cachedFolder); + t.true(fs.existsSync(`${cachedFolder}.complete`)); + } + }); + }, + ); +} + const EXPLICITLY_REQUESTED_BUNDLE_TEST_CASES = [ { tagName: "codeql-bundle-2.17.6", @@ -296,9 +360,10 @@ for (const { util.GitHubVariant.DOTCOM, SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion features, - getRunnerLogger(true), + new RecordingLogger(), false, ); t.assert(toolcache.find("CodeQL", expectedToolcacheVersion)); @@ -338,9 +403,10 @@ for (const toolcacheVersion of [ util.GitHubVariant.DOTCOM, SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion features, - getRunnerLogger(true), + new RecordingLogger(), false, ); t.is( @@ -382,9 +448,10 @@ test.serial( ], }, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion features, - getRunnerLogger(true), + new RecordingLogger(), false, ); t.deepEqual(result.toolsVersion, "0.0.0-20200601"); @@ -428,9 +495,10 @@ test.serial( ], }, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion features, - getRunnerLogger(true), + new RecordingLogger(), false, ); t.deepEqual(result.toolsVersion, defaults.cliVersion); @@ -467,9 +535,10 @@ test.serial( util.GitHubVariant.DOTCOM, SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion features, - getRunnerLogger(true), + new RecordingLogger(), false, ); t.deepEqual(result.toolsVersion, defaults.cliVersion); @@ -508,9 +577,10 @@ test.serial( util.GitHubVariant.DOTCOM, SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion features, - getRunnerLogger(true), + new RecordingLogger(), false, ); @@ -595,7 +665,7 @@ const injectedConfigMacro = makeMacro({ tempDir, }; thisStubConfig.computedConfig = generateCodeScanningConfig( - getRunnerLogger(true), + new RecordingLogger(), thisStubConfig.originalUserInput, augmentationProperties, ); @@ -970,7 +1040,7 @@ test.serial("runTool summarizes autobuilder errors", async (t) => { [2019-09-18 12:00:01] [autobuild] A non-error message `; stubToolRunnerConstructor(1, stderr); - const codeqlObject = await codeql.getCodeQLForTesting(); + const codeqlObject = await getCodeQLForTesting(); sinon.stub(codeqlObject, "getVersion").resolves(makeVersionInfo("2.17.6")); sinon.stub(codeqlObject, "resolveExtractor").resolves("/path/to/extractor"); // io throws because of the test CodeQL object. @@ -1026,7 +1096,7 @@ test.serial("runTool recognizes fatal internal errors", async (t) => { com.semmle.util.exception.CatastrophicError: An error occurred while evaluating ControlFlowGraph::ControlFlow::Root.isRootOf/1#dispred#f610e6ed/2@86282cc8 Severe disk cache trouble (corruption or out of space) at /home/runner/work/_temp/codeql_databases/go/db-go/default/cache/pages/28/33.pack: Failed to write item to disk`; stubToolRunnerConstructor(1, stderr); - const codeqlObject = await codeql.getCodeQLForTesting(); + const codeqlObject = await getCodeQLForTesting(); sinon.stub(codeqlObject, "getVersion").resolves(makeVersionInfo("2.17.6")); sinon.stub(codeqlObject, "resolveExtractor").resolves("/path/to/extractor"); // io throws because of the test CodeQL object. diff --git a/src/codeql.ts b/src/codeql.ts index 117b0d8e65..c142c537af 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -4,6 +4,7 @@ import * as path from "path"; import * as core from "@actions/core"; import * as toolrunner from "@actions/exec/lib/toolrunner"; import * as yaml from "js-yaml"; +import * as semver from "semver"; import { CommandInvocationError, @@ -15,9 +16,11 @@ import * as api from "./api-client"; import * as outputCache from "./cli/output-cache"; import type { VersionInfo } from "./cli/types"; import { CliError, wrapCliConfigurationError } from "./cli-errors"; +import type { ActionConfig } from "./config/action-config"; import { appendExtraQueryExclusions, type Config } from "./config-utils"; import { DocUrl } from "./doc-url"; -import { EnvVar, getEnv } from "./environment"; +import { EnvVar, getEnv, Env, ReadOnlyEnv } from "./environment"; +import { getErrorMessage, isDiskConfigurationError } from "./errors"; import { CodeQLDefaultVersionInfo, Feature, @@ -25,7 +28,7 @@ import { } from "./feature-flags"; import { isAnalyzingDefaultBranch } from "./git-utils"; import { Language } from "./languages"; -import { getRunnerLogger, Logger } from "./logging"; +import type { Logger } from "./logging"; import { writeBaseDatabaseOidsFile, writeOverlayChangesFile } from "./overlay"; import { OverlayDatabaseMode } from "./overlay/overlay-database-mode"; import * as setupCodeql from "./setup-codeql"; @@ -33,7 +36,9 @@ import { ToolsDownloadStatusReport } from "./tools-download"; import { ToolsFeature, isSupportedToolsFeature } from "./tools-features"; import { shouldEnableIndirectTracing } from "./tracer-config"; import * as util from "./util"; -import { BuildMode, CleanupLevel, getErrorMessage } from "./util"; +import { BuildMode, CleanupLevel } from "./util"; + +export { isDiskConfigurationError } from "./errors"; type Options = Array; @@ -69,6 +74,11 @@ export interface CodeQL { * Get a string containing the semver version of the CodeQL executable. */ getVersion(): Promise; + /** + * Determines whether the CLI installation represented by this {@link CodeQL} instance + * has at least the {@link requiredVersion}. + */ + isVersionAtLeast(requiredVersion: string): Promise; /** * Print version information about CodeQL. */ @@ -197,7 +207,8 @@ export interface CodeQL { diagnosticsExport( sarifFile: string, automationDetailsId: string | undefined, - config: Config, + config: ActionConfig<"tempDir">, + diagnosticDir: string | undefined, ): Promise; /** Get the location of an extractor for the specified language. */ resolveExtractor(language: Language): Promise; @@ -253,46 +264,26 @@ let cachedCodeQL: CodeQL | undefined = undefined; * The version flags below can be used to conditionally enable certain features * on versions newer than this. */ -const CODEQL_MINIMUM_VERSION = "2.19.4"; +const CODEQL_MINIMUM_VERSION = "2.20.7"; /** * This version will shortly become the oldest version of CodeQL that the Action will run with. */ -const CODEQL_NEXT_MINIMUM_VERSION = "2.20.7"; +const CODEQL_NEXT_MINIMUM_VERSION = "2.22.4"; /** * This is the version of GHES that was most recently deprecated. */ -const GHES_VERSION_MOST_RECENTLY_DEPRECATED = "3.16"; +const GHES_VERSION_MOST_RECENTLY_DEPRECATED = "3.18"; /** * This is the deprecation date for the version of GHES that was most recently deprecated. */ -const GHES_MOST_RECENT_DEPRECATION_DATE = "2026-07-01"; +const GHES_MOST_RECENT_DEPRECATION_DATE = "2026-10-16"; /** The CLI verbosity level to use for extraction in debug mode. */ const EXTRACTION_DEBUG_MODE_VERBOSITY = "progress++"; -/** - * Decides whether `e` is a disk-related error outside of our control - * that should be classified as a `ConfigurationError`. - * - * @param e The error to check. - * @returns True if the error should be treated as a `ConfigurationError` or false if not. - */ -export function isDiskConfigurationError(e: unknown): boolean { - if (!(e instanceof Error)) { - return false; - } - - return ( - // out of disk space - e.message.includes("ENOSPC") || - // access denied - e.message.includes("EACCES") - ); -} - /** * Set up CodeQL CLI access. * @@ -302,6 +293,9 @@ export function isDiskConfigurationError(e: unknown): boolean { * @param variant * @param defaultCliVersion * @param rawLanguages Raw set of languages. + * @param otherLanguagePacksReason Why the CodeQL CLI may need packs for languages other than + * `rawLanguages`, or `undefined` if it won't. If defined, the combined bundle is used. See + * `PerLanguageBundleOptions.otherLanguagePacksReason`. * @param useOverlayAwareDefaultCliVersion Whether to select an overlay-aware default CLI version. * @param features Information about the features that are enabled. * @param logger @@ -316,6 +310,7 @@ export async function setupCodeQL( variant: util.GitHubVariant, defaultCliVersion: CodeQLDefaultVersionInfo, rawLanguages: string[] | undefined, + otherLanguagePacksReason: string | undefined, useOverlayAwareDefaultCliVersion: boolean, features: FeatureEnablement, logger: Logger, @@ -339,6 +334,7 @@ export async function setupCodeQL( variant, defaultCliVersion, rawLanguages, + otherLanguagePacksReason, useOverlayAwareDefaultCliVersion, features, logger, @@ -396,9 +392,9 @@ export function setCodeQL(codeql: Partial): void { cachedCodeQL = createStubCodeQL(codeql); } -function resolveFunction( +function resolveFunction( partialCodeql: Partial, - methodName: string, + methodName: K, defaultImplementation?: T, ): T { if (typeof partialCodeql[methodName] !== "function") { @@ -408,7 +404,7 @@ function resolveFunction( const dummyMethod = () => { throw new Error(`CodeQL ${methodName} method not correctly defined`); }; - return dummyMethod as T; + return dummyMethod as unknown as T; } return partialCodeql[methodName] as T; } @@ -425,6 +421,19 @@ export function createStubCodeQL(partialCodeql: Partial): CodeQL { getVersion: resolveFunction(partialCodeql, "getVersion", async () => ({ version: "1.0.0", })), + isVersionAtLeast: resolveFunction( + partialCodeql, + "isVersionAtLeast", + async (requiredVersion) => { + return ( + !!partialCodeql.getVersion && + semver.gte( + (await partialCodeql.getVersion()).version, + requiredVersion, + ) + ); + }, + ), printVersion: resolveFunction(partialCodeql, "printVersion"), supportsFeature: resolveFunction( partialCodeql, @@ -480,18 +489,6 @@ export function createStubCodeQL(partialCodeql: Partial): CodeQL { }; } -/** - * Get a real, newly created CodeQL instance for testing. The instance refers to - * a non-existent placeholder codeql command, so tests that use this function - * should also stub the toolrunner.ToolRunner constructor. - */ -export async function getCodeQLForTesting( - cmd = "codeql-for-testing", - logger: Logger = getRunnerLogger(true), -): Promise { - return getCodeQLForCmd(logger, cmd, false); -} - /** * Return a CodeQL object for CodeQL CLI access. * @@ -500,29 +497,39 @@ export async function getCodeQLForTesting( * version requirement. Must be set to true outside tests. * @returns A new CodeQL object */ -async function getCodeQLForCmd( +export async function getCodeQLForCmd( logger: Logger, cmd: string, checkVersion: boolean, + env: Env = getEnv(), ): Promise { const codeql: CodeQL = { getPath() { return cmd; }, async getVersion() { - let result = outputCache.getCachedCodeQlVersion(logger, getEnv(), cmd); + const cacheFilePath = outputCache.getCommandCacheFilePath(env); + let result = outputCache.getCachedCodeQlVersion( + logger, + cacheFilePath, + cmd, + ); if (result === undefined) { result = await runCliJson( + env, cmd, ["version", "--format=json"], { noStreamStdout: true, }, ); - outputCache.cacheCodeQlVersion(getEnv(), cmd, result); + outputCache.cacheCodeQlVersion(cacheFilePath, cmd, result); } return result; }, + async isVersionAtLeast(requiredVersion: string) { + return semver.gte((await this.getVersion()).version, requiredVersion); + }, async printVersion() { // Reuse the cached version information rather than invoking the CLI again. core.info(JSON.stringify(await this.getVersion(), null, 2)); @@ -596,6 +603,7 @@ async function getCodeQLForCmd( : ["--no-calculate-baseline"]; await runCli( + env, cmd, [ "database", @@ -631,7 +639,7 @@ async function getCodeQLForCmd( } }, async runAutobuild(config: Config, language: Language) { - applyAutobuildAzurePipelinesTimeoutFix(); + applyAutobuildAzurePipelinesTimeoutFix(env); const autobuildCmd = path.join( await this.resolveExtractor(language), @@ -641,8 +649,11 @@ async function getCodeQLForCmd( // Bump the verbosity of the autobuild command if we're in debug mode if (config.debugMode) { - process.env[EnvVar.CLI_VERBOSITY] = - process.env[EnvVar.CLI_VERBOSITY] || EXTRACTION_DEBUG_MODE_VERBOSITY; + env.set( + EnvVar.CLI_VERBOSITY, + env.getOptional(EnvVar.CLI_VERBOSITY) ?? + EXTRACTION_DEBUG_MODE_VERBOSITY, + ); } // On macOS, System Integrity Protection (SIP) typically interferes with @@ -659,10 +670,10 @@ async function getCodeQLForCmd( // When `DYLD_INSERT_LIBRARIES` is set in the environment for a step, // the Actions runtime introduces its own workaround for SIP // (https://github.com/actions/runner/pull/416). - await runCli(autobuildCmd); + await runCli(env, autobuildCmd); }, async extractScannedLanguage(config: Config, language: Language) { - await runCli(cmd, [ + await runCli(env, cmd, [ "database", "trace-command", "--index-traceless-dbs", @@ -674,10 +685,10 @@ async function getCodeQLForCmd( }, async extractUsingBuildMode(config: Config, language: Language) { if (config.buildMode === BuildMode.Autobuild) { - applyAutobuildAzurePipelinesTimeoutFix(); + applyAutobuildAzurePipelinesTimeoutFix(env); } try { - await runCli(cmd, [ + await runCli(env, cmd, [ "database", "trace-command", "--use-build-mode", @@ -716,7 +727,7 @@ async function getCodeQLForCmd( ...getExtraOptionsFromEnv(["database", "finalize"]), databasePath, ]; - await runCli(cmd, args); + await runCli(env, cmd, args); }, async resolveLanguages( { @@ -725,7 +736,7 @@ async function getCodeQLForCmd( filterToLanguagesWithQueries: boolean; } = { filterToLanguagesWithQueries: false }, ) { - return runCliJson(cmd, [ + return runCliJson(env, cmd, [ "resolve", "languages", "--format=betterjson", @@ -754,7 +765,11 @@ async function getCodeQLForCmd( if (workingDir !== undefined) { codeqlArgs.push("--working-dir", workingDir); } - return await runCliJson(cmd, codeqlArgs); + return await runCliJson( + env, + cmd, + codeqlArgs, + ); }, async databaseRunQueries( databasePath: string, @@ -773,7 +788,7 @@ async function getCodeQLForCmd( ignoringOptions: ["--expect-discarded-cache"], }), ]; - await runCli(cmd, codeqlArgs); + await runCli(env, cmd, codeqlArgs); }, async databaseInterpretResults( databasePath: string, @@ -806,7 +821,7 @@ async function getCodeQLForCmd( "--sarif-group-rules-by-pack", "--sarif-include-query-help=always", "--sublanguage-file-coverage", - ...(await getJobRunUuidSarifOptions()), + ...(await getJobRunUuidSarifOptions(env)), ...getExtraOptionsFromEnv(["database", "interpret-results"]), ]; if (sarifRunPropertyFlag !== undefined) { @@ -826,7 +841,7 @@ async function getCodeQLForCmd( } // Capture the stdout, which contains the analysis summary. Don't stream it to the Actions // logs to avoid printing it twice. - return await runCli(cmd, codeqlArgs, { + return await runCli(env, cmd, codeqlArgs, { noStreamStdout: true, }); }, @@ -843,7 +858,7 @@ async function getCodeQLForCmd( `--cache-cleanup=${cleanupLevel}`, ...getExtraOptionsFromEnv(["database", "cleanup"]), ]; - await runCli(cmd, codeqlArgs); + await runCli(env, cmd, codeqlArgs); } }, async databaseBundle( @@ -877,7 +892,9 @@ async function getCodeQLForCmd( ]), ); } - await new toolrunner.ToolRunner(cmd, args).exec(); + await new toolrunner.ToolRunner(cmd, args, { + env: env.getDefined(), + }).exec(); }, async databaseExportDiagnostics( databasePath: string, @@ -898,27 +915,59 @@ async function getCodeQLForCmd( if (automationDetailsId !== undefined) { args.push("--sarif-category", automationDetailsId); } - await new toolrunner.ToolRunner(cmd, args).exec(); + await new toolrunner.ToolRunner(cmd, args, { + env: env.getDefined(), + }).exec(); }, async diagnosticsExport( sarifFile: string, automationDetailsId: string | undefined, - config: Config, + config: ActionConfig<"tempDir">, + diagnosticDir: string | undefined, ): Promise { + // We may be exporting diagnostics for a failed SARIF, in which case the configuration + // file may not have been written to disk and there may not be a database. The CLI + // will produce a SARIF for diagnostics from `diagnosticDir` without it. Therefore, + // we check whether `configPath` exists and only provide it to the CLI if it does. + // Although not needed, the CLI will produce an error if it + // is provided with an argument to `--sarif-codescanning-config` that does not exist. + let configPath: string | undefined = + getGeneratedCodeScanningConfigPath(config); + + if (!fs.existsSync(configPath)) { + // Warn if there is no configuration file, even though `config` claims that `init` + // was successful. This shouldn't be happening. + if (config.successfullyInitialised) { + logger.warning( + [ + `Expected a configuration file at '${configPath}', which does not exist.`, + "Continuing with diagnostics export anyway, without a configuration file.", + ].join(" "), + ); + } + + configPath = undefined; + } + const args = [ "diagnostics", "export", "--format=sarif-latest", `--output=${sarifFile}`, - `--sarif-codescanning-config=${getGeneratedCodeScanningConfigPath( - config, - )}`, + ...(configPath !== undefined + ? [`--sarif-codescanning-config=${configPath}`] + : []), + ...(diagnosticDir !== undefined + ? [`--diagnostic-dir=${diagnosticDir}`] + : []), ...getExtraOptionsFromEnv(["diagnostics", "export"]), ]; if (automationDetailsId !== undefined) { args.push("--sarif-category", automationDetailsId); } - await new toolrunner.ToolRunner(cmd, args).exec(); + await new toolrunner.ToolRunner(cmd, args, { + env: env.getDefined(), + }).exec(); }, async resolveExtractor(language: Language): Promise { // Request it using `format=json` so we don't need to strip the trailing new line generated by @@ -932,9 +981,11 @@ async function getCodeQLForCmd( "--format=json", `--language=${language}`, "--extractor-include-aliases", + "-J-XX:-UsePerfData", ...getExtraOptionsFromEnv(["resolve", "extractor"]), ], { + env: env.getDefined(), silent: true, listeners: { stdout: (data) => { @@ -946,7 +997,13 @@ async function getCodeQLForCmd( }, }, ).exec(); - return JSON.parse(extractorPath) as string; + try { + return JSON.parse(extractorPath) as string; + } catch (err) { + throw new Error( + `Failed to parse extractor path for '${language}' from CLI: ${getErrorMessage(err)}\nOutput was: ${extractorPath}`, + ); + } }, async resolveQueriesStartingPacks(queries: string[]): Promise { const codeqlArgs = [ @@ -956,7 +1013,7 @@ async function getCodeQLForCmd( ...getExtraOptionsFromEnv(["resolve", "queries"]), ...queries, ]; - return await runCliJson(cmd, codeqlArgs, { + return await runCliJson(env, cmd, codeqlArgs, { noStreamStdout: true, }); }, @@ -970,7 +1027,7 @@ async function getCodeQLForCmd( "--format=json", ...getExtraOptionsFromEnv(["resolve", "database"]), ]; - return await runCliJson(cmd, codeqlArgs, { + return await runCliJson(env, cmd, codeqlArgs, { noStreamStdout: true, }); }, @@ -997,7 +1054,7 @@ async function getCodeQLForCmd( args.push("--sarif-merge-runs-from-equal-category"); } - await runCli(cmd, args); + await runCli(env, cmd, args); }, }; // To ensure that status reports include the CodeQL CLI version wherever @@ -1010,7 +1067,7 @@ async function getCodeQLForCmd( // CodeQL object is created. if ( checkVersion && - !(await util.codeQlVersionAtLeast(codeql, CODEQL_MINIMUM_VERSION)) + !(await codeql.isVersionAtLeast(CODEQL_MINIMUM_VERSION)) ) { throw new util.ConfigurationError( `Expected a CodeQL CLI with version at least ${CODEQL_MINIMUM_VERSION} but got version ${ @@ -1019,8 +1076,8 @@ async function getCodeQLForCmd( ); } else if ( checkVersion && - process.env[EnvVar.SUPPRESS_DEPRECATED_SOON_WARNING] !== "true" && - !(await util.codeQlVersionAtLeast(codeql, CODEQL_NEXT_MINIMUM_VERSION)) + env.getOptional(EnvVar.SUPPRESS_DEPRECATED_SOON_WARNING) !== "true" && + !(await codeql.isVersionAtLeast(CODEQL_NEXT_MINIMUM_VERSION)) ) { const result = await codeql.getVersion(); core.warning( @@ -1037,7 +1094,7 @@ async function getCodeQLForCmd( }' by 'github/codeql-action/*@v${getActionVersion()}' in your code scanning workflow to ` + "continue using this version of the CodeQL Action.", ); - core.exportVariable(EnvVar.SUPPRESS_DEPRECATED_SOON_WARNING, "true"); + env.export(EnvVar.SUPPRESS_DEPRECATED_SOON_WARNING, "true"); } return codeql; } @@ -1114,12 +1171,13 @@ export function getExtraOptions( } async function runCli( + env: ReadOnlyEnv, cmd: string, args: string[] = [], opts: { stdin?: string; noStreamStdout?: boolean } = {}, ): Promise { try { - return await runTool(cmd, args, opts); + return await runTool(env, cmd, args, opts); } catch (e) { if (e instanceof CommandInvocationError) { throw wrapCliConfigurationError(new CliError(e)); @@ -1130,6 +1188,8 @@ async function runCli( /** * Wraps the command executor {@link runCli} and tries to parse the output as JSON. + * + * @param env The environment variables. * @param cmd The command to run. * @param args The arguments to pass to the command. * @param opts The options for running the command. @@ -1138,11 +1198,12 @@ async function runCli( * @returns The parsed JSON output from the command. */ async function runCliJson( + env: ReadOnlyEnv, cmd: string, args: string[] = [], opts: { stdin?: string; noStreamStdout?: boolean } = {}, ): Promise { - const output = await runCli(cmd, args, opts); + const output = await runCli(env, cmd, args, opts); try { return JSON.parse(output) as T; } catch (e) { @@ -1207,7 +1268,7 @@ export async function getTrapCachingExtractorConfigArgsForLang( ): Promise { const cacheDir = config.trapCaches[language]; if (cacheDir === undefined) return []; - const write = await isAnalyzingDefaultBranch(); + const write = await isAnalyzingDefaultBranch(getEnv(), config.repositoryRoot); return [ `-O=${language}.trap.cache.dir=${cacheDir}`, `-O=${language}.trap.cache.bound=${TRAP_CACHE_SIZE_MB}`, @@ -1220,7 +1281,9 @@ export async function getTrapCachingExtractorConfigArgsForLang( * * This will not exist if the configuration is being parsed in the Action. */ -function getGeneratedCodeScanningConfigPath(config: Config): string { +function getGeneratedCodeScanningConfigPath( + config: ActionConfig<"tempDir">, +): string { return path.resolve(config.tempDir, "user-config.yaml"); } @@ -1239,17 +1302,20 @@ function getExtractionVerbosityArguments( * Without the fix, long build processes will timeout when pulling down Java packages * https://developercommunity.visualstudio.com/content/problem/292284/maven-hosted-agent-connection-timeout.html */ -function applyAutobuildAzurePipelinesTimeoutFix() { - const javaToolOptions = process.env["JAVA_TOOL_OPTIONS"] || ""; - process.env["JAVA_TOOL_OPTIONS"] = [ - ...javaToolOptions.split(/\s+/), - "-Dhttp.keepAlive=false", - "-Dmaven.wagon.http.pool=false", - ].join(" "); +function applyAutobuildAzurePipelinesTimeoutFix(env: Env) { + const javaToolOptions = env.getOptional("JAVA_TOOL_OPTIONS") ?? ""; + env.set( + "JAVA_TOOL_OPTIONS", + [ + ...javaToolOptions.split(/\s+/), + "-Dhttp.keepAlive=false", + "-Dmaven.wagon.http.pool=false", + ].join(" "), + ); } -async function getJobRunUuidSarifOptions() { - const jobRunUuid = process.env[EnvVar.JOB_RUN_UUID]; +async function getJobRunUuidSarifOptions(env: ReadOnlyEnv) { + const jobRunUuid = env.getOptional(EnvVar.JOB_RUN_UUID); return jobRunUuid ? [`--sarif-run-property=jobRunUuid=${jobRunUuid}`] : []; } diff --git a/src/config-utils.test.ts b/src/config-utils.test.ts index 29d72f3af4..b66d4a797e 100644 --- a/src/config-utils.test.ts +++ b/src/config-utils.test.ts @@ -21,7 +21,6 @@ import { RepositoryProperties } from "./feature-flags/properties"; import * as gitUtils from "./git-utils"; import { GitVersionInfo } from "./git-utils"; import { BuiltInLanguage, Language } from "./languages"; -import { getRunnerLogger } from "./logging"; import { CODEQL_OVERLAY_MINIMUM_VERSION } from "./overlay"; import * as overlayDiagnostics from "./overlay/diagnostics"; import { OverlayDisabledReason } from "./overlay/diagnostics"; @@ -42,6 +41,7 @@ import { callee, SAMPLE_DOTCOM_API_DETAILS, AssertableTarget, + RecordingLogger, } from "./testing-utils"; import { GitHubVariant, @@ -102,7 +102,7 @@ function createTestInitConfigInputs( features: createFeatures([]), repositoryProperties: {}, enableFileCoverageInformation: true, - logger: getRunnerLogger(true), + logger: new RecordingLogger(), } satisfies configUtils.InitConfigInputs, overrides, ); @@ -150,7 +150,7 @@ function mockListLanguages(languages: string[]) { test.serial("load empty config", async (t) => { return await withTmpDir(async (tempDir) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const languages = "javascript,python"; setupActionsVars(tempDir, tempDir); @@ -172,6 +172,7 @@ test.serial("load empty config", async (t) => { createTestInitConfigInputs({ languagesInput: languages, repository: { owner: "github", repo: "example" }, + sourceRoot: tempDir, tempDir, codeql, logger, @@ -186,6 +187,7 @@ test.serial("load empty config", async (t) => { logger, }), {}, + undefined, ); t.deepEqual(config, expectedConfig); @@ -194,7 +196,7 @@ test.serial("load empty config", async (t) => { test.serial("load code quality config", async (t) => { return await withTmpDir(async (tempDir) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const languages = "actions"; setupActionsVars(tempDir, tempDir); @@ -216,6 +218,7 @@ test.serial("load code quality config", async (t) => { analysisKinds: [AnalysisKind.CodeQuality], languagesInput: languages, repository: { owner: "github", repo: "example" }, + sourceRoot: tempDir, tempDir, codeql, logger, @@ -249,7 +252,7 @@ test.serial( "initActionState doesn't throw if there are queries configured in the repository properties", async (t) => { return await withTmpDir(async (tempDir) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const languages = "javascript"; setupActionsVars(tempDir, tempDir); @@ -296,6 +299,7 @@ test.serial( analysisKinds: [AnalysisKind.CodeQuality], languagesInput: languages, repository: { owner: "github", repo: "example" }, + sourceRoot: tempDir, tempDir, codeql, repositoryProperties, @@ -311,7 +315,7 @@ test.serial( test.serial("loading a saved config produces the same config", async (t) => { return await withTmpDir(async (tempDir) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const codeql = createStubCodeQL({ async resolveLanguages() { @@ -359,7 +363,7 @@ test.serial("loading a saved config produces the same config", async (t) => { test.serial("loading config with version mismatch throws", async (t) => { return await withTmpDir(async (tempDir) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const codeql = createStubCodeQL({ async resolveLanguages() { @@ -473,6 +477,12 @@ const simpleConfigFileContents = ` queries: - uses: ./foo_file`; +/** The configuration in `simpleConfigFileContents`. */ +const simpleConfigInput: UserConfig = { + name: "my config", + queries: [{ uses: "./foo_file" }], +}; + /** A less minimal configuration file. */ const otherConfigFileContents = ` name: my config @@ -512,6 +522,7 @@ test.serial("load non-empty input", async (t) => { // And the config we expect it to parse to const expectedConfig = createTestConfig({ languages: [BuiltInLanguage.javascript], + repositoryRoot: undefined, buildMode: BuildMode.None, originalUserInput: userConfig, computedConfig: userConfig, @@ -532,6 +543,7 @@ test.serial("load non-empty input", async (t) => { state, createTestInitConfigInputs({ languagesInput, + sourceRoot: tempDir, buildModeInput: "none", configFile: configFilePath, debugArtifactName: "my-artifact", @@ -558,16 +570,14 @@ test.serial( tempDir, ); - const configInput = ` - name: my config - queries: - - uses: ./foo - packs: - javascript: - - a/b@1.2.3 - python: - - c/d@1.2.3 - `; + const configInput: UserConfig = { + name: "my config", + queries: [{ uses: "./foo" }], + packs: { + javascript: ["a/b@1.2.3"], + python: ["c/d@1.2.3"], + }, + }; fs.mkdirSync(path.join(tempDir, "foo")); @@ -598,7 +608,16 @@ test.serial( }), ); - t.deepEqual(config.originalUserInput, yaml.load(configInput)); + // Compare with a separate object rather than `configInput` itself, so that the test catches + // changes made to the input in place. + t.deepEqual(config.originalUserInput, { + name: "my config", + queries: [{ uses: "./foo" }], + packs: { + javascript: ["a/b@1.2.3"], + python: ["c/d@1.2.3"], + }, + }); }); }, ); @@ -769,12 +788,12 @@ test.serial("Unknown languages", async (t) => { }); }); -const mockLogger = getRunnerLogger(true); +const mockLogger = new RecordingLogger(); test.serial("no generateRegistries when registries is undefined", async (t) => { return await withTmpDir(async (tmpDir) => { const registriesInput = undefined; - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const { registriesAuthTokens, qlconfigFile } = await configUtils.generateRegistries(registriesInput, tmpDir, logger); @@ -795,7 +814,7 @@ test.serial( token: "not-a-token", }, ]); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const { registriesAuthTokens, qlconfigFile } = await configUtils.generateRegistries(registriesInput, tmpDir, logger); @@ -1092,11 +1111,6 @@ const checkOverlayEnablementMacro = makeMacro({ return lang === BuiltInLanguage.java; }); - // Mock git root detection - if (setup.gitRoot !== undefined) { - sinon.stub(gitUtils, "getGitRoot").resolves(setup.gitRoot); - } - // Mock submodule detection sinon.stub(gitUtils, "hasSubmodules").returns(setup.hasSubmodules); @@ -1109,6 +1123,7 @@ const checkOverlayEnablementMacro = makeMacro({ codeql, features, setup.languages, + setup.gitRoot, // repositoryRoot tempDir, // sourceRoot setup.buildMode, undefined, @@ -2111,7 +2126,7 @@ test.serial("getPrimaryAnalysisConfig - Code Scanning + Code Quality", (t) => { }); test.serial( - "isTrapCachingEnabled: explicit input true is respected", + "isTrapCachingEnabled: explicit true input overrides self-hosted default", async (t) => { return await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); @@ -2119,77 +2134,60 @@ test.serial( .stub(actionsUtil, "getOptionalInput") .withArgs("trap-caching") .returns("true"); - t.true( - await configUtils.isTrapCachingEnabled( - createFeatures([]), - OverlayDatabaseMode.None, - ), - ); + t.true(configUtils.isTrapCachingEnabled(OverlayDatabaseMode.None)); }); }, ); test.serial( - "isTrapCachingEnabled: disabled on self-hosted runner by default", + "isTrapCachingEnabled: explicit true input overrides overlay defaults", async (t) => { return await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + setupActionsVars(tmpDir, path.join(tmpDir, "hostedtoolcache")); sinon .stub(actionsUtil, "getOptionalInput") .withArgs("trap-caching") - .returns(undefined); - t.false( - await configUtils.isTrapCachingEnabled( - createFeatures([]), - OverlayDatabaseMode.None, - ), - ); + .returns("true"); + for (const overlayDatabaseMode of [ + OverlayDatabaseMode.Overlay, + OverlayDatabaseMode.OverlayBase, + ]) { + t.true(configUtils.isTrapCachingEnabled(overlayDatabaseMode)); + } }); }, ); test.serial( - "isTrapCachingEnabled: enabled on hosted runner by default", + "isTrapCachingEnabled: explicit false input overrides hosted default", async (t) => { return await withTmpDir(async (tmpDir) => { - const hostedToolCache = path.join(tmpDir, "hostedtoolcache"); - setupActionsVars(tmpDir, hostedToolCache); + setupActionsVars(tmpDir, path.join(tmpDir, "hostedtoolcache")); sinon .stub(actionsUtil, "getOptionalInput") .withArgs("trap-caching") - .returns(undefined); - t.true( - await configUtils.isTrapCachingEnabled( - createFeatures([]), - OverlayDatabaseMode.None, - ), - ); + .returns("false"); + t.false(configUtils.isTrapCachingEnabled(OverlayDatabaseMode.None)); }); }, ); test.serial( - "isTrapCachingEnabled: enabled on hosted runner when overlay enabled but feature flag off", + "isTrapCachingEnabled: disabled on self-hosted runner by default", async (t) => { return await withTmpDir(async (tmpDir) => { - const hostedToolCache = path.join(tmpDir, "hostedtoolcache"); - setupActionsVars(tmpDir, hostedToolCache); + setupActionsVars(tmpDir, tmpDir); sinon .stub(actionsUtil, "getOptionalInput") .withArgs("trap-caching") .returns(undefined); - t.true( - await configUtils.isTrapCachingEnabled( - createFeatures([]), - OverlayDatabaseMode.Overlay, - ), - ); + t.false(configUtils.isTrapCachingEnabled(OverlayDatabaseMode.None)); }); }, ); test.serial( - "isTrapCachingEnabled: disabled on hosted runner when overlay enabled and feature flag on", + "isTrapCachingEnabled: enabled on hosted runner without overlay analysis", async (t) => { return await withTmpDir(async (tmpDir) => { const hostedToolCache = path.join(tmpDir, "hostedtoolcache"); @@ -2198,18 +2196,13 @@ test.serial( .stub(actionsUtil, "getOptionalInput") .withArgs("trap-caching") .returns(undefined); - t.false( - await configUtils.isTrapCachingEnabled( - createFeatures([Feature.OverlayAnalysisDisableTrapCaching]), - OverlayDatabaseMode.Overlay, - ), - ); + t.true(configUtils.isTrapCachingEnabled(OverlayDatabaseMode.None)); }); }, ); test.serial( - "isTrapCachingEnabled: enabled on hosted runner when overlay is None even with feature flag on", + "isTrapCachingEnabled: disabled on hosted runner with overlay analysis", async (t) => { return await withTmpDir(async (tmpDir) => { const hostedToolCache = path.join(tmpDir, "hostedtoolcache"); @@ -2218,12 +2211,12 @@ test.serial( .stub(actionsUtil, "getOptionalInput") .withArgs("trap-caching") .returns(undefined); - t.true( - await configUtils.isTrapCachingEnabled( - createFeatures([Feature.OverlayAnalysisDisableTrapCaching]), - OverlayDatabaseMode.None, - ), - ); + for (const overlayDatabaseMode of [ + OverlayDatabaseMode.Overlay, + OverlayDatabaseMode.OverlayBase, + ]) { + t.false(configUtils.isTrapCachingEnabled(overlayDatabaseMode)); + } }); }, ); @@ -2232,7 +2225,7 @@ test("applyIncrementalAnalysisSettings: no-op when mode is not Overlay and diff const config = createTestConfig({}); config.overlayDatabaseMode = OverlayDatabaseMode.None; const codeql = createStubCodeQL({}); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); await configUtils.applyIncrementalAnalysisSettings( config, @@ -2250,7 +2243,7 @@ test("applyIncrementalAnalysisSettings: keeps overlay mode and adds exclusions w overlayDatabaseMode: OverlayDatabaseMode.Overlay, }); const codeql = createStubCodeQL({}); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); await configUtils.applyIncrementalAnalysisSettings( config, @@ -2273,7 +2266,7 @@ test.serial( }); config.useOverlayDatabaseCaching = true; const codeql = createStubCodeQL({}); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const addDiagnosticsStub = sinon .stub(overlayDiagnostics, "addOverlayDisablementDiagnostics") .resolves(); @@ -2305,7 +2298,7 @@ test.serial( config.useOverlayDatabaseCaching = false; config.overlayModeSetExplicitly = true; const codeql = createStubCodeQL({}); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const addDiagnosticsStub = sinon .stub(overlayDiagnostics, "addOverlayDisablementDiagnostics") .resolves(); @@ -2328,7 +2321,7 @@ test("applyIncrementalAnalysisSettings: adds exclusions for diff-informed-only r const config = createTestConfig({}); config.overlayDatabaseMode = OverlayDatabaseMode.None; const codeql = createStubCodeQL({}); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); await configUtils.applyIncrementalAnalysisSettings( config, @@ -2413,7 +2406,7 @@ test("determineUserConfig - loads config input", async (t) => { const expectedConfigPath = configUtils.userConfigFromActionPath(tmpDir); const inputs = createTestInitConfigInputs({ - configInput: simpleConfigFileContents, + configInput: simpleConfigInput, configFile: undefined, workspacePath: tmpDir, }); @@ -2423,17 +2416,15 @@ test("determineUserConfig - loads config input", async (t) => { await target // The input source and path of the generated config file should have been logged. - .logs( - t, - "Using config from action input:", - `Using configuration file: ${expectedConfigPath}`, - ) - // The message about no configuration input and - // the warning about both inputs should not have been logged. + .logs(t, `Using config from action input: ${expectedConfigPath}`) + // The message about no configuration input and the warning about both inputs should not have + // been logged. The generated config file isn't loaded, since the `config` input has already + // been parsed. .notLogs( t, "No configuration file was provided", "Both a config file and config input were provided. Ignoring config file.", + `Using configuration file: ${expectedConfigPath}`, ) // The loaded configuration should match `simpleConfigFileContents`. .passes(t.deepEqual, { @@ -2452,7 +2443,7 @@ test("determineUserConfig - ignores config file input when both specified", asyn const expectedConfigPath = configUtils.userConfigFromActionPath(tmpDir); const inputs = createTestInitConfigInputs({ - configInput: simpleConfigFileContents, + configInput: simpleConfigInput, configFile: configFilePath, workspacePath: tmpDir, }); @@ -2466,10 +2457,14 @@ test("determineUserConfig - ignores config file input when both specified", asyn .logs( t, `Using config from action input: ${expectedConfigPath}`, - `Using configuration file: ${expectedConfigPath}`, "Both a config file and config input were provided. Ignoring config file.", ) - .notLogs(t, "No configuration file was provided") + // The generated config file isn't loaded, since the `config` input has already been parsed. + .notLogs( + t, + "No configuration file was provided", + `Using configuration file: ${expectedConfigPath}`, + ) // The loaded configuration should match `simpleConfigFileContents`. .passes(t.deepEqual, { name: "my config", @@ -2482,11 +2477,14 @@ test("determineUserConfig - ignores config file input when both specified", asyn }); /** A `config` input that we might get from Default Setup. */ -const defaultSetupConfigInput = ` - threat-models: [local, remote] - default-setup: - org: - model-packs: [foo, bar]`; +const defaultSetupConfigInput: UserConfig = { + "threat-models": ["local", "remote"], + "default-setup": { + org: { + "model-packs": ["foo", "bar"], + }, + }, +}; test("determineUserConfig - merges configs if FF is enabled in Default Setup", async (t) => { await withTmpDir(async (tmpDir) => { @@ -2537,7 +2535,7 @@ test("determineUserConfig - merges configs if FF is enabled in Default Setup", a // also check whether loading the configuration from disk that was written // by `determineUserConfig` matches our expectations. const loadedFromDisk = configUtils.getLocalConfig( - getRunnerLogger(true), + new RecordingLogger(), expectedConfigPath, false, ); @@ -2555,7 +2553,7 @@ test("determineUserConfig - ignores config file input in Default Setup if FF is .withArgs( tmpDir, createTestInitConfigInputs({ - configInput: simpleConfigFileContents, + configInput: simpleConfigInput, configFile: configFilePath, workspacePath: tmpDir, }), @@ -2565,10 +2563,14 @@ test("determineUserConfig - ignores config file input in Default Setup if FF is .logs( t, `Using config from action input: ${expectedConfigPath}`, - `Using configuration file: ${expectedConfigPath}`, "Both a config file and config input were provided. Ignoring config file.", ) - .notLogs(t, "No configuration file was provided") + // The generated config file isn't loaded, since the `config` input has already been parsed. + .notLogs( + t, + "No configuration file was provided", + `Using configuration file: ${expectedConfigPath}`, + ) .passes(t.deepEqual, { name: "my config", queries: [{ uses: "./foo_file" }], @@ -2587,7 +2589,7 @@ test("determineUserConfig - ignores config file input outside Default Setup if F .withArgs( tmpDir, createTestInitConfigInputs({ - configInput: simpleConfigFileContents, + configInput: simpleConfigInput, configFile: configFilePath, workspacePath: tmpDir, }), @@ -2597,10 +2599,14 @@ test("determineUserConfig - ignores config file input outside Default Setup if F .logs( t, `Using config from action input: ${expectedConfigPath}`, - `Using configuration file: ${expectedConfigPath}`, "Both a config file and config input were provided. Ignoring config file.", ) - .notLogs(t, "No configuration file was provided") + // The generated config file isn't loaded, since the `config` input has already been parsed. + .notLogs( + t, + "No configuration file was provided", + `Using configuration file: ${expectedConfigPath}`, + ) .passes(t.deepEqual, { name: "my config", queries: [{ uses: "./foo_file" }], diff --git a/src/config-utils.ts b/src/config-utils.ts index 0a6ced00aa..b59149e47f 100644 --- a/src/config-utils.ts +++ b/src/config-utils.ts @@ -2,7 +2,6 @@ import * as fs from "fs"; import * as path from "path"; import { performance } from "perf_hooks"; -import * as core from "@actions/core"; import * as yaml from "js-yaml"; import { ActionState } from "./action-common"; @@ -22,7 +21,11 @@ import { import * as api from "./api-client"; import { getCachingKind } from "./caching-utils"; import { type CodeQL } from "./codeql"; -import { type Config } from "./config/action-config"; +import { + type AbortedInitConfig, + type ActionConfig, + type Config, +} from "./config/action-config"; import { calculateAugmentation, ExcludeQueryFilter, @@ -46,7 +49,7 @@ import { makeTelemetryDiagnostic, } from "./diagnostics"; import { prepareDiffInformedAnalysis } from "./diff-informed-analysis-utils"; -import { EnvVar } from "./environment"; +import { EnvVar, exportEnvVar, getEnv } from "./environment"; import * as errorMessages from "./error-messages"; import { Feature, FeatureEnablement, FeatureWithoutCLI } from "./feature-flags"; import { @@ -72,13 +75,13 @@ import { import { OverlayDatabaseMode } from "./overlay/overlay-database-mode"; import { shouldSkipOverlayAnalysis } from "./overlay/status"; import { RepositoryNwo } from "./repository"; +import { ActionName } from "./status-report"; import { ToolsFeature } from "./tools-features"; import { downloadTrapCaches } from "./trap-caching"; import { GitHubVersion, ConfigurationError, BuildMode, - codeQlVersionAtLeast, cloneObject, isDefined, checkDiskUsage, @@ -90,9 +93,8 @@ import { Result, Success, Failure, - isHostedRunner, + looksLikeHostedRunner, } from "./util"; - export { type Config } from "./config/action-config"; /** @@ -338,7 +340,8 @@ export interface InitConfigInputs { packsInput: string | undefined; configFile: string | undefined; dbLocation: string | undefined; - configInput: string | undefined; + /** The configuration from the `config` input. */ + configInput: UserConfig | undefined; buildModeInput: string | undefined; ramInput: string | undefined; dependencyCachingEnabled: string | undefined; @@ -386,6 +389,7 @@ export async function initActionState( enableFileCoverageInformation, }: InitConfigInputs, userConfig: UserConfig, + repositoryRoot: string | undefined, ): Promise { const languages = await getLanguages( codeql, @@ -437,6 +441,7 @@ export async function initActionState( return { version: getActionVersion(), + repositoryRoot, analysisKinds, languages, buildMode, @@ -459,6 +464,8 @@ export async function initActionState( overlayModeSetExplicitly: false, repositoryProperties, enableFileCoverageInformation, + // We don't set this to `true` until `init` is successful. + successfullyInitialised: false, }; } @@ -466,12 +473,18 @@ async function downloadCacheWithTime( codeQL: CodeQL, languages: Language[], logger: Logger, + repositoryRoot: string | undefined, ): Promise<{ trapCaches: { [language: string]: string }; trapCacheDownloadTime: number; }> { const start = performance.now(); - const trapCaches = await downloadTrapCaches(codeQL, languages, logger); + const trapCaches = await downloadTrapCaches( + codeQL, + languages, + logger, + repositoryRoot, + ); const trapCacheDownloadTime = performance.now() - start; return { trapCaches, trapCacheDownloadTime }; } @@ -640,10 +653,7 @@ async function runnerHasSufficientMemory( logger: Logger, ): Promise { if ( - await codeQlVersionAtLeast( - codeql, - CODEQL_VERSION_REDUCED_OVERLAY_MEMORY_USAGE, - ) + await codeql.isVersionAtLeast(CODEQL_VERSION_REDUCED_OVERLAY_MEMORY_USAGE) ) { logger.debug( `Skipping memory check for overlay analysis because CodeQL version is at least ${CODEQL_VERSION_REDUCED_OVERLAY_MEMORY_USAGE}.`, @@ -719,6 +729,7 @@ export async function checkOverlayEnablement( codeql: CodeQL, features: FeatureEnablement, languages: Language[], + repositoryRoot: string | undefined, sourceRoot: string, buildMode: BuildMode | undefined, ramInput: string | undefined, @@ -748,6 +759,7 @@ export async function checkOverlayEnablement( true, codeql, languages, + repositoryRoot, sourceRoot, buildMode, gitVersion, @@ -821,7 +833,7 @@ export async function checkOverlayEnablement( `Setting overlay database mode to ${overlayDatabaseMode} ` + "with caching because we are analyzing a pull request.", ); - } else if (await isAnalyzingDefaultBranch()) { + } else if (await isAnalyzingDefaultBranch(getEnv(), repositoryRoot)) { overlayDatabaseMode = OverlayDatabaseMode.OverlayBase; logger.info( `Setting overlay database mode to ${overlayDatabaseMode} ` + @@ -837,6 +849,7 @@ export async function checkOverlayEnablement( false, codeql, languages, + repositoryRoot, sourceRoot, buildMode, gitVersion, @@ -856,6 +869,7 @@ async function validateOverlayDatabaseMode( overlayModeSetExplicitly: boolean, codeql: CodeQL, languages: Language[], + repositoryRoot: string | undefined, sourceRoot: string, buildMode: BuildMode | undefined, gitVersion: GitVersionInfo | undefined, @@ -883,7 +897,7 @@ async function validateOverlayDatabaseMode( ); return new Failure(OverlayDisabledReason.IncompatibleBuildMode); } - if (!(await codeQlVersionAtLeast(codeql, CODEQL_OVERLAY_MINIMUM_VERSION))) { + if (!(await codeql.isVersionAtLeast(CODEQL_OVERLAY_MINIMUM_VERSION))) { logger.warning( `Cannot build an ${overlayDatabaseMode} database because ` + `the CodeQL CLI is older than ${CODEQL_OVERLAY_MINIMUM_VERSION}. ` + @@ -891,8 +905,7 @@ async function validateOverlayDatabaseMode( ); return new Failure(OverlayDisabledReason.IncompatibleCodeQl); } - const gitRoot = await getGitRoot(sourceRoot); - if (gitRoot === undefined) { + if (repositoryRoot === undefined) { logger.warning( `Cannot build an ${overlayDatabaseMode} database because ` + `the source root "${sourceRoot}" is not inside a git repository. ` + @@ -900,7 +913,7 @@ async function validateOverlayDatabaseMode( ); return new Failure(OverlayDisabledReason.NoGitRoot); } - if (hasSubmodules(gitRoot)) { + if (hasSubmodules(repositoryRoot)) { if (gitVersion === undefined) { logger.warning( `Cannot build an ${overlayDatabaseMode} database because ` + @@ -929,23 +942,23 @@ async function validateOverlayDatabaseMode( }); } -export async function isTrapCachingEnabled( - features: FeatureEnablement, +/** + * Determines whether TRAP caching is enabled for the current run. + * + * @returns Whether TRAP caches should be downloaded and uploaded. + */ +export function isTrapCachingEnabled( overlayDatabaseMode: OverlayDatabaseMode, -): Promise { +): boolean { // If the workflow specified something, always respect that. const trapCaching = getOptionalInput("trap-caching"); if (trapCaching !== undefined) return trapCaching === "true"; // On self-hosted runners which may have slow network access, disable TRAP caching by default. - if (!isHostedRunner()) return false; + if (!looksLikeHostedRunner()) return false; - // If overlay analysis is enabled, then disable TRAP caching since overlay analysis supersedes it. - // This change is gated behind a feature flag. - if ( - overlayDatabaseMode !== OverlayDatabaseMode.None && - (await features.getValue(Feature.OverlayAnalysisDisableTrapCaching)) - ) { + // Overlay analysis supersedes TRAP caching, so disable TRAP caching by default when it is active. + if (overlayDatabaseMode !== OverlayDatabaseMode.None) { return false; } @@ -965,10 +978,10 @@ async function setCppTrapCachingEnvironmentVariables( ); } else if (config.trapCaches[BuiltInLanguage.cpp]) { logger.info("Enabling TRAP caching for C/C++."); - core.exportVariable(envVar, "true"); + exportEnvVar(envVar, "true"); } else { logger.debug(`Disabling TRAP caching for C/C++.`); - core.exportVariable(envVar, "false"); + exportEnvVar(envVar, "false"); } } } @@ -1058,17 +1071,13 @@ export async function determineUserConfig( tempDir: string, inputs: InitConfigInputs, ): Promise { - const validateConfig = await action.features.getValue( - Feature.ValidateDbConfig, - ); - // We have the following cases: // 1. A `config` or `config-file` input is provided, but not both: use the provided one. // 2. Both are provided and we are in an advanced workflow: ignore the `config-file` input. // 3. Both are provided and we are in Default Setup: the `config` input uses a limited // set of options, which are supported by `mergeDefaultSetupAndUserConfigs`, // and we merge the two configs. - if (inputs.configInput) { + if (inputs.configInput !== undefined) { const computedConfigPath = userConfigFromActionPath(tempDir); // Get a function which enables us to determine whether the FF that allows us to @@ -1085,12 +1094,6 @@ export async function determineUserConfig( ) { // If the FF is enabled and we are in Default Setup, combine the supported // configuration file properties and write the result to disk. - const fromConfigInput = parseUserConfig( - action.logger, - "`config` input", - inputs.configInput, - validateConfig, - ); const fromConfigFile = await loadUserConfig( action, inputs.configFile, @@ -1103,7 +1106,7 @@ export async function determineUserConfig( // the CLI or other CodeQL Action steps. const mergedConfig = mergeDefaultSetupAndUserConfigs( action.logger, - fromConfigInput, + inputs.configInput, fromConfigFile, ); fs.writeFileSync(computedConfigPath, yaml.dump(mergedConfig)); @@ -1123,12 +1126,13 @@ export async function determineUserConfig( ); } - // Write the `config` input straight to disk. - fs.writeFileSync(computedConfigPath, inputs.configInput); + // Write the `config` input to disk without merging it with a configuration file. + fs.writeFileSync(computedConfigPath, yaml.dump(inputs.configInput)); inputs.configFile = computedConfigPath; action.logger.debug( `Using config from action input: ${inputs.configFile}`, ); + return inputs.configInput; } } @@ -1161,9 +1165,11 @@ export async function initConfig( const { logger, features } = actionState; const { tempDir } = inputs; + const repositoryRoot = await getGitRoot(inputs.sourceRoot); + const userConfig = await determineUserConfig(actionState, tempDir, inputs); - const config = await initActionState(inputs, userConfig); + const config = await initActionState(inputs, userConfig, repositoryRoot); // If Code Quality analysis is the only enabled analysis kind, then we will initialise // the database for Code Quality. That entails disabling the default queries and only @@ -1245,6 +1251,7 @@ export async function initConfig( inputs.codeql, inputs.features, config.languages, + repositoryRoot, inputs.sourceRoot, config.buildMode, inputs.ramInput, @@ -1293,11 +1300,12 @@ export async function initConfig( logger, ); - if (await isTrapCachingEnabled(features, config.overlayDatabaseMode)) { + if (isTrapCachingEnabled(config.overlayDatabaseMode)) { const { trapCaches, trapCacheDownloadTime } = await downloadCacheWithTime( inputs.codeql, config.languages, logger, + repositoryRoot, ); config.trapCaches = trapCaches; config.trapCacheDownloadTime = trapCacheDownloadTime; @@ -1389,31 +1397,86 @@ export function getPathToParsedConfigFile(tempDir: string): string { return path.join(tempDir, "config"); } +function getPathToFailedConfigFile(tempDir: string): string { + return path.join(tempDir, "failed-config"); +} + /** - * Store the given config to the path returned from getPathToParsedConfigFile. + * Writes {@link config} to {@link configFilePath}. + * + * This function is not intended to be called, other than by + * {@link saveConfig} and {@link saveAbortedInitConfig} below. */ -export async function saveConfig(config: Config, logger: Logger) { +function saveConfigFile( + logger: Logger, + configFilePath: string, + config: Partial, +) { const configString = JSON.stringify(config); - const configFile = getPathToParsedConfigFile(config.tempDir); - fs.mkdirSync(path.dirname(configFile), { recursive: true }); - fs.writeFileSync(configFile, configString, "utf8"); + fs.mkdirSync(path.dirname(configFilePath), { recursive: true }); + fs.writeFileSync(configFilePath, configString, "utf8"); logger.debug("Saved config:"); logger.debug(configString); } /** - * Get the config that has been saved to the given temp dir. - * If the config could not be found then returns undefined. + * Store the given config to the path returned from getPathToParsedConfigFile. */ -export async function getConfig( - tempDir: string, +export async function saveConfig(config: Config, logger: Logger) { + const configFile = getPathToParsedConfigFile(config.tempDir); + saveConfigFile(logger, configFile, config); +} + +/** + * Store parts of {@link config} as a failed configuration file. + * + * The file will only contain parts of {@link config} that are relevant to + * the `init-post` step in the workflow. + */ +export function saveAbortedInitConfig( + action: ActionState<["Base", "Logger"]>, + config: Config, +) { + // Should only be called by init. + if (action.name !== ActionName.Init) { + throw new Error( + `Internal error: 'saveAbortedInitConfig' should only be called by '${ActionName.Init}', but was called by '${action.name}'.`, + ); + } + + // Create a copy of the input `Config` that only contains the keys we want. + const failedConfig: AbortedInitConfig = { + version: config.version, + tempDir: config.tempDir, + codeQLCmd: config.codeQLCmd, + debugMode: config.debugMode, + gitHubVersion: config.gitHubVersion, + languages: config.languages, + analysisKinds: config.analysisKinds, + }; + + action.logger.debug(`Saving config for failed init step.`); + saveConfigFile( + action.logger, + getPathToFailedConfigFile(config.tempDir), + failedConfig, + ); +} + +/** + * Attempts to read a {@link Config} from {@link configFilePath}. + * + * This function is not intended to be called, other than by + * {@link getConfig} and {@link getAbortedInitConfig} below. + */ +function readConfigFile( logger: Logger, -): Promise { - const configFile = getPathToParsedConfigFile(tempDir); - if (!fs.existsSync(configFile)) { + configFilePath: string, +): Config | undefined { + if (!fs.existsSync(configFilePath)) { return undefined; } - const configString = fs.readFileSync(configFile, "utf8"); + const configString = fs.readFileSync(configFilePath, "utf8"); logger.debug("Loaded config:"); logger.debug(configString); @@ -1426,13 +1489,50 @@ export async function getConfig( } if (config.version !== getActionVersion()) { throw new ConfigurationError( - `Loaded a configuration file for version '${config.version}', but running version '${getActionVersion()}'`, + [ + `Loaded a configuration file for version '${config.version}', but running version '${getActionVersion()}'.`, + "All steps in a workflow that use `github/codeql-action` must use the same version to work correctly.", + "If you are using Dependabot to manage dependency updates, you can configure a dependency group to update all `github/codeql-action` steps at the same time.", + "For more information, see https://docs.github.com/en/code-security/reference/supply-chain-security/dependabot-options-reference#groups--", + ].join(" "), ); } return config as Config; } +/** + * Get the config that has been saved to the given temp dir. + * If the config could not be found then returns undefined. + */ +export async function getConfig( + tempDir: string, + logger: Logger, +): Promise { + const configFile = getPathToParsedConfigFile(tempDir); + return readConfigFile(logger, configFile); +} + +/** + * Loads a {@link AbortedInitConfig} from a failed `init` step if it exists. + * + * The result will only contain parts of a {@link Config} that are relevant to + * the `init-post` step in the workflow. + */ +export function getAbortedInitConfig( + action: ActionState<["Base", "Logger"]>, + tempDir: string, +): AbortedInitConfig | undefined { + // Only intended to be called by the `init-post` action. + if (action.name !== ActionName.InitPost) { + throw new Error( + `Internal error: 'getAbortedInitConfig' should only be called by '${ActionName.InitPost}', but was called by '${action.name}'.`, + ); + } + + return readConfigFile(action.logger, getPathToFailedConfigFile(tempDir)); +} + /** * Generate a `qlconfig.yml` file from the `registries` input. * This file is used by the CodeQL CLI to list the registries to use for each @@ -1623,21 +1723,27 @@ export function appendExtraQueryExclusions( /** * Returns `true` if Code Scanning analysis is enabled, or `false` if not. */ -export function isCodeScanningEnabled(config: Config): boolean { +export function isCodeScanningEnabled( + config: ActionConfig<"analysisKinds">, +): boolean { return config.analysisKinds.includes(AnalysisKind.CodeScanning); } /** * Returns `true` if Code Quality analysis is enabled, or `false` if not. */ -export function isCodeQualityEnabled(config: Config): boolean { +export function isCodeQualityEnabled( + config: ActionConfig<"analysisKinds">, +): boolean { return config.analysisKinds.includes(AnalysisKind.CodeQuality); } /** * Returns `true` if Code Scanning Risk Assessment analysis is enabled, or `false` if not. */ -export function isRiskAssessmentEnabled(config: Config): boolean { +export function isRiskAssessmentEnabled( + config: ActionConfig<"analysisKinds">, +): boolean { return config.analysisKinds.includes(AnalysisKind.RiskAssessment); } diff --git a/src/config/action-config.ts b/src/config/action-config.ts index de6882e77e..9daf966eec 100644 --- a/src/config/action-config.ts +++ b/src/config/action-config.ts @@ -16,6 +16,11 @@ export interface Config { * The version of the CodeQL Action that the configuration is for. */ version: string; + /** + * The path at which the repository being analysed is checked out at, if available. + * Persisted in the CodeQL Action configuration state, so that we can consult it in later workflow steps. + */ + repositoryRoot: string | undefined; /** * Set of analysis kinds that are enabled. */ @@ -125,4 +130,42 @@ export interface Config { * Whether to enable file coverage information. */ enableFileCoverageInformation: boolean; + + /** Whether the analysis was successfully initialised using the configuration. */ + successfullyInitialised: boolean; } + +/** Properties available in `Config`. */ +export type ActionConfigProperties = keyof Config; + +/** + * The CodeQL Action configuration state that is persisted + * between steps of the CodeQL Action in a CodeQL workflow. + * + * By default, this is equivalent to `Config`. By explicitly + * providing required property names for `T` this can be restricted + * to requiring only those. For example, in `ActionConfig<"codeQLCmd">` + * all properties except `codeqlCmd` are optional. + */ +export type ActionConfig< + T extends ActionConfigProperties = ActionConfigProperties, +> = Partial & Pick; + +/** Helper function to check whether `config` has `key` to narrow the type of `config`. */ +export function hasConfigKey( + config: Partial, + key: Key, +): config is ActionConfig { + return config[key] !== undefined; +} + +/** A minimal configuration that we can make available even when `init` aborts. */ +export type AbortedInitConfig = ActionConfig< + | "version" + | "tempDir" + | "gitHubVersion" + | "debugMode" + | "languages" + | "analysisKinds" + | "codeQLCmd" +>; diff --git a/src/config/db-config.test.ts b/src/config/db-config.test.ts index 63d9d2ffec..ac1df16a00 100644 --- a/src/config/db-config.test.ts +++ b/src/config/db-config.test.ts @@ -2,15 +2,15 @@ import test, { ExecutionContext } from "ava"; import { RepositoryProperties } from "../feature-flags/properties"; import { BuiltInLanguage, Language } from "../languages"; -import { getRunnerLogger } from "../logging"; import { checkExpectedLogMessages, getRecordingLogger, LoggedMessage, makeMacro, RecordingLogger, + setupActionsVars, } from "../testing-utils"; -import { ConfigurationError, prettyPrintPack } from "../util"; +import { ConfigurationError, prettyPrintPack, withTmpDir } from "../util"; import * as dbConfig from "./db-config"; @@ -384,7 +384,7 @@ calculateAugmentationErrorMacro( test("parseUserConfig - successfully parses valid YAML", (t) => { const result = dbConfig.parseUserConfig( - getRunnerLogger(true), + new RecordingLogger(), "test", ` paths-ignore: @@ -410,7 +410,7 @@ test("parseUserConfig - throws a ConfigurationError if the file is not valid YAM t.throws( () => dbConfig.parseUserConfig( - getRunnerLogger(true), + new RecordingLogger(), "test", ` paths-ignore: @@ -562,66 +562,151 @@ test("mergeDefaultSetupAndUserConfigs - keeps other properties from user-supplie t.deepEqual(result, configFile); }); -test("mergeDefaultSetupAndUserConfigs - ignores, but warns about, unknown keys from Default Setup", async (t) => { - const logger = new RecordingLogger(); - const configFile: dbConfig.UserConfig = { - "query-filters": [{ exclude: { a: "b" } }], - "paths-ignore": ["path"], - }; - - const result = dbConfig.mergeDefaultSetupAndUserConfigs( - logger, - { - "default-setup": { - borg: [], - org: { - unknown: "foo", - "model-packs": [], +test.serial( + "mergeDefaultSetupAndUserConfigs - ignores, but warns about, unknown keys from Default Setup", + async (t) => { + const logger = new RecordingLogger(); + const configFile: dbConfig.UserConfig = { + "query-filters": [{ exclude: { a: "b" } }], + "paths-ignore": ["path"], + }; + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const result = dbConfig.mergeDefaultSetupAndUserConfigs( + logger, + { + "default-setup": { + borg: [], + org: { + unknown: "foo", + "model-packs": [], + }, + } as unknown as dbConfig.DefaultSetupConfig, + "paths-ignore": ["other-path"], }, - } as unknown as dbConfig.DefaultSetupConfig, - "paths-ignore": ["other-path"], - }, - configFile, - ); + configFile, + ); + + t.deepEqual(result, { + ...configFile, + "default-setup": { org: { "model-packs": [] } }, + }); + + const expectedUnrecognisedKeys = [ + ".default-setup.org.unknown", + ".default-setup.borg", + ".paths-ignore", + ].join(", "); + checkExpectedLogMessages(t, logger.messages, [ + `Unrecognised keys in Default Setup configuration: ${expectedUnrecognisedKeys}`, + ]); + }); + }, +); - t.deepEqual(result, { - ...configFile, - "default-setup": { org: { "model-packs": [] } }, - }); - - const expectedUnrecognisedKeys = [ - ".default-setup.org.unknown", - ".default-setup.borg", - ".paths-ignore", - ].join(", "); - checkExpectedLogMessages(t, logger.messages, [ - `Unrecognised keys in Default Setup configuration: ${expectedUnrecognisedKeys}`, - ]); -}); +test.serial( + "mergeDefaultSetupAndUserConfigs - warns about invalid keys from Default Setup", + async (t) => { + const logger = new RecordingLogger(); + const configFile: dbConfig.UserConfig = {}; -test("mergeDefaultSetupAndUserConfigs - warns about invalid keys from Default Setup", async (t) => { - const logger = new RecordingLogger(); - const configFile: dbConfig.UserConfig = {}; + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); - const result = dbConfig.mergeDefaultSetupAndUserConfigs( - logger, - { - "default-setup": { - org: { - "model-packs": [123], + const result = dbConfig.mergeDefaultSetupAndUserConfigs( + logger, + { + "default-setup": { + org: { + "model-packs": [123], + }, + } as unknown as dbConfig.DefaultSetupConfig, }, - } as unknown as dbConfig.DefaultSetupConfig, - }, - configFile, + configFile, + ); + + t.deepEqual(result, { + ...configFile, + "default-setup": { org: { "model-packs": [123] } }, + }); + + const expectedInvalidKeys = [".default-setup.org.model-packs[0]"].join( + ", ", + ); + checkExpectedLogMessages(t, logger.messages, [ + `Invalid keys in Default Setup configuration: ${expectedInvalidKeys}`, + ]); + }); + }, +); + +/** Parses `contents` as a configuration without validating it. */ +function parseUnvalidatedConfig(contents: string): dbConfig.UserConfig { + return dbConfig.parseUserConfig( + new RecordingLogger(), + "test", + contents, + false, ); +} + +test("matchesDefaultSetupConfigSchema - returns true for configurations that only use Default Setup properties", (t) => { + for (const contents of [ + [ + "default-setup:", + " org:", + " model-packs: [ github/immutable-actions-list@0.0.1 ]", + "threat-models: [ ]", + ].join("\n"), + "threat-models: [ local ]", + "{}", + ]) { + t.true( + dbConfig.matchesDefaultSetupConfigSchema( + parseUnvalidatedConfig(contents), + ), + contents, + ); + } +}); - t.deepEqual(result, { - ...configFile, - "default-setup": { org: { "model-packs": [123] } }, - }); +test("matchesDefaultSetupConfigSchema - returns false for configurations that use other properties", (t) => { + for (const contents of [ + "queries: [ { uses: ./queries/show_ifs.ql } ]", + "paths-ignore: [ tests ]", + "default-setup: { org: { model-packs: [], queries: [] } }", + ]) { + t.false( + dbConfig.matchesDefaultSetupConfigSchema( + parseUnvalidatedConfig(contents), + ), + contents, + ); + } +}); + +test("matchesDefaultSetupConfigSchema - returns false for invalid Default Setup properties", (t) => { + for (const contents of [ + "threat-models: local", + "default-setup: { org: { model-packs: [ 1 ] } }", + ]) { + t.false( + dbConfig.matchesDefaultSetupConfigSchema( + parseUnvalidatedConfig(contents), + ), + contents, + ); + } +}); - const expectedInvalidKeys = [".default-setup.org.model-packs[0]"].join(", "); - checkExpectedLogMessages(t, logger.messages, [ - `Invalid keys in Default Setup configuration: ${expectedInvalidKeys}`, - ]); +test("matchesDefaultSetupConfigSchema - returns false for configurations that aren't mappings", (t) => { + for (const contents of ["- threat-models", "local", "null"]) { + t.false( + dbConfig.matchesDefaultSetupConfigSchema( + parseUnvalidatedConfig(contents), + ), + contents, + ); + } }); diff --git a/src/config/db-config.ts b/src/config/db-config.ts index 7b5bdbd8ce..91a97db4ec 100644 --- a/src/config/db-config.ts +++ b/src/config/db-config.ts @@ -33,6 +33,15 @@ export interface QuerySpec { uses: string; } +// A set of default query suite names that are understood by the CLI. +export const defaultSuites: Set = new Set([ + "security-experimental", + "security-extended", + "security-and-quality", + "code-quality", + "code-scanning", +]); + const ORG_SCHEMA = { /** An array of model pack names. */ "model-packs": json.optional(json.array(json.string)), @@ -77,7 +86,11 @@ export interface UserConfig { "default-setup"?: DefaultSetupConfig; } -/** A subset of the `UserConfig` schema that is used by Default Setup. */ +/** + * A subset of the `UserConfig` schema that is known to be used by Default Setup. None of these + * properties may add queries, since a per-language CodeQL bundle can be used with a `config` input + * that only sets them. + */ const DEFAULT_SETUP_CONFIG_SCHEMA = { "threat-models": json.optional(json.array(json.string)), "default-setup": json.optional( @@ -85,6 +98,24 @@ const DEFAULT_SETUP_CONFIG_SCHEMA = { ), } as const satisfies json.Schema; +/** + * Returns whether `config` matches what we expect Default Setup to send in the `config` input: a + * mapping that only sets properties in `DEFAULT_SETUP_CONFIG_SCHEMA`, with values of the expected + * types. + */ +export function matchesDefaultSetupConfigSchema(config: UserConfig): boolean { + // Unless validation is enabled, `parseUserConfig` doesn't check that the YAML is a mapping. + if (!json.isObject(config)) { + return false; + } + const result = json.checkSchema( + DEFAULT_SETUP_CONFIG_SCHEMA, + config as json.UnvalidatedObject, + ); + // `valid` doesn't account for unknown properties. + return result.valid && result.unknownKeys.length === 0; +} + /** * Merges supported properties from two configuration files. This is intended only for * use with merging the `config` input provided by Default Setup with a potentially @@ -437,63 +468,60 @@ export async function calculateAugmentation( languages, packsInputCombines, ); - const queriesInputCombines = shouldCombine(rawQueriesInput); - const queriesInput = parseQueriesFromInput( - rawQueriesInput, - queriesInputCombines, + const queries = parseQueriesFromInput(rawQueriesInput); + const repoPropertyQueries = parseQueriesFromInput( + repositoryProperties[RepositoryPropertyName.EXTRA_QUERIES], + RepositoryPropertyName.EXTRA_QUERIES, ); - const repoExtraQueries = - repositoryProperties[RepositoryPropertyName.EXTRA_QUERIES]; - const repoExtraQueriesCombines = shouldCombine(repoExtraQueries); - const repoPropertyQueries = { - combines: repoExtraQueriesCombines, - input: parseQueriesFromInput( - repoExtraQueries, - repoExtraQueriesCombines, - new ConfigurationError( - errorMessages.getRepoPropertyError( - RepositoryPropertyName.EXTRA_QUERIES, - errorMessages.getEmptyCombinesError(), - ), - ), - ), - }; - return { packsInputCombines, packsInput: packsInput?.[languages[0]], - queriesInput, - queriesInputCombines, + queriesInput: queries.input, + queriesInputCombines: queries.combines, repoPropertyQueries, }; } -function parseQueriesFromInput( - rawQueriesInput: string | undefined, - queriesInputCombines: boolean, - errorToThrow?: ConfigurationError, -) { - if (!rawQueriesInput) { - return undefined; +/** + * Parses a comma-separated list of queries, which may have a '+' prefix. Entries aren't validated, + * so an empty entry becomes `{ uses: "" }`. + * + * @param value The list of queries. + * @param repositoryProperty The repository property that `value` comes from, if any. Error messages + * refer to this property, or to the `queries` input if no property is given. + * @returns An `Augmentation` containing the parsed queries and whether `value` has a '+' prefix. + * The queries are `undefined` if `value` is unset or empty. + * @throws A `ConfigurationError` if `value` is a '+' with no queries after it. + */ +export function parseQueriesFromInput( + value: string | undefined, + repositoryProperty?: RepositoryPropertyName, +): Augmentation { + if (!value) { + return { combines: false, input: undefined }; } - const trimmedInput = queriesInputCombines - ? rawQueriesInput.trim().slice(1).trim() - : (rawQueriesInput?.trim() ?? ""); - if (queriesInputCombines && trimmedInput.length === 0) { - if (errorToThrow) { - throw errorToThrow; - } + const combines = shouldCombine(value); + const trimmedInput = combines ? value.trim().slice(1).trim() : value.trim(); + if (combines && trimmedInput.length === 0) { throw new ConfigurationError( - errorMessages.getConfigFilePropertyError( - undefined, - "queries", - "A '+' was used in the 'queries' input to specify that you wished to add some packs to your CodeQL analysis. However, no packs were specified. Please either remove the '+' or specify some packs.", - ), + repositoryProperty !== undefined + ? errorMessages.getRepoPropertyError( + repositoryProperty, + errorMessages.getEmptyCombinesError(), + ) + : errorMessages.getConfigFilePropertyError( + undefined, + "queries", + "A '+' was used in the 'queries' input to specify that you wished to add some packs to your CodeQL analysis. However, no packs were specified. Please either remove the '+' or specify some packs.", + ), ); } - return trimmedInput.split(",").map((query) => ({ uses: query.trim() })); + return { + combines, + input: trimmedInput.split(",").map((query) => ({ uses: query.trim() })), + }; } /** @@ -610,11 +638,13 @@ export function generateCodeScanningConfig( * Attempts to parse `contents` into a `UserConfig` value. * * @param logger The logger to use. - * @param pathInput The path to the file where `contents` was obtained from, for use in error messages. - * @param contents The string contents of a YAML file to try and parse as a `UserConfig`. - * @param validateConfig Whether to validate the configuration file against the schema. - * @returns The `UserConfig` corresponding to `contents`, if parsing was successful. - * @throws A `ConfigurationError` if parsing failed. + * @param pathInput Where `contents` came from, such as the path to a file, for use in error messages. + * @param contents The YAML to try and parse as a `UserConfig`. + * @param validateConfig Whether to validate the configuration against the schema. + * @returns The `UserConfig` corresponding to `contents`, if parsing was successful. Unless + * `validateConfig` is set, the result might not be a mapping. + * @throws A `ConfigurationError` if `contents` isn't valid YAML or, when `validateConfig` is set, + * isn't a valid configuration. */ export function parseUserConfig( logger: Logger, diff --git a/src/database-upload.test.ts b/src/database-upload.test.ts index bcaf9f1c9e..7d7145dd36 100644 --- a/src/database-upload.test.ts +++ b/src/database-upload.test.ts @@ -1,4 +1,5 @@ -import * as fs from "fs"; +import fs from "fs"; +import path from "path"; import * as github from "@actions/github"; import test from "ava"; @@ -10,7 +11,11 @@ import { GitHubApiDetails } from "./api-client"; import * as apiClient from "./api-client"; import { createStubCodeQL } from "./codeql"; import { Config } from "./config-utils"; -import { cleanupAndUploadDatabases } from "./database-upload"; +import { + cleanupAndUploadDatabases, + uploadBundledDatabase, +} from "./database-upload"; +import { getEnv } from "./environment"; import { Feature } from "./feature-flags"; import * as gitUtils from "./git-utils"; import { BuiltInLanguage } from "./languages"; @@ -20,23 +25,19 @@ import { checkExpectedLogMessages, createFeatures, createTestConfig, - getRecordingLogger, - LoggedMessage, + getTestEnv, + initAllState, + RecordingLogger, + SAMPLE_DOTCOM_API_DETAILS, setupActionsVars, setupTests, } from "./testing-utils"; -import { - CleanupLevel, - GitHubVariant, - HTTPError, - initializeEnvironment, - withTmpDir, -} from "./util"; +import { CleanupLevel, GitHubVariant, HTTPError, withTmpDir } from "./util"; setupTests(test); test.beforeEach(() => { - initializeEnvironment("1.2.3"); + getEnv().initialise("1.2.3"); }); const testRepoName: RepositoryNwo = { owner: "github", repo: "example" }; @@ -90,23 +91,24 @@ test.serial( "Abort database upload if 'upload-database' input set to false", async (t) => { await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); sinon .stub(actionsUtil, "getRequiredInput") .withArgs("upload-database") .returns("false"); sinon.stub(gitUtils, "isAnalyzingDefaultBranch").resolves(true); - const loggedMessages: LoggedMessage[] = []; + const logger = new RecordingLogger(); await cleanupAndUploadDatabases( + initAllState({ env, logger }), testRepoName, getCodeQL(), getTestConfig(tmpDir), testApiDetails, - createFeatures([]), - getRecordingLogger(loggedMessages), + "", ); - checkExpectedLogMessages(t, loggedMessages, [ + checkExpectedLogMessages(t, logger.messages, [ "Database upload disabled in workflow. Skipping upload.", ]); }); @@ -117,7 +119,8 @@ test.serial( "Abort database upload if 'analysis-kinds: code-scanning' is not enabled", async (t) => { await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); sinon .stub(actionsUtil, "getRequiredInput") .withArgs("upload-database") @@ -126,8 +129,9 @@ test.serial( await mockHttpRequests(201); - const loggedMessages: LoggedMessage[] = []; + const logger = new RecordingLogger(); await cleanupAndUploadDatabases( + initAllState({ env, logger }), testRepoName, getCodeQL(), { @@ -135,10 +139,9 @@ test.serial( analysisKinds: [AnalysisKind.CodeQuality], }, testApiDetails, - createFeatures([]), - getRecordingLogger(loggedMessages), + "", ); - checkExpectedLogMessages(t, loggedMessages, [ + checkExpectedLogMessages(t, logger.messages, [ "Not uploading database because 'analysis-kinds: code-scanning' is not enabled.", ]); }); @@ -147,7 +150,8 @@ test.serial( test.serial("Abort database upload if running against GHES", async (t) => { await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); sinon .stub(actionsUtil, "getRequiredInput") .withArgs("upload-database") @@ -157,16 +161,16 @@ test.serial("Abort database upload if running against GHES", async (t) => { const config = getTestConfig(tmpDir); config.gitHubVersion = { type: GitHubVariant.GHES, version: "3.0" }; - const loggedMessages: LoggedMessage[] = []; + const logger = new RecordingLogger(); await cleanupAndUploadDatabases( + initAllState({ env, logger }), testRepoName, getCodeQL(), config, testApiDetails, - createFeatures([]), - getRecordingLogger(loggedMessages), + "", ); - checkExpectedLogMessages(t, loggedMessages, [ + checkExpectedLogMessages(t, logger.messages, [ "Not running against github.com or GHEC-DR. Skipping upload.", ]); }); @@ -176,23 +180,24 @@ test.serial( "Abort database upload if not analyzing default branch", async (t) => { await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); sinon .stub(actionsUtil, "getRequiredInput") .withArgs("upload-database") .returns("true"); sinon.stub(gitUtils, "isAnalyzingDefaultBranch").resolves(false); - const loggedMessages: LoggedMessage[] = []; + const logger = new RecordingLogger(); await cleanupAndUploadDatabases( + initAllState({ env, logger }), testRepoName, getCodeQL(), getTestConfig(tmpDir), testApiDetails, - createFeatures([]), - getRecordingLogger(loggedMessages), + "", ); - checkExpectedLogMessages(t, loggedMessages, [ + checkExpectedLogMessages(t, logger.messages, [ "Not analyzing default branch. Skipping upload.", ]); }); @@ -203,7 +208,8 @@ test.serial( "Don't crash if uploading a database fails with a non-retryable error", async (t) => { await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); sinon .stub(actionsUtil, "getRequiredInput") .withArgs("upload-database") @@ -212,17 +218,17 @@ test.serial( const databaseUploadSpy = await mockHttpRequests(422); - const loggedMessages: LoggedMessage[] = []; + const logger = new RecordingLogger(); await cleanupAndUploadDatabases( + initAllState({ env, logger }), testRepoName, getCodeQL(), getTestConfig(tmpDir), testApiDetails, - createFeatures([]), - getRecordingLogger(loggedMessages), + "", ); - checkExpectedLogMessages(t, loggedMessages, [ + checkExpectedLogMessages(t, logger.messages, [ "Failed to upload database for javascript: some error message", ]); @@ -236,7 +242,8 @@ test.serial( "Don't crash if uploading a database fails with a retryable error", async (t) => { await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); sinon .stub(actionsUtil, "getRequiredInput") .withArgs("upload-database") @@ -251,17 +258,17 @@ test.serial( .stub(global, "setTimeout") .callsFake((fn: () => void) => originalSetTimeout(fn, 0)); - const loggedMessages: LoggedMessage[] = []; + const logger = new RecordingLogger(); await cleanupAndUploadDatabases( + initAllState({ env, logger }), testRepoName, getCodeQL(), getTestConfig(tmpDir), testApiDetails, - createFeatures([]), - getRecordingLogger(loggedMessages), + "", ); - checkExpectedLogMessages(t, loggedMessages, [ + checkExpectedLogMessages(t, logger.messages, [ "Failed to upload database for javascript: some error message", ]); @@ -279,7 +286,8 @@ test.serial( test.serial("Successfully uploading a database to github.com", async (t) => { await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); sinon .stub(actionsUtil, "getRequiredInput") .withArgs("upload-database") @@ -288,16 +296,16 @@ test.serial("Successfully uploading a database to github.com", async (t) => { await mockHttpRequests(201); - const loggedMessages: LoggedMessage[] = []; + const logger = new RecordingLogger(); await cleanupAndUploadDatabases( + initAllState({ env, logger }), testRepoName, getCodeQL(), getTestConfig(tmpDir), testApiDetails, - createFeatures([]), - getRecordingLogger(loggedMessages), + "", ); - checkExpectedLogMessages(t, loggedMessages, [ + checkExpectedLogMessages(t, logger.messages, [ "Successfully uploaded database for javascript", ]); }); @@ -305,7 +313,8 @@ test.serial("Successfully uploading a database to github.com", async (t) => { test.serial("Successfully uploading a database to GHEC-DR", async (t) => { await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); sinon .stub(actionsUtil, "getRequiredInput") .withArgs("upload-database") @@ -314,8 +323,9 @@ test.serial("Successfully uploading a database to GHEC-DR", async (t) => { const databaseUploadSpy = await mockHttpRequests(201); - const loggedMessages: LoggedMessage[] = []; + const logger = new RecordingLogger(); await cleanupAndUploadDatabases( + initAllState({ env, logger }), testRepoName, getCodeQL(), getTestConfig(tmpDir), @@ -324,10 +334,9 @@ test.serial("Successfully uploading a database to GHEC-DR", async (t) => { url: "https://tenant.ghe.com", apiURL: undefined, }, - createFeatures([]), - getRecordingLogger(loggedMessages), + "", ); - checkExpectedLogMessages(t, loggedMessages, [ + checkExpectedLogMessages(t, logger.messages, [ "Successfully uploaded database for javascript", ]); t.assert( @@ -343,7 +352,8 @@ test.serial( "Records overlay and clear cleanup sizes when uploading an overlay-base database", async (t) => { await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); sinon .stub(actionsUtil, "getRequiredInput") .withArgs("upload-database") @@ -375,14 +385,16 @@ test.serial( const config = getTestConfig(tmpDir); config.overlayDatabaseMode = OverlayDatabaseMode.OverlayBase; - const loggedMessages: LoggedMessage[] = []; const results = await cleanupAndUploadDatabases( + initAllState({ + env, + features: createFeatures([Feature.UploadOverlayDbToApi]), + }), testRepoName, codeql, config, testApiDetails, - createFeatures([Feature.UploadOverlayDbToApi]), - getRecordingLogger(loggedMessages), + "", ); // The database should be cleaned up at the `overlay` level for the upload @@ -402,7 +414,8 @@ test.serial( "Does not measure clear cleanup size for a regular (non-overlay-base) upload", async (t) => { await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); sinon .stub(actionsUtil, "getRequiredInput") .withArgs("upload-database") @@ -422,12 +435,15 @@ test.serial( }); const results = await cleanupAndUploadDatabases( + initAllState({ + env, + features: createFeatures([Feature.UploadOverlayDbToApi]), + }), testRepoName, codeql, getTestConfig(tmpDir), testApiDetails, - createFeatures([Feature.UploadOverlayDbToApi]), - getRecordingLogger([]), + "", ); // A regular upload is cleaned only once, at the `clear` level. @@ -441,7 +457,8 @@ test.serial( test.serial("Does not measure clear cleanup size in debug mode", async (t) => { await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); sinon .stub(actionsUtil, "getRequiredInput") .withArgs("upload-database") @@ -465,12 +482,15 @@ test.serial("Does not measure clear cleanup size in debug mode", async (t) => { config.debugMode = true; const results = await cleanupAndUploadDatabases( + initAllState({ + env, + features: createFeatures([Feature.UploadOverlayDbToApi]), + }), testRepoName, codeql, config, testApiDetails, - createFeatures([Feature.UploadOverlayDbToApi]), - getRecordingLogger([]), + "", ); // In debug mode we clean up at the `overlay` level for the upload but skip @@ -486,7 +506,8 @@ test.serial( "Does not record a clear cleanup duration when the clear cleanup fails", async (t) => { await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); sinon .stub(actionsUtil, "getRequiredInput") .withArgs("upload-database") @@ -510,12 +531,15 @@ test.serial( config.overlayDatabaseMode = OverlayDatabaseMode.OverlayBase; const results = await cleanupAndUploadDatabases( + initAllState({ + env, + features: createFeatures([Feature.UploadOverlayDbToApi]), + }), testRepoName, codeql, config, testApiDetails, - createFeatures([Feature.UploadOverlayDbToApi]), - getRecordingLogger([]), + "", ); // When the `clear` cleanup fails, no size is measured, so we should not @@ -526,3 +550,86 @@ test.serial( }); }, ); + +test.serial( + "uploadBundledDatabase provides expected request arguments", + async (t) => + withTmpDir(async (tmpDir) => { + // Write some file that `uploadBundledDatabase` can use for its `fs.createReadStream(bundledDb)` call + // so we don't have to stub that or create a fake `ReadStream`. + const dbPath = path.join(tmpDir, "db"); + const content = JSON.stringify({}); + fs.writeFileSync(dbPath, content); + + // A simple stub for `fetch` that satisfies Octokit when it inspects the response. + const fetchStub = sinon.stub().resolves({ + status: 200, + headers: new Headers(), + text: async () => "", + }); + + // Construct a real `ApiClient`. + const client = apiClient.getApiClient( + getTestEnv(), + SAMPLE_DOTCOM_API_DETAILS, + ); + + // Then wrap the real `request` method in a stub that calls it with our stubbed `fetch`. + // This ensures that we have a real `ApiClient` with a mostly real `request`, but which + // does not perform any actual requests. + const request = client.request; + sinon.stub(client, "request").callsFake(async (route, options) => + request(route, { + ...options, + request: { ...options?.request, fetch: fetchStub }, + }), + ); + + // Stub `getApiClient` to return our modified `ApiClient`. + const getApiClient = sinon + .stub(apiClient, "getApiClient") + .returns(client); + + // Calling `uploadBundledDatabase` shouldn't throw. + const nwo: RepositoryNwo = { owner: "test", repo: "foo" }; + const language: BuiltInLanguage = BuiltInLanguage.java; + + await t.notThrowsAsync(async () => { + await uploadBundledDatabase( + nwo, + language, + "123", + dbPath, + content.length, + SAMPLE_DOTCOM_API_DETAILS, + ); + }); + + // Check that our stubs were called and that they received the expected arguments. + t.is(getApiClient.callCount, 1); + t.is(fetchStub.callCount, 1); + + const args = fetchStub.args[0]; + t.is(args.length, 2); + + const url = args[0]; + t.is( + url, + `https://uploads.github.com/repos/${nwo.owner}/${nwo.repo}/code-scanning/codeql/databases/${language}?name=${language}-database&commit_oid=123`, + ); + + const options = args[1]; + t.like(options, { + // Going via `new Headers` and `Object.fromEntries` ensures we get the same cases + // for the header keys as we are given. + headers: Object.fromEntries( + new Headers({ + authorization: `token ${SAMPLE_DOTCOM_API_DETAILS.auth}`, + "Content-Type": "application/zip", + "Content-Length": content.length.toString(), + }).entries(), + ), + method: "POST", + } satisfies RequestInit); + }), +); diff --git a/src/database-upload.ts b/src/database-upload.ts index 0189bef1e6..2a24a2e1d4 100644 --- a/src/database-upload.ts +++ b/src/database-upload.ts @@ -1,5 +1,6 @@ import * as fs from "fs"; +import { ActionState } from "./action-common"; import * as actionsUtil from "./actions-util"; import { AnalysisKind } from "./analyses"; import { @@ -9,13 +10,14 @@ import { } from "./api-client"; import { type CodeQL } from "./codeql"; import { Config } from "./config-utils"; -import { Feature, FeatureEnablement } from "./feature-flags"; +import { Feature } from "./feature-flags"; import * as gitUtils from "./git-utils"; +import { parseGitHubUrl } from "./github"; import { Logger, withGroupAsync } from "./logging"; import { OverlayDatabaseMode } from "./overlay/overlay-database-mode"; import { RepositoryNwo } from "./repository"; import * as util from "./util"; -import { asHTTPError, bundleDb, CleanupLevel, parseGitHubUrl } from "./util"; +import { asHTTPError, bundleDb, CleanupLevel } from "./util"; /** Information about a database upload. */ export interface DatabaseUploadResult { @@ -45,13 +47,15 @@ export interface DatabaseUploadResult { } export async function cleanupAndUploadDatabases( + action: ActionState<["ReadOnlyEnv", "Logger", "FeatureFlags"]>, repositoryNwo: RepositoryNwo, codeql: CodeQL, config: Config, apiDetails: GitHubApiDetails, - features: FeatureEnablement, - logger: Logger, + checkoutPath: string, ): Promise { + const logger = action.logger; + if (actionsUtil.getRequiredInput("upload-database") !== "true") { logger.debug("Database upload disabled in workflow. Skipping upload."); return []; @@ -78,7 +82,7 @@ export async function cleanupAndUploadDatabases( return []; } - if (!(await gitUtils.isAnalyzingDefaultBranch())) { + if (!(await gitUtils.isAnalyzingDefaultBranch(action.env, checkoutPath))) { // We only want to upload a database if we are analyzing the default branch. logger.debug("Not analyzing default branch. Skipping upload."); return []; @@ -87,7 +91,7 @@ export async function cleanupAndUploadDatabases( // If config.overlayDatabaseMode is OverlayBase, then we have overlay base databases for all languages. const shouldUploadOverlayBase = config.overlayDatabaseMode === OverlayDatabaseMode.OverlayBase && - (await features.getValue(Feature.UploadOverlayDbToApi, codeql)); + (await action.features.getValue(Feature.UploadOverlayDbToApi, codeql)); const cleanupLevel = shouldUploadOverlayBase ? CleanupLevel.Overlay : CleanupLevel.Clear; @@ -110,9 +114,7 @@ export async function cleanupAndUploadDatabases( includeDiagnostics: false, }); bundledDbSize = fs.statSync(bundledDb).size; - const commitOid = await gitUtils.getCommitOid( - actionsUtil.getRequiredInput("checkout_path"), - ); + const commitOid = await gitUtils.getCommitOid(action.env, checkoutPath); // Upload with manual retry logic. We disable Octokit's built-in retries // because the request body is a ReadStream, which can only be consumed // once. @@ -257,7 +259,7 @@ async function recordClearCleanupSizes( * * @returns the duration of the upload in milliseconds */ -async function uploadBundledDatabase( +export async function uploadBundledDatabase( repositoryNwo: RepositoryNwo, language: string, commitOid: string, @@ -265,7 +267,10 @@ async function uploadBundledDatabase( bundledDbSize: number, apiDetails: GitHubApiDetails, ): Promise { - const client = getApiClient(); + // Ensure that the `apiDetails` that `getApiClient` uses match the ones we were given here, + // because we use `apiDetails.auth` below which must be used with the same instance that + // `apiDetails` refers to. + const client = getApiClient(util.getEnv(), apiDetails); const uploadsUrl = new URL(parseGitHubUrl(apiDetails.url)); uploadsUrl.hostname = `uploads.${uploadsUrl.hostname}`; @@ -291,7 +296,6 @@ async function uploadBundledDatabase( commit_oid: commitOid, data: bundledDbReadStream, headers: { - authorization: `token ${apiDetails.auth}`, "Content-Type": "application/zip", "Content-Length": bundledDbSize, }, diff --git a/src/debug-artifacts.test.ts b/src/debug-artifacts.test.ts index 370816aef5..16ecb6d5dd 100644 --- a/src/debug-artifacts.test.ts +++ b/src/debug-artifacts.test.ts @@ -55,25 +55,20 @@ test("getArtifactSuffix", (t) => { } }); -// These next tests check the correctness of the logic to determine whether or not -// artifacts are uploaded in debug mode. Since it's not easy to mock the actual -// call to upload an artifact, we just check that we get an "upload-failed" result, -// instead of actually uploading the artifact. -// -// For tests where we expect artifact upload to be blocked, we check for a different -// response from the function. +// These next tests check whether `uploadArtifacts` attempts to upload an artifact. Since it's not +// easy to mock the actual call to upload an artifact, we check that we get an "upload-failed" +// result, instead of actually uploading the artifact. -test("uploadDebugArtifacts when artifacts empty should emit 'no-artifacts-to-upload'", async (t) => { +test("uploadArtifacts returns 'no-artifacts-to-upload' when there are no files to upload", async (t) => { // Test that no error is thrown if artifacts list is empty. const logger = getActionsLogger(); await t.notThrowsAsync(async () => { - const uploaded = await debugArtifacts.uploadDebugArtifacts( + const uploaded = await debugArtifacts.uploadArtifacts( logger, [], "i-dont-exist", "artifactName", GitHubVariant.DOTCOM, - undefined, ); t.is( uploaded, @@ -83,17 +78,15 @@ test("uploadDebugArtifacts when artifacts empty should emit 'no-artifacts-to-upl }); }); -test("uploadDebugArtifacts when no codeql version is used should invoke artifact upload", async (t) => { - // Test that the artifact is uploaded. +test("uploadArtifacts attempts an upload when there are files to upload", async (t) => { const logger = getActionsLogger(); await t.notThrowsAsync(async () => { - const uploaded = await debugArtifacts.uploadDebugArtifacts( + const uploaded = await debugArtifacts.uploadArtifacts( logger, ["hucairz"], "i-dont-exist", "artifactName", GitHubVariant.DOTCOM, - undefined, ); t.is( uploaded, @@ -103,44 +96,3 @@ test("uploadDebugArtifacts when no codeql version is used should invoke artifact ); }); }); - -test("uploadDebugArtifacts when new codeql version is used should invoke artifact upload", async (t) => { - // Test that the artifact is uploaded. - const logger = getActionsLogger(); - await t.notThrowsAsync(async () => { - const uploaded = await debugArtifacts.uploadDebugArtifacts( - logger, - ["hucairz"], - "i-dont-exist", - "artifactName", - GitHubVariant.DOTCOM, - "2.20.3", - ); - t.is( - uploaded, - // The failure is expected since we don't want to actually upload any artifacts in unit tests. - "upload-failed", - "Expect failure to upload artifacts since root dir does not exist", - ); - }); -}); - -test("uploadDebugArtifacts when old codeql is used should avoid trying to upload artifacts", async (t) => { - // Test that the artifact is not uploaded. - const logger = getActionsLogger(); - await t.notThrowsAsync(async () => { - const uploaded = await debugArtifacts.uploadDebugArtifacts( - logger, - ["hucairz"], - "i-dont-exist", - "artifactName", - GitHubVariant.DOTCOM, - "2.20.2", - ); - t.is( - uploaded, - "upload-not-supported", - "Expected artifact upload to be blocked because of old CodeQL version", - ); - }); -}); diff --git a/src/debug-artifacts.ts b/src/debug-artifacts.ts index 9f5f1775d4..23a5566547 100644 --- a/src/debug-artifacts.ts +++ b/src/debug-artifacts.ts @@ -10,15 +10,11 @@ import { getOptionalInput, getTemporaryDirectory } from "./actions-util"; import { dbIsFinalized } from "./analyze"; import { scanArtifactsForTokens } from "./artifact-scanner"; import { type CodeQL } from "./codeql"; -import { Config } from "./config-utils"; -import { EnvVar } from "./environment"; +import type { ActionConfig } from "./config/action-config"; +import { EnvVar, exportEnvVar } from "./environment"; import * as json from "./json"; import { Language } from "./languages"; import { Logger, withGroup } from "./logging"; -import { - isSafeArtifactUpload, - SafeArtifactUploadVersion, -} from "./tools-features"; import { bundleDb, doesDirectoryExist, @@ -40,7 +36,6 @@ export function sanitizeArtifactName(name: string): string { export async function uploadCombinedSarifArtifacts( logger: Logger, gitHubVariant: GitHubVariant, - codeQlVersion: string | undefined, ) { const tempDir = getTemporaryDirectory(); @@ -70,13 +65,12 @@ export async function uploadCombinedSarifArtifacts( } try { - await uploadDebugArtifacts( + await uploadArtifacts( logger, toUpload, baseTempDir, "combined-sarif-artifacts", gitHubVariant, - codeQlVersion, ); } catch (e) { logger.warning( @@ -95,7 +89,7 @@ export async function uploadCombinedSarifArtifacts( * @return The path to that debug artifact, or undefined if an error occurs. */ function tryPrepareSarifDebugArtifact( - config: Config, + config: ActionConfig<"dbLocation">, language: Language, logger: Logger, ): string | undefined { @@ -137,7 +131,7 @@ function tryPrepareSarifDebugArtifact( */ async function tryBundleDatabase( codeql: CodeQL, - config: Config, + config: ActionConfig<"dbLocation">, language: Language, logger: Logger, ): Promise { @@ -163,6 +157,11 @@ async function tryBundleDatabase( } } +/** The minimal configuration needed for `tryUploadAllAvailableDebugArtifacts`. */ +export type UploadDebugArtifactsConfig = ActionConfig< + "languages" | "gitHubVersion" | "dbLocation" | "debugArtifactName" +>; + /** * Attempt to upload all available debug artifacts. * @@ -170,9 +169,8 @@ async function tryBundleDatabase( */ export async function tryUploadAllAvailableDebugArtifacts( codeql: CodeQL, - config: Config, + config: UploadDebugArtifactsConfig, logger: Logger, - codeQlVersion: string | undefined, ) { const filesToUpload: string[] = []; try { @@ -231,13 +229,12 @@ export async function tryUploadAllAvailableDebugArtifacts( try { await withGroup("Uploading debug artifacts", async () => - uploadDebugArtifacts( + uploadArtifacts( logger, filesToUpload, config.dbLocation, config.debugArtifactName, config.gitHubVersion.type, - codeQlVersion, ), ); } catch (e) { @@ -279,29 +276,7 @@ export function getArtifactSuffix(matrix: string | undefined): string { // Enumerates different, possible outcomes for artifact uploads. export type UploadArtifactsResult = - | "no-artifacts-to-upload" - | "upload-successful" - | "upload-failed"; - -export async function uploadDebugArtifacts( - logger: Logger, - toUpload: string[], - rootDir: string, - artifactName: string, - ghVariant: GitHubVariant, - codeQlVersion: string | undefined, -): Promise { - const uploadSupported = isSafeArtifactUpload(codeQlVersion); - - if (!uploadSupported) { - core.info( - `Skipping debug artifact upload because the current CLI does not support safe upload. Please upgrade to CLI v${SafeArtifactUploadVersion} or later.`, - ); - return "upload-not-supported"; - } - - return uploadArtifacts(logger, toUpload, rootDir, artifactName, ghVariant); -} + "no-artifacts-to-upload" | "upload-successful" | "upload-failed"; /** * Uploads the specified files as a single workflow artifact. @@ -330,7 +305,7 @@ export async function uploadArtifacts( // some issues early. if (isInTestMode()) { await scanArtifactsForTokens(toUpload, logger); - core.exportVariable("CODEQL_ACTION_ARTIFACT_SCAN_FINISHED", "true"); + exportEnvVar("CODEQL_ACTION_ARTIFACT_SCAN_FINISHED", "true"); } const suffix = getArtifactSuffix(getOptionalInput("matrix")); @@ -381,7 +356,7 @@ export async function getArtifactUploaderClient( * all files in the database folder and return the path. */ async function createPartialDatabaseBundle( - config: Config, + config: ActionConfig<"dbLocation">, language: Language, ): Promise { const databasePath = getCodeQLDatabasePath(config, language); @@ -422,7 +397,7 @@ async function createPartialDatabaseBundle( */ async function createDatabaseBundleCli( codeql: CodeQL, - config: Config, + config: ActionConfig<"dbLocation">, language: Language, ): Promise { const databaseBundlePath = await bundleDb( diff --git a/src/defaults.json b/src/defaults.json index b5d9f13644..cfa3f6c1c7 100644 --- a/src/defaults.json +++ b/src/defaults.json @@ -1,6 +1,6 @@ { - "bundleVersion": "codeql-bundle-v2.26.3", - "cliVersion": "2.26.3", - "priorBundleVersion": "codeql-bundle-v2.26.2", - "priorCliVersion": "2.26.2" + "bundleVersion": "codeql-bundle-v2.27.4", + "cliVersion": "2.27.4", + "priorBundleVersion": "codeql-bundle-v2.27.3", + "priorCliVersion": "2.27.3" } diff --git a/src/dependency-caching.ts b/src/dependency-caching.ts index f04d38f46c..e6495f3a7b 100644 --- a/src/dependency-caching.ts +++ b/src/dependency-caching.ts @@ -313,6 +313,7 @@ export async function downloadDependencyCaches( const primaryKey = await cacheKey(codeql, features, language, patterns); const restoreKeys: string[] = [ + primaryKey, await cachePrefix(codeql, features, language), ]; diff --git a/src/diagnostics.test.ts b/src/diagnostics.test.ts new file mode 100644 index 0000000000..39ed95b209 --- /dev/null +++ b/src/diagnostics.test.ts @@ -0,0 +1,165 @@ +import * as fs from "fs"; +import path from "path"; + +import test, { type ExecutionContext } from "ava"; + +import * as diagnostics from "./diagnostics"; +import { BuiltInLanguage } from "./languages"; +import { + checkExpectedLogMessages, + createTestConfig, + initAllState, + RecordingLogger, + setupTests, +} from "./testing-utils"; +import { withTmpDir } from "./util"; + +setupTests(test); + +const id = "codeql-action/test-diagnostic"; +const name = "Test title"; + +test("makeDiagnostic - adds expected properties", (t) => { + const diagnostic = diagnostics.makeDiagnostic(id, name, {}); + + t.truthy(diagnostic.timestamp); + t.is(diagnostic.source.id, id); + t.is(diagnostic.source.name, name); +}); + +test("getLanguageDiagnosticsPath gets language-specific path", async (t) => + withTmpDir(async (tmpDir) => { + for (const language of Object.values(BuiltInLanguage)) { + t.is( + diagnostics.getLanguageDiagnosticsPath(tmpDir, language), + path.resolve( + tmpDir, + language, + ...diagnostics.CODEQL_ACTION_DIAGNOSTIC_SUBDIR_PARTS, + ), + ); + } + })); + +test("getTempLanguageDiagnosticsPath returns path without language", async (t) => + withTmpDir(async (tmpDir) => { + t.is( + diagnostics.getTempLanguageDiagnosticsPath(tmpDir), + path.resolve( + tmpDir, + diagnostics.TEMP_DIAGNOSTIC_DIR_NAME, + ...diagnostics.CODEQL_ACTION_DIAGNOSTIC_SUBDIR_PARTS, + ), + ); + })); + +test("getTempLanguageDiagnosticsPath returns language-specific path if a language is provided", async (t) => + withTmpDir(async (tmpDir) => { + t.is( + diagnostics.getTempLanguageDiagnosticsPath(tmpDir, BuiltInLanguage.swift), + path.resolve( + tmpDir, + diagnostics.TEMP_DIAGNOSTIC_DIR_NAME, + BuiltInLanguage.swift, + ...diagnostics.CODEQL_ACTION_DIAGNOSTIC_SUBDIR_PARTS, + ), + ); + })); + +test("getDatabaseDiagnosticsPath returns language-specific path", async (t) => + withTmpDir(async (tmpDir) => { + t.is( + diagnostics.getDatabaseDiagnosticsPath( + createTestConfig({ dbLocation: tmpDir }), + BuiltInLanguage.swift, + ), + path.resolve( + tmpDir, + BuiltInLanguage.swift, + ...diagnostics.CODEQL_ACTION_DIAGNOSTIC_SUBDIR_PARTS, + ), + ); + })); + +/** + * Diagnostic files that are written to disk don't have deterministic names. + * This function recursively finds all `.json` files at {@link rootPath}, + * asserts that there is exactly one, and that it matches {@link expected}. + * + * @param rootPath The path to start searching from. + */ +function assertSingleDiagnosticIn( + t: ExecutionContext, + rootPath: string, + expected: diagnostics.DiagnosticMessage, +) { + // Find all `.json` files in `rootPath` and check that there is exactly one. + const filePaths = fs + .readdirSync(rootPath, { + recursive: true, + encoding: "utf-8", + }) + .filter((p) => p.endsWith(".json")); + + t.is(filePaths.length, 1); + + // Check that the written diagnostic matches the one we added. + const contents = fs.readFileSync( + path.resolve(rootPath, filePaths[0]), + "utf-8", + ); + + const readDiagnostic = JSON.parse(contents) as diagnostics.DiagnosticMessage; + t.deepEqual(readDiagnostic, expected); +} + +test("addDiagnostic writes temporary diagnostics and flushDiagnostics moves them to the database", async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + + const tempDiagDir = path.resolve(tmpDir, "temp"); + const testDbDir = path.resolve(tmpDir, "test", "database"); + const diagnostic = diagnostics.makeDiagnostic(id, name, {}); + + // Write the diagnostic. The path provided for `dbLocation` doesn't exist, + // so the diagnostic will be written to a temporary location. + t.notThrows(() => { + diagnostics.addDiagnostic( + createTestConfig({ tempDir: tempDiagDir, dbLocation: testDbDir }), + BuiltInLanguage.actions, + diagnostic, + logger, + ); + }); + + // Check that `tempDiagDir` was created. + t.true(fs.existsSync(tempDiagDir)); + + // Check that the diagnostic exists under `tempDiagDir`. + assertSingleDiagnosticIn(t, tempDiagDir, diagnostic); + + // Flush the diagnostics. This will cause the diagnostic we wrote previously to + // be moved to a location under `dbLocation`. + t.notThrows(() => { + diagnostics.flushDiagnostics( + initAllState({ logger }), + createTestConfig({ + tempDir: tempDiagDir, + dbLocation: testDbDir, + }), + ); + }); + + // Check that `testDbDir` was created. + t.true(fs.existsSync(testDbDir)); + + // Check that the diagnostic exists under `testDbDir`. + assertSingleDiagnosticIn(t, testDbDir, diagnostic); + + // Check that we logged that the database directory doesn't exist yet + // and that we moved one diagnostic. + checkExpectedLogMessages(t, logger.messages, [ + `but the database at ${path.join(testDbDir, "actions")} does not exist yet`, + "Moving 1 diagnostic(s) to their respective databases.", + ]); + })); diff --git a/src/diagnostics.ts b/src/diagnostics.ts index fa0e87c046..f2d3a152a8 100644 --- a/src/diagnostics.ts +++ b/src/diagnostics.ts @@ -1,10 +1,24 @@ -import { existsSync, mkdirSync, writeFileSync } from "fs"; +import * as fs from "fs"; import path from "path"; -import type { Config } from "./config-utils"; +import type { ActionState } from "./action-common"; +import { getTemporaryDirectory } from "./actions-util"; +import type { ActionConfig } from "./config/action-config"; import { Language } from "./languages"; -import { getActionsLogger } from "./logging"; -import { getCodeQLDatabasePath } from "./util"; +import { getActionsLogger, type Logger } from "./logging"; +import { + getCodeQLDatabasePath, + getErrorMessage, + isErrnoException, +} from "./util"; + +/** The name of the directory we use to temporarily store diagnostics. */ +export const TEMP_DIAGNOSTIC_DIR_NAME = "codeql-action-temp-diagnostics"; + +export const CODEQL_ACTION_DIAGNOSTIC_SUBDIR_PARTS = [ + "diagnostic", + "codeql-action", +]; /** * Known tags for diagnostics. There is currently only "internal-error", @@ -84,22 +98,16 @@ export type DiagnosticMessage = DiagnosticMessageOptions & { source: DiagnosticSource; }; -/** Represents a diagnostic message that has not yet been written to the database. */ -interface UnwrittenDiagnostic { - /** The diagnostic message that has not yet been written. */ - diagnostic: DiagnosticMessage; - /** The language the diagnostic is for. */ - language: Language; +/** Represents a diagnostic message that has not yet been saved to the database. */ +interface TemporaryDiagnostic { + /** The path to which the diagnostic has temporarily been written to. */ + path: string; + /** The language the diagnostic is for, if any. */ + language?: Language; } -/** A list of diagnostics which have not yet been written to disk. */ -let unwrittenDiagnostics: UnwrittenDiagnostic[] = []; - -/** - * A list of diagnostics which have not yet been written to disk, - * and where the language does not matter. - */ -let unwrittenDefaultLanguageDiagnostics: DiagnosticMessage[] = []; +/** A list of diagnostics which have not yet been saved to the database. */ +let temporaryDiagnostics: TemporaryDiagnostic[] = []; /** * Counter used to generate a unique suffix for each diagnostic filename, so that @@ -128,6 +136,54 @@ export function makeDiagnostic( }; } +/** + * Gets a path relative to {@link basePath} where diagnostics for {@link language} should be stored at. + */ +export function getLanguageDiagnosticsPath( + basePath: string, + language: Language, +) { + return path.resolve( + basePath, + language, + ...CODEQL_ACTION_DIAGNOSTIC_SUBDIR_PARTS, + ); +} + +/** + * Gets a path relative to {@link tmpDir} where diagnostics should temporarily be stored + * until they can be moved to the database. + */ +export function getTempDiagnosticsRoot(tmpDir: string): string { + return path.resolve(tmpDir, TEMP_DIAGNOSTIC_DIR_NAME); +} + +/** + * Gets a path relative to {@link tmpDir} where diagnostics for {@link language} + * can temporarily be stored at before the database is initialised. If {@link language} + * is `undefined`, then a non-language-specific path is returned. + */ +export function getTempLanguageDiagnosticsPath( + tmpDir: string, + language?: Language, +) { + const root = getTempDiagnosticsRoot(tmpDir); + + if (language !== undefined) { + return getLanguageDiagnosticsPath(root, language); + } + + return path.resolve(root, ...CODEQL_ACTION_DIAGNOSTIC_SUBDIR_PARTS); +} + +/** Gets the path where diagnostics for {@link language} should be stored in the database. */ +export function getDatabaseDiagnosticsPath( + config: ActionConfig<"dbLocation">, + language: Language, +) { + return getLanguageDiagnosticsPath(config.dbLocation, language); +} + /** * Adds the given diagnostic to the database. If the database does not yet exist, * the diagnostic will be written to it once it has been created. @@ -137,32 +193,34 @@ export function makeDiagnostic( * @param diagnostic The diagnostic message to add to the database. */ export function addDiagnostic( - config: Config, + config: ActionConfig<"dbLocation" | "tempDir">, language: Language, diagnostic: DiagnosticMessage, + logger: Logger = getActionsLogger(), ) { - const logger = getActionsLogger(); const databasePath = language ? getCodeQLDatabasePath(config, language) : config.dbLocation; // Check that the database exists before writing to it. If the database does not yet exist, - // store the diagnostic in memory and write it later. - if (existsSync(databasePath)) { - writeDiagnostic(config, language, diagnostic); + // store the diagnostic in a temporary location and move it to the database later. + if (fs.existsSync(databasePath)) { + writeDiagnostic({ logger }, config, language, diagnostic); } else { logger.debug( `Writing a diagnostic for ${language}, but the database at ${databasePath} does not exist yet.`, ); - unwrittenDiagnostics.push({ diagnostic, language }); + // Write the diagnostic to a temporary location. + writeTemporaryDiagnosticFile(logger, config.tempDir, language, diagnostic); } } /** Adds a diagnostic that is not specific to any language. */ export function addNoLanguageDiagnostic( - config: Config | undefined, + config: ActionConfig<"dbLocation" | "languages" | "tempDir"> | undefined, diagnostic: DiagnosticMessage, + logger: Logger = getActionsLogger(), ) { if (config !== undefined) { addDiagnostic( @@ -173,10 +231,74 @@ export function addNoLanguageDiagnostic( diagnostic, ); } else { - unwrittenDefaultLanguageDiagnostics.push(diagnostic); + logger.debug( + `Writing a diagnostic not associated with any language, but we have no configuration to tell us where the database is yet.`, + ); + + // Write the diagnostic to a temporary location. + writeTemporaryDiagnosticFile( + logger, + getTemporaryDirectory(), + undefined, + diagnostic, + ); + } +} + +/** + * Writes {@link diagnostic} for an optional {@link language} to a subdirectory of {@link tempDir} + * and tracks it as a diagnostic that was written to a temporary location. + */ +function writeTemporaryDiagnosticFile( + logger: Logger, + tempDir: string, + language: Language | undefined, + diagnostic: DiagnosticMessage, +) { + const tempDiagnosticsPath = getTempLanguageDiagnosticsPath(tempDir, language); + + try { + // Write the diagnostic to a temporary location. + const diagnosticPath = writeDiagnosticFile(tempDiagnosticsPath, diagnostic); + + // Track the temporary file. + temporaryDiagnostics.push({ path: diagnosticPath, language }); + } catch (err) { + logger.warning( + `Unable to write temporary diagnostic to '${tempDiagnosticsPath}': ${getErrorMessage(err)}\n\n${JSON.stringify(diagnostic)}`, + ); } } +/** + * Writes {@link diagnostic} to a file in {@link diagnosticsPath}. + */ +function writeDiagnosticFile( + diagnosticsPath: string, + diagnostic: DiagnosticMessage, +): string { + // Create the directory if it doesn't exist yet. + fs.mkdirSync(diagnosticsPath, { recursive: true }); + + // Include a monotonically increasing suffix to avoid filename collisions + // between diagnostics produced within the same millisecond. + const uniqueSuffix = (diagnosticCounter++).toString(); + // We should only need to remove colons, but to be defensive, only allow a restricted set of + // characters. + const sanitizedTimestamp = diagnostic.timestamp.replace( + /[^a-zA-Z0-9.-]/g, + "", + ); + const jsonPath = path.resolve( + diagnosticsPath, + `codeql-action-${sanitizedTimestamp}-${uniqueSuffix}.json`, + ); + + fs.writeFileSync(jsonPath, JSON.stringify(diagnostic)); + + return jsonPath; +} + /** * Writes the given diagnostic to the database. * @@ -185,78 +307,94 @@ export function addNoLanguageDiagnostic( * @param diagnostic The diagnostic message to add to the database. */ function writeDiagnostic( - config: Config, - language: Language | undefined, + action: ActionState<["Logger"]>, + config: ActionConfig<"dbLocation">, + language: Language, diagnostic: DiagnosticMessage, ) { - const logger = getActionsLogger(); - const databasePath = language - ? getCodeQLDatabasePath(config, language) - : config.dbLocation; - const diagnosticsPath = path.resolve( - databasePath, - "diagnostic", - "codeql-action", - ); + const diagnosticsPath = getDatabaseDiagnosticsPath(config, language); try { - // Create the directory if it doesn't exist yet. - mkdirSync(diagnosticsPath, { recursive: true }); - - // Include a monotonically increasing suffix to avoid filename collisions - // between diagnostics produced within the same millisecond. - const uniqueSuffix = (diagnosticCounter++).toString(); - // We should only need to remove colons, but to be defensive, only allow a restricted set of - // characters. - const sanitizedTimestamp = diagnostic.timestamp.replace( - /[^a-zA-Z0-9.-]/g, - "", - ); - const jsonPath = path.resolve( - diagnosticsPath, - `codeql-action-${sanitizedTimestamp}-${uniqueSuffix}.json`, - ); - - writeFileSync(jsonPath, JSON.stringify(diagnostic)); + writeDiagnosticFile(diagnosticsPath, diagnostic); } catch (err) { - logger.warning(`Unable to write diagnostic message to database: ${err}`); - logger.debug(JSON.stringify(diagnostic)); + action.logger.warning( + `Unable to write diagnostic message to database: ${err}`, + ); + action.logger.debug(JSON.stringify(diagnostic)); } } -/** Report if there are unwritten diagnostics and write them to the log. */ -export function logUnwrittenDiagnostics() { - const logger = getActionsLogger(); - const num = unwrittenDiagnostics.length; - if (num > 0) { - logger.warning( - `${num} diagnostic(s) could not be written to the database and will not appear on the Tool Status Page.`, +/** Report if there are temporary diagnostics and write them to the log. */ +export function logTemporaryDiagnostics(action: ActionState<["Logger"]>) { + const num = temporaryDiagnostics.length; + + if (num > 0 && action.logger.isDebug()) { + action.logger.startGroup("Diagnostics in temporary location"); + action.logger.debug( + `${num} diagnostic(s) were not moved to the database and remain in the temporary directory.`, ); - for (const unwritten of unwrittenDiagnostics) { - logger.debug(JSON.stringify(unwritten.diagnostic)); + for (const temporary of temporaryDiagnostics) { + try { + action.logger.debug(fs.readFileSync(temporary.path, "utf-8")); + } catch (err) { + action.logger.debug( + `Failed to read diagnostics from temporary location at '${temporary.path}': ${getErrorMessage(err)}`, + ); + } } + + action.logger.endGroup(); } } -/** Writes all unwritten diagnostics to disk. */ -export function flushDiagnostics(config: Config) { - const logger = getActionsLogger(); +/** Relocates all temporary diagnostics to the respective databases. */ +export function flushDiagnostics( + action: ActionState<["Logger"]>, + config: ActionConfig<"dbLocation" | "languages">, +) { + const diagnosticsCount = temporaryDiagnostics.length; + action.logger.debug( + `Moving ${diagnosticsCount} diagnostic(s) to their respective databases.`, + ); - const diagnosticsCount = - unwrittenDiagnostics.length + unwrittenDefaultLanguageDiagnostics.length; - logger.debug(`Writing ${diagnosticsCount} diagnostic(s) to database.`); + const failedFlushDiagnostics: TemporaryDiagnostic[] = []; + for (const temporary of temporaryDiagnostics) { + // If `temporary.language` is `undefined`, then we didn't have a `config` at the time that + // `addNoLanguageDiagnostic` was called. In that case, we arbitrarily choose the first + // configured language here like we would have done in `addNoLanguageDiagnostic`. + const directory = getDatabaseDiagnosticsPath( + config, + temporary.language ?? config.languages[0], + ); + const filename = path.basename(temporary.path); + const destination = path.join(directory, filename); - for (const unwritten of unwrittenDiagnostics) { - writeDiagnostic(config, unwritten.language, unwritten.diagnostic); - } - for (const unwritten of unwrittenDefaultLanguageDiagnostics) { - addNoLanguageDiagnostic(config, unwritten); + try { + fs.mkdirSync(directory, { recursive: true }); + try { + fs.renameSync(temporary.path, destination); + } catch (renameErr: unknown) { + // Rethrow the error if it isn't an EXDEV one. + if (!isErrnoException(renameErr) || renameErr.code !== "EXDEV") { + throw renameErr; + } + + // The error was an EXDEV one: try to copy the file and delete the temporary one. + fs.copyFileSync(temporary.path, destination); + fs.unlinkSync(temporary.path); + } + } catch (err) { + action.logger.warning( + `Failed to relocate '${temporary.path}' to '${destination}': ${getErrorMessage(err)}`, + ); + + failedFlushDiagnostics.push(temporary); + } } - // Reset the unwritten diagnostics arrays. - unwrittenDiagnostics = []; - unwrittenDefaultLanguageDiagnostics = []; + // Reset the temporary diagnostics arrays. + temporaryDiagnostics = failedFlushDiagnostics; } /** diff --git a/src/diff-informed-analysis-utils.test.ts b/src/diff-informed-analysis-utils.test.ts index e07240e322..76e5f33b4d 100644 --- a/src/diff-informed-analysis-utils.test.ts +++ b/src/diff-informed-analysis-utils.test.ts @@ -10,7 +10,6 @@ import { exportedForTesting, } from "./diff-informed-analysis-utils"; import { Feature, FeatureEnablement, initFeatures } from "./feature-flags"; -import { getRunnerLogger } from "./logging"; import { parseRepositoryNwo } from "./repository"; import { setupTests, @@ -19,6 +18,7 @@ import { mockFeatureFlagApiEndpoint, setupActionsVars, makeMacro, + RecordingLogger, } from "./testing-utils"; import { GitHubVariant, withTmpDir } from "./util"; import type { GitHubVersion } from "./util"; @@ -55,7 +55,7 @@ const testShouldPerformDiffInformedAnalysis = makeMacro({ setupActionsVars(tmpDir, tmpDir); const testCase = { ...defaultTestCase, ...partialTestCase }; - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const codeql = mockCodeQLVersion(testCase.codeQLVersion); if (testCase.diffInformedQueriesEnvVar !== undefined) { @@ -182,7 +182,7 @@ test.serial( async (t) => { await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const codeql = mockCodeQLVersion("2.21.0"); const features = createFeatures([Feature.DiffInformedQueries]); @@ -207,7 +207,7 @@ test.serial( async (t) => { await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const codeql = mockCodeQLVersion("2.21.0"); // A features implementation whose getValue rejects, simulating an // unexpected failure when determining whether diff-informed analysis @@ -237,7 +237,7 @@ test.serial( async (t) => { await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const codeql = mockCodeQLVersion("2.21.0"); const features = createFeatures([Feature.DiffInformedQueries]); @@ -274,7 +274,7 @@ test.serial( async (t) => { await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const codeql = mockCodeQLVersion("2.21.0"); const features = createFeatures([Feature.DiffInformedQueries]); @@ -313,7 +313,7 @@ function runGetDiffRanges(changes: number, patch: string[] | undefined): any { changes, patch: patch?.join("\n"), }, - getRunnerLogger(true), + new RecordingLogger(), ); } diff --git a/src/doc-url.ts b/src/doc-url.ts index c624817e90..c75d47a68d 100644 --- a/src/doc-url.ts +++ b/src/doc-url.ts @@ -3,7 +3,6 @@ */ export enum DocUrl { - ASSIGNING_PERMISSIONS_TO_JOBS = "https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs", AUTOMATIC_BUILD_FAILED = "https://docs.github.com/en/code-security/code-scanning/troubleshooting-code-scanning/automatic-build-failed", CODEQL_BUILD_MODES = "https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages#codeql-build-modes", DEFINE_ENV_VARIABLES = "https://docs.github.com/en/actions/learn-github-actions/variables#defining-environment-variables-for-a-single-workflow", @@ -13,4 +12,6 @@ export enum DocUrl { SPECIFY_BUILD_STEPS_MANUALLY = "https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages#about-specifying-build-steps-manually", SYSTEM_REQUIREMENTS = "https://codeql.github.com/docs/codeql-overview/system-requirements/", TRACK_CODE_SCANNING_ALERTS_ACROSS_RUNS = "https://docs.github.com/en/code-security/reference/code-scanning/sarif-support-for-code-scanning#data-for-preventing-duplicated-alerts", + /** Blog post about traced analysis being unsupported on macOS 27 and with Xcode 27. */ + UNSUPPORTED_TRACED_ANALYSIS_MACOS27 = "https://github.blog/changelog/2026-10-19-codeql-changes-for-macos-27-xcode-27-and-swift-6-4/", } diff --git a/src/environment.test.ts b/src/environment.test.ts new file mode 100644 index 0000000000..2c8a8a8f1c --- /dev/null +++ b/src/environment.test.ts @@ -0,0 +1,12 @@ +import test from "ava"; + +import { Env, ReadOnlyEnv } from "./environment"; +import { getTestEnv, setupTests } from "./testing-utils"; + +setupTests(test); + +test("isTestingEnv() is true", (t) => { + t.true(new ReadOnlyEnv(process.env).isTestingEnv()); + t.true(new Env(process.env).isTestingEnv()); + t.true(getTestEnv().isTestingEnv()); +}); diff --git a/src/environment.ts b/src/environment.ts index 29665512c2..f3d38075ea 100644 --- a/src/environment.ts +++ b/src/environment.ts @@ -1,3 +1,10 @@ +import * as core from "@actions/core"; + +/** + * This constant is set in `ava.setup.mjs` for tests. + */ +declare const __CODEQL_ACTION_TEST_ENV__: string | undefined; + /** * Environment variables used by Default Setup to communicate the private registry proxy configuration. */ @@ -63,6 +70,12 @@ export enum EnvVar { /** Whether the CodeQL Action has already warned the user about low disk space. */ HAS_WARNED_ABOUT_DISK_SPACE = "CODEQL_ACTION_HAS_WARNED_ABOUT_DISK_SPACE", + /** + * Whether a step in this job has already set up CodeQL. Steps that run afterwards may be holding + * a path into the toolcache, so we must not delete anything from it. + */ + HAS_SET_UP_CODEQL = "CODEQL_ACTION_HAS_SET_UP_CODEQL", + /** Whether the `setup-codeql` action has been run. */ SETUP_CODEQL_ACTION_HAS_RUN = "CODEQL_ACTION_SETUP_CODEQL_HAS_RUN", @@ -152,9 +165,21 @@ export enum EnvVar { */ SARIF_DUMP_DIR = "CODEQL_ACTION_SARIF_DUMP_DIR", + /** + * Whether to skip generating a failed SARIF file. Intended for testing purposes. + * This setting is more specific than `CODEQL_ACTION_TEST_MODE` and + * `CODEQL_ACTION_SKIP_SARIF_UPLOAD`, which imply this option. + * + * Setting this to `false` takes precedence over `CODEQL_ACTION_TEST_MODE: true` or + * `CODEQL_ACTION_SKIP_SARIF_UPLOAD: true`. + */ + SKIP_GENERATE_FAILED_SARIF = "CODEQL_ACTION_SKIP_GENERATE_FAILED_SARIF", + /** * Whether to skip uploading SARIF results to GitHub. Intended for testing purposes. * This setting is more specific than `CODEQL_ACTION_TEST_MODE`, which implies this option. + * + * Setting this to `false` takes precedence over `CODEQL_ACTION_TEST_MODE: true`. */ SKIP_SARIF_UPLOAD = "CODEQL_ACTION_SKIP_SARIF_UPLOAD", @@ -205,8 +230,17 @@ export enum ActionsEnvVars { RUNNER_TOOL_CACHE = "RUNNER_TOOL_CACHE", } +/** Environment variables which are not specific to CodeQL. */ +export enum SystemEnvVar { + /** + * Used by Node and related tools to indicate what kind of environment we are running in. + */ + NODE_ENV = "NODE_ENV", +} + /** A type representing all known environment variables. */ -export type KnownEnvVar = EnvVar | ActionsEnvVars | RegistryProxyVars; +export type KnownEnvVar = + EnvVar | ActionsEnvVars | RegistryProxyVars | SystemEnvVar; /** * Gets an environment variable, but throws an error if it is not set. @@ -256,8 +290,8 @@ export function getOptionalEnvVar(paramName: string): string | undefined { * in tests, while clearly signalling in regular code that the consumer of the `ReadOnlyEnv` instance * will only read from it. */ -export class ReadOnlyEnv { - constructor(protected readonly vars: Record) {} +export class ReadOnlyEnv { + constructor(protected readonly vars: Record) {} /** Clones the object while detaching the underlying environment from the original. */ public clone(): this { @@ -265,10 +299,24 @@ export class ReadOnlyEnv { } /** Gets a copy of the underlying environment. */ - public get(): Record { + public get(): Record { return { ...this.vars }; } + /** Gets a copy of the underlying environment, where the values are not `undefined`. */ + public getDefined(): Record { + const result: Record = {}; + + for (const [key, val] of Object.entries(this.vars)) { + if (val === undefined) { + continue; + } + result[key] = val; + } + + return result; + } + /** Tries to get the value for `name` and throws if there isn't one. */ public getRequired(name: string): string { return getRequiredEnvVar(this.vars, name); @@ -280,9 +328,29 @@ export class ReadOnlyEnv { } /** Gets the entries of the underlying `ProcessEnv`. */ - public entries(): Array<[string, T]> { + public entries(): Array<[string, string | undefined]> { return Object.entries(this.vars); } + + /** + * Gets a value indicating whether we should skip uploads of + * all kinds (SARIF results, status reports, DBs, ...). + * + * This is not guaranteed to be set in all test environments. + */ + public isSkippingUploadsInTests(): boolean { + return this.getOptional(EnvVar.TEST_MODE) === "true"; + } + + /** + * Gets a value indicative of whether we are in a testing environment + * by testing whether the value of the `NODE_ENV` variable is "test". + * This is expected to be the case if e.g. `ava` is running the tests + * or if this instance was constructed by `getTestEnv`. + */ + public isTestingEnv(): boolean { + return __CODEQL_ACTION_TEST_ENV__ === "unit-test"; + } } /** @@ -290,17 +358,54 @@ export class ReadOnlyEnv { * Use `ReadOnlyEnv` instead if you only plan to read from the environment. * This type allows writing to the environment. */ -export class Env< - T extends string | undefined = string | undefined, -> extends ReadOnlyEnv { +export class Env extends ReadOnlyEnv { private changed: boolean = false; /** Sets an environment variable. */ - public set(name: string, value: T): void { + public set(name: string, value: string | undefined): void { this.vars[name] = value; this.changed = true; } + /** Sets all environment variables given by `vars`. */ + public setAll(vars: Record): void { + for (const [key, val] of Object.entries(vars)) { + this.set(key, val); + } + } + + /** + * Wrapper around `core.exportVariable` which does not call `core.exportVariable` + * when running unit tests. This is important, because otherwise `core.exportVariable` + * sets environment variables for other steps in a workflow when we run unit tests in CI. + * + * @param name The name of the environment variable to set and export. + * @param val The value to set and export for the environment variable. + */ + public export(name: string, val: string): void { + // Setting the environment variable for this instance is always OK, including + // in tests, since we use fresh `Env` instances whenever needed. This allows + // tests to pass that rely on that part of the `core.exportVariable` behaviour. + this.set(name, val); + + // Call `core.exportVariable` whenever we are not in a test environment. + if (!this.isTestingEnv()) { + core.exportVariable(name, val); + } + } + + /** + * Set some initial environment variables that we can set even without + * knowing what version of CodeQL we're running. + */ + public initialise(version: string) { + this.export(EnvVar.FEATURE_MULTI_LANGUAGE, "false"); + this.export(EnvVar.FEATURE_SANDWICH, "false"); + this.export(EnvVar.FEATURE_SARIF_COMBINE, "true"); + this.export(EnvVar.FEATURE_WILL_UPLOAD, "true"); + this.export(EnvVar.VERSION, version); + } + /** Gets a value indicating whether `set` was called at least once. */ public hasChanged(): boolean { return this.changed; @@ -311,3 +416,34 @@ export class Env< export function getEnv(env: NodeJS.ProcessEnv = process.env): Env { return new Env(env); } + +/** + * Returns whether we are in test mode. This is used by CodeQL Action PR checks. + * + * In test mode, we skip several uploads (SARIF results, status reports, DBs, ...). + * + * @deprecated + * The purpose of this function is ambiguous. Use `isSkippingUploadsInTests` on + * a `ReadOnlyEnv` instance instead for equivalent behaviour. Use `isTestingEnv` + * to determine if we are running in a unit test. + */ +export function isInTestMode(): boolean { + return getEnv().isSkippingUploadsInTests(); +} + +/** + * Wrapper around `core.exportVariable` which does not call `core.exportVariable` + * when running unit tests. This is important, because otherwise `core.exportVariable` + * sets environment variables for other steps in a workflow when we run unit tests in CI. + * + * @deprecated Use `export` on an `Env` instance instead. + */ +export function exportEnvVar(name: string, val: any): void { + const env = getEnv(); + + if (typeof val === "string") { + env.export(name, val); + } else { + env.export(name, JSON.stringify(val)); + } +} diff --git a/src/errors/index.ts b/src/errors/index.ts new file mode 100644 index 0000000000..c2b947d3fa --- /dev/null +++ b/src/errors/index.ts @@ -0,0 +1,88 @@ +import * as json from "../json"; + +/** + * If {@link error} is not already an instance of {@link Error}, then this function constructs + * an {@link Error} with a string representation of {@link error} as the message. + */ +export function wrapError(error: unknown): Error { + return error instanceof Error ? error : new Error(String(error)); +} + +/** + * Returns an appropriate message for the error. + * + * If the error is an {@link Error} instance, this returns the error message without + * an `Error: ` prefix. + */ +export function getErrorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** + * Approximates whether {@link error} is like a {@link NodeJS.ErrnoException}. + * We only typically care about the `code` property, so that's what we check for here. + */ +export function isErrnoException( + error: unknown, +): error is NodeJS.ErrnoException { + return ( + typeof error === "object" && + error !== null && + "code" in error && + typeof error.code === "string" + ); +} + +/** + * Decides whether `e` is a disk-related error outside of our control + * that should be classified as a `ConfigurationError`. + * + * @param e The error to check. + * @returns True if the error should be treated as a `ConfigurationError` or false if not. + */ +export function isDiskConfigurationError(e: unknown): boolean { + if (!(e instanceof Error)) { + return false; + } + + return ( + // out of disk space + e.message.includes("ENOSPC") || + // access denied + e.message.includes("EACCES") + ); +} + +/** + * An Error class that indicates an error that occurred due to + * a misconfiguration of the action or the CodeQL CLI. + */ +export class ConfigurationError extends Error {} + +/** Minimal representation of errors resulting from HTTP requests. */ +export class HTTPError extends Error { + public status: number; + + constructor(message: string, status: number) { + super(message); + this.status = status; + } +} + +/** + * Tries to convert {@link arg} to a {@link HTTPError}, but returns `undefined` if + * {@link arg} is not like a {@link HTTPError}. + */ +export function asHTTPError(arg: any): HTTPError | undefined { + if (!json.isObject(arg) || !json.isString(arg.message)) { + return undefined; + } + if (Number.isInteger(arg.status)) { + return new HTTPError(arg.message, arg.status as number); + } + // See https://github.com/actions/toolkit/blob/acb230b99a46ed33a3f04a758cd68b47b9a82908/packages/tool-cache/src/tool-cache.ts#L19 + if (Number.isInteger(arg.httpStatusCode)) { + return new HTTPError(arg.message, arg.httpStatusCode as number); + } + return undefined; +} diff --git a/src/feature-flags.test.ts b/src/feature-flags.test.ts index d8b5eea04d..7b1c1ef3e5 100644 --- a/src/feature-flags.test.ts +++ b/src/feature-flags.test.ts @@ -4,6 +4,7 @@ import * as path from "path"; import test from "ava"; import * as defaults from "./defaults.json"; +import { getEnv } from "./environment"; import { Feature, featureConfig, @@ -26,12 +27,12 @@ import { setupTests, stubFeatureFlagApiEndpoint, } from "./testing-utils"; -import { GitHubVariant, initializeEnvironment, withTmpDir } from "./util"; +import { GitHubVariant, withTmpDir } from "./util"; setupTests(test); test.beforeEach(() => { - initializeEnvironment("1.2.3"); + getEnv().initialise("1.2.3"); }); test.serial( diff --git a/src/feature-flags.ts b/src/feature-flags.ts index 7abccf60cb..3d05cbe9db 100644 --- a/src/feature-flags.ts +++ b/src/feature-flags.ts @@ -6,6 +6,7 @@ import * as semver from "semver"; import { getApiClient } from "./api-client"; import type { CodeQL } from "./codeql"; import * as defaults from "./defaults.json"; +import { Feature } from "./feature-flags/features"; import { Logger } from "./logging"; import { CODEQL_OVERLAY_MINIMUM_VERSION, @@ -21,6 +22,8 @@ import { RepositoryNwo } from "./repository"; import { ToolsFeature } from "./tools-features"; import * as util from "./util"; +export { Feature } from "./feature-flags/features"; + const DEFAULT_VERSION_FEATURE_FLAG_PREFIX = "default_codeql_version_"; const DEFAULT_VERSION_FEATURE_FLAG_SUFFIX = "_enabled"; @@ -61,116 +64,6 @@ export interface CodeQLDefaultVersionInfo { toolsFeatureFlagsValid?: boolean; } -/** - * Features as named by the GitHub API endpoint. - * - * Do not include the `codeql_action_` prefix as this is stripped by the API - * endpoint. - * - * Legacy features should end with `_enabled`. - */ -export enum Feature { - /** Allows supported properties of configuration files to be merged. */ - AllowMergeConfigFiles = "allow_merge_config_files", - /** Controls whether we allow multiple values for the `analysis-kinds` input. */ - AllowMultipleAnalysisKinds = "allow_multiple_analysis_kinds", - CleanupTrapCaches = "cleanup_trap_caches", - /** Whether to allow the `config-file` input to be specified via a repository property. */ - ConfigFileRepositoryProperty = "config_file_repository_property", - CppDependencyInstallation = "cpp_dependency_installation_enabled", - CsharpCacheBuildModeNone = "csharp_cache_bmn", - CsharpNewCacheKey = "csharp_new_cache_key", - DiffInformedQueries = "diff_informed_queries", - DisableCsharpBuildless = "disable_csharp_buildless", - DisableJavaBuildlessEnabled = "disable_java_buildless_enabled", - DisableKotlinAnalysisEnabled = "disable_kotlin_analysis_enabled", - ExportDiagnosticsEnabled = "export_diagnostics_enabled", - /** - * Emergency override that forces the CodeQL CLI to use the JGit-based Git backend instead of its - * default backend selection. - */ - ForceJGit = "force_jgit", - ForceNightly = "force_nightly", - IgnoreGeneratedFiles = "ignore_generated_files", - JavaNetworkDebugging = "java_network_debugging", - OverlayAnalysis = "overlay_analysis", - OverlayAnalysisCodeScanningCpp = "overlay_analysis_code_scanning_cpp", - OverlayAnalysisCodeScanningCsharp = "overlay_analysis_code_scanning_csharp", - OverlayAnalysisCodeScanningGo = "overlay_analysis_code_scanning_go", - OverlayAnalysisCodeScanningJava = "overlay_analysis_code_scanning_java", - OverlayAnalysisCodeScanningJavascript = "overlay_analysis_code_scanning_javascript", - OverlayAnalysisCodeScanningPython = "overlay_analysis_code_scanning_python", - OverlayAnalysisCodeScanningRuby = "overlay_analysis_code_scanning_ruby", - OverlayAnalysisCpp = "overlay_analysis_cpp", - OverlayAnalysisCsharp = "overlay_analysis_csharp", - /** Disable TRAP caching when overlay analysis is enabled. */ - OverlayAnalysisDisableTrapCaching = "overlay_analysis_disable_trap_caching", - OverlayAnalysisGo = "overlay_analysis_go", - OverlayAnalysisJava = "overlay_analysis_java", - OverlayAnalysisJavascript = "overlay_analysis_javascript", - /** - * When set, chooses the default CodeQL CLI version as the highest version that is both enabled by - * feature flags and present as an overlay-base database in the Actions cache for the configured - * languages. Falls back to the highest feature flagged version if no intersecting overlay-base - * database exists in the cache. - */ - OverlayAnalysisMatchCodeqlVersion = "overlay_analysis_match_codeql_version", - /** - * Like `OverlayAnalysisMatchCodeqlVersion`, but only logs a diagnostic with the version that - * would have been chosen instead of actually changing the default CodeQL CLI version. - * `OverlayAnalysisMatchCodeqlVersion` overrides this flag. - */ - OverlayAnalysisMatchCodeqlVersionDryRun = "overlay_analysis_match_codeql_version_dry_run", - /** - * Lowers the overlay minimum available disk space to 8 GB. The lowest enabled limit wins; if - * none are enabled, the default applies. - */ - OverlayAnalysisMinDisk8Gb = "overlay_analysis_min_disk_8_gb", - /** - * Lowers the overlay minimum available disk space to 9 GB. The lowest enabled limit wins; if - * none are enabled, the default applies. - */ - OverlayAnalysisMinDisk9Gb = "overlay_analysis_min_disk_9_gb", - /** - * Lowers the overlay minimum available disk space to 10 GB. The lowest enabled limit wins; if - * none are enabled, the default applies. - */ - OverlayAnalysisMinDisk10Gb = "overlay_analysis_min_disk_10_gb", - /** - * Lowers the overlay minimum available disk space to 11 GB. The lowest enabled limit wins; if - * none are enabled, the default applies. - */ - OverlayAnalysisMinDisk11Gb = "overlay_analysis_min_disk_11_gb", - /** - * Lowers the overlay minimum available disk space to 12 GB. The lowest enabled limit wins; if - * none are enabled, the default applies. - */ - OverlayAnalysisMinDisk12Gb = "overlay_analysis_min_disk_12_gb", - /** - * Lowers the overlay minimum available disk space to 13 GB. The lowest enabled limit wins; if - * none are enabled, the default applies. - */ - OverlayAnalysisMinDisk13Gb = "overlay_analysis_min_disk_13_gb", - OverlayAnalysisPython = "overlay_analysis_python", - OverlayAnalysisRuby = "overlay_analysis_ruby", - /** Controls whether hardware checks are skipped for overlay analysis. */ - OverlayAnalysisSkipResourceChecks = "overlay_analysis_skip_resource_checks", - /** Controls whether the Actions cache is checked for overlay build outcomes. */ - OverlayAnalysisStatusCheck = "overlay_analysis_status_check", - /** Controls whether overlay build failures on the default branch are stored in the Actions cache. */ - OverlayAnalysisStatusSave = "overlay_analysis_status_save", - QaTelemetryEnabled = "qa_telemetry_enabled", - /** Routes (some) API requests through the registry proxy. */ - ProxyApiRequests = "proxy_api_requests", - /** Note that this currently only disables baseline file coverage information. */ - SkipFileCoverageOnPrs = "skip_file_coverage_on_prs", - StartProxyUseFeaturesRelease = "start_proxy_use_features_release", - /** Whether to allow the `tools` input to be specified via a repository property. */ - ToolsRepositoryProperty = "tools_repository_property", - UploadOverlayDbToApi = "upload_overlay_db_to_api", - ValidateDbConfig = "validate_db_config", -} - export type FeatureConfig = { /** * Default value in environments where the feature flags API is not available, @@ -211,9 +104,9 @@ export const featureConfig = { envVar: "CODEQL_ACTION_ALLOW_MULTIPLE_ANALYSIS_KINDS", minimumVersion: undefined, }, - [Feature.CleanupTrapCaches]: { + [Feature.CheckUnsupportedTracedAnalysis]: { defaultValue: false, - envVar: "CODEQL_ACTION_CLEANUP_TRAP_CACHES", + envVar: "CODEQL_ACTION_CHECK_UNSUPPORTED_TRACED_ANALYSIS", minimumVersion: undefined, }, [Feature.ConfigFileRepositoryProperty]: { @@ -225,7 +118,7 @@ export const featureConfig = { defaultValue: false, envVar: "CODEQL_EXTRACTOR_CPP_AUTOINSTALL_DEPENDENCIES", legacyApi: true, - minimumVersion: "2.15.0", + minimumVersion: undefined, }, [Feature.CsharpCacheBuildModeNone]: { defaultValue: false, @@ -364,21 +257,6 @@ export const featureConfig = { minimumVersion: CODEQL_OVERLAY_MINIMUM_VERSION_RUBY, }, // Other overlay-related feature flags - [Feature.OverlayAnalysisDisableTrapCaching]: { - defaultValue: false, - envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_DISABLE_TRAP_CACHING", - minimumVersion: undefined, - }, - [Feature.OverlayAnalysisMatchCodeqlVersion]: { - defaultValue: false, - envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_MATCH_CODEQL_VERSION", - minimumVersion: undefined, - }, - [Feature.OverlayAnalysisMatchCodeqlVersionDryRun]: { - defaultValue: false, - envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_MATCH_CODEQL_VERSION_DRY_RUN", - minimumVersion: undefined, - }, [Feature.OverlayAnalysisMinDisk8Gb]: { defaultValue: false, envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_MIN_DISK_8_GB", @@ -446,6 +324,11 @@ export const featureConfig = { envVar: "CODEQL_ACTION_START_PROXY_USE_FEATURES_RELEASE", minimumVersion: undefined, }, + [Feature.AbortUnsupportedTracedAnalysis]: { + defaultValue: false, + envVar: "CODEQL_ACTION_ABORT_UNSUPPORTED_TRACED_ANALYSIS", + minimumVersion: undefined, + }, [Feature.ToolsRepositoryProperty]: { defaultValue: false, envVar: "CODEQL_ACTION_TOOLS_REPOSITORY_PROPERTY", @@ -579,7 +462,7 @@ class OfflineFeatures implements FeatureEnablement { // Never use this feature if the CLI version explicitly can't support it. const minimumVersion = config.minimumVersion; if (codeql && minimumVersion) { - if (!(await util.codeQlVersionAtLeast(codeql, minimumVersion))) { + if (!(await codeql.isVersionAtLeast(minimumVersion))) { this.logger.debug( `Feature ${feature} is disabled because the CodeQL CLI version is older than the minimum ` + `version ${minimumVersion}.`, diff --git a/src/feature-flags/features.ts b/src/feature-flags/features.ts new file mode 100644 index 0000000000..795f8f57ba --- /dev/null +++ b/src/feature-flags/features.ts @@ -0,0 +1,100 @@ +/** + * Features as named by the GitHub API endpoint. + * + * Do not include the `codeql_action_` prefix as this is stripped by the API + * endpoint. + * + * Legacy features should end with `_enabled`. + */ +export enum Feature { + /** Allows supported properties of configuration files to be merged. */ + AllowMergeConfigFiles = "allow_merge_config_files", + /** Controls whether we allow multiple values for the `analysis-kinds` input. */ + AllowMultipleAnalysisKinds = "allow_multiple_analysis_kinds", + /** + * Whether to check for unsupported traced analysis. Primarily intended as an override to disable + * the check if it causes problems somehow. + */ + CheckUnsupportedTracedAnalysis = "check_unsupported_traced_analysis", + /** Whether to allow the `config-file` input to be specified via a repository property. */ + ConfigFileRepositoryProperty = "config_file_repository_property", + CppDependencyInstallation = "cpp_dependency_installation_enabled", + CsharpCacheBuildModeNone = "csharp_cache_bmn", + CsharpNewCacheKey = "csharp_new_cache_key", + DiffInformedQueries = "diff_informed_queries", + DisableCsharpBuildless = "disable_csharp_buildless", + DisableJavaBuildlessEnabled = "disable_java_buildless_enabled", + DisableKotlinAnalysisEnabled = "disable_kotlin_analysis_enabled", + ExportDiagnosticsEnabled = "export_diagnostics_enabled", + /** + * Emergency override that forces the CodeQL CLI to use the JGit-based Git backend instead of its + * default backend selection. + */ + ForceJGit = "force_jgit", + ForceNightly = "force_nightly", + IgnoreGeneratedFiles = "ignore_generated_files", + JavaNetworkDebugging = "java_network_debugging", + OverlayAnalysis = "overlay_analysis", + OverlayAnalysisCodeScanningCpp = "overlay_analysis_code_scanning_cpp", + OverlayAnalysisCodeScanningCsharp = "overlay_analysis_code_scanning_csharp", + OverlayAnalysisCodeScanningGo = "overlay_analysis_code_scanning_go", + OverlayAnalysisCodeScanningJava = "overlay_analysis_code_scanning_java", + OverlayAnalysisCodeScanningJavascript = "overlay_analysis_code_scanning_javascript", + OverlayAnalysisCodeScanningPython = "overlay_analysis_code_scanning_python", + OverlayAnalysisCodeScanningRuby = "overlay_analysis_code_scanning_ruby", + OverlayAnalysisCpp = "overlay_analysis_cpp", + OverlayAnalysisCsharp = "overlay_analysis_csharp", + OverlayAnalysisGo = "overlay_analysis_go", + OverlayAnalysisJava = "overlay_analysis_java", + OverlayAnalysisJavascript = "overlay_analysis_javascript", + /** + * Lowers the overlay minimum available disk space to 8 GB. The lowest enabled limit wins; if + * none are enabled, the default applies. + */ + OverlayAnalysisMinDisk8Gb = "overlay_analysis_min_disk_8_gb", + /** + * Lowers the overlay minimum available disk space to 9 GB. The lowest enabled limit wins; if + * none are enabled, the default applies. + */ + OverlayAnalysisMinDisk9Gb = "overlay_analysis_min_disk_9_gb", + /** + * Lowers the overlay minimum available disk space to 10 GB. The lowest enabled limit wins; if + * none are enabled, the default applies. + */ + OverlayAnalysisMinDisk10Gb = "overlay_analysis_min_disk_10_gb", + /** + * Lowers the overlay minimum available disk space to 11 GB. The lowest enabled limit wins; if + * none are enabled, the default applies. + */ + OverlayAnalysisMinDisk11Gb = "overlay_analysis_min_disk_11_gb", + /** + * Lowers the overlay minimum available disk space to 12 GB. The lowest enabled limit wins; if + * none are enabled, the default applies. + */ + OverlayAnalysisMinDisk12Gb = "overlay_analysis_min_disk_12_gb", + /** + * Lowers the overlay minimum available disk space to 13 GB. The lowest enabled limit wins; if + * none are enabled, the default applies. + */ + OverlayAnalysisMinDisk13Gb = "overlay_analysis_min_disk_13_gb", + OverlayAnalysisPython = "overlay_analysis_python", + OverlayAnalysisRuby = "overlay_analysis_ruby", + /** Controls whether hardware checks are skipped for overlay analysis. */ + OverlayAnalysisSkipResourceChecks = "overlay_analysis_skip_resource_checks", + /** Controls whether the Actions cache is checked for overlay build outcomes. */ + OverlayAnalysisStatusCheck = "overlay_analysis_status_check", + /** Controls whether overlay build failures on the default branch are stored in the Actions cache. */ + OverlayAnalysisStatusSave = "overlay_analysis_status_save", + QaTelemetryEnabled = "qa_telemetry_enabled", + /** Whether we should fail early if we detect that traced analysis is unsupported. */ + AbortUnsupportedTracedAnalysis = "abort_unsupported_traced_analysis", + /** Routes (some) API requests through the registry proxy. */ + ProxyApiRequests = "proxy_api_requests", + /** Note that this currently only disables baseline file coverage information. */ + SkipFileCoverageOnPrs = "skip_file_coverage_on_prs", + StartProxyUseFeaturesRelease = "start_proxy_use_features_release", + /** Whether to allow the `tools` input to be specified via a repository property. */ + ToolsRepositoryProperty = "tools_repository_property", + UploadOverlayDbToApi = "upload_overlay_db_to_api", + ValidateDbConfig = "validate_db_config", +} diff --git a/src/feature-flags/offline-features.test.ts b/src/feature-flags/offline-features.test.ts index 2870ef3b8a..1c3d2a8c1b 100644 --- a/src/feature-flags/offline-features.test.ts +++ b/src/feature-flags/offline-features.test.ts @@ -8,7 +8,7 @@ import { LoggedMessage, setupTests, } from "../testing-utils"; -import { GitHubVariant, initializeEnvironment, withTmpDir } from "../util"; +import { getEnv, GitHubVariant, withTmpDir } from "../util"; import { assertAllFeaturesHaveDefaultValues, @@ -18,7 +18,7 @@ import { setupTests(test); test.beforeEach(() => { - initializeEnvironment("1.2.3"); + getEnv().initialise("1.2.3"); }); test("OfflineFeatures makes no API requests", async (t) => { diff --git a/src/feature-flags/properties.test.ts b/src/feature-flags/properties.test.ts index d3094a8d1c..6544d15d35 100644 --- a/src/feature-flags/properties.test.ts +++ b/src/feature-flags/properties.test.ts @@ -2,7 +2,6 @@ import test from "ava"; import * as sinon from "sinon"; import * as api from "../api-client"; -import { getRunnerLogger } from "../logging"; import { parseRepositoryNwo } from "../repository"; import { RecordingLogger, setupTests } from "../testing-utils"; @@ -19,7 +18,7 @@ test.serial( url: "", data: {}, }); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const mockRepositoryNwo = parseRepositoryNwo("owner/repo"); await t.throwsAsync( properties.loadPropertiesFromApi(logger, mockRepositoryNwo), @@ -39,7 +38,7 @@ test.serial( url: "", data: [{}], }); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const mockRepositoryNwo = parseRepositoryNwo("owner/repo"); await t.throwsAsync( properties.loadPropertiesFromApi(logger, mockRepositoryNwo), @@ -63,7 +62,7 @@ test.serial( { property_name: "also-not-used-by-us", value: ["A", "B", "C"] }, ], }); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const mockRepositoryNwo = parseRepositoryNwo("owner/repo"); await t.notThrowsAsync( properties.loadPropertiesFromApi(logger, mockRepositoryNwo), @@ -86,7 +85,7 @@ test.serial("loadPropertiesFromApi loads known properties", async (t) => { { property_name: "unknown-property", value: "something" }, ] satisfies properties.GitHubPropertiesResponse, }); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const mockRepositoryNwo = parseRepositoryNwo("owner/repo"); const response = await properties.loadPropertiesFromApi( logger, @@ -113,7 +112,7 @@ test.serial("loadPropertiesFromApi parses true boolean property", async (t) => { { property_name: "github-codeql-extra-queries", value: "+queries" }, ] satisfies properties.GitHubPropertiesResponse, }); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const warningSpy = sinon.spy(logger, "warning"); const mockRepositoryNwo = parseRepositoryNwo("owner/repo"); const response = await properties.loadPropertiesFromApi( @@ -141,7 +140,7 @@ test.serial( }, ] satisfies properties.GitHubPropertiesResponse, }); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const warningSpy = sinon.spy(logger, "warning"); const mockRepositoryNwo = parseRepositoryNwo("owner/repo"); const response = await properties.loadPropertiesFromApi( @@ -164,7 +163,7 @@ test.serial( url: "", data: [{ property_name: "github-codeql-extra-queries", value: 123 }], }); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const mockRepositoryNwo = parseRepositoryNwo("owner/repo"); await t.throwsAsync( properties.loadPropertiesFromApi(logger, mockRepositoryNwo), @@ -190,7 +189,7 @@ test.serial( }, ] satisfies properties.GitHubPropertiesResponse, }); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const warningSpy = sinon.spy(logger, "warning"); const mockRepositoryNwo = parseRepositoryNwo("owner/repo"); const response = await properties.loadPropertiesFromApi( diff --git a/src/feature-flags/testing-util.ts b/src/feature-flags/testing-util.ts index 202f2c97b1..46795bdf09 100644 --- a/src/feature-flags/testing-util.ts +++ b/src/feature-flags/testing-util.ts @@ -8,11 +8,12 @@ import { FeatureWithoutCLI, initFeatures, } from "../feature-flags"; -import { getRunnerLogger } from "../logging"; +import type { Logger } from "../logging"; import { parseRepositoryNwo } from "../repository"; import { LoggedMessage, mockCodeQLVersion, + RecordingLogger, setupActionsVars, } from "../testing-utils"; import { ToolsFeature } from "../tools-features"; @@ -51,7 +52,7 @@ export function assertAllFeaturesUndefinedInApi( export function setUpFeatureFlagTests( tmpDir: string, - logger = getRunnerLogger(true), + logger: Logger = new RecordingLogger(), gitHubVersion = { type: GitHubVariant.DOTCOM } as util.GitHubVersion, ): FeatureEnablement { setupActionsVars(tmpDir, tmpDir); diff --git a/src/fingerprints.test.ts b/src/fingerprints.test.ts index 6cb9b68617..6b480a777f 100644 --- a/src/fingerprints.test.ts +++ b/src/fingerprints.test.ts @@ -5,9 +5,8 @@ import * as ava from "ava"; import test from "ava"; import * as fingerprints from "./fingerprints"; -import { getRunnerLogger } from "./logging"; import * as sarif from "./sarif"; -import { setupTests } from "./testing-utils"; +import { RecordingLogger, setupTests } from "./testing-utils"; import * as util from "./util"; setupTests(test); @@ -131,7 +130,7 @@ function testResolveUriToFile(uri: any, index: any, artifactsURIs: any[]) { location, artifacts, process.cwd(), - getRunnerLogger(true), + new RecordingLogger(), ); } @@ -218,7 +217,7 @@ test("addFingerprints", async (t) => { await fingerprints.addFingerprints( input, sourceRoot, - getRunnerLogger(true), + new RecordingLogger(), ), expected, ); @@ -246,7 +245,7 @@ test("missingRegions", async (t) => { await fingerprints.addFingerprints( input, sourceRoot, - getRunnerLogger(true), + new RecordingLogger(), ), expected, ); diff --git a/src/git-utils.test.ts b/src/git-utils.test.ts index b77d40a7ec..0240a09501 100644 --- a/src/git-utils.test.ts +++ b/src/git-utils.test.ts @@ -7,32 +7,42 @@ import test from "ava"; import * as sinon from "sinon"; import * as actionsUtil from "./actions-util"; +import { ActionsEnvVars, EnvVar } from "./environment"; import * as gitUtils from "./git-utils"; -import { setupActionsVars, setupTests } from "./testing-utils"; +import { getTestEnv, setupActionsVars, setupTests } from "./testing-utils"; import { withTmpDir } from "./util"; setupTests(test); -test.serial("getRef() throws on the empty string", async (t) => { - process.env["GITHUB_REF"] = ""; - await t.throwsAsync(gitUtils.getRef); +test("getRef() throws on the empty string", async (t) => { + const env = getTestEnv({ [ActionsEnvVars.GITHUB_REF]: "" }); + await t.throwsAsync(() => gitUtils.getRef(env, "")); }); test.serial( "getRef() returns merge PR ref if GITHUB_SHA still checked out", async (t) => { await withTmpDir(async (tmpDir: string) => { - setupActionsVars(tmpDir, tmpDir); const expectedRef = "refs/pull/1/merge"; const currentSha = "a".repeat(40); - process.env["GITHUB_REF"] = expectedRef; - process.env["GITHUB_SHA"] = currentSha; + + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); + env.setAll({ + [ActionsEnvVars.GITHUB_REF]: expectedRef, + [ActionsEnvVars.GITHUB_SHA]: currentSha, + }); const callback = sinon.stub(gitUtils, "getCommitOid"); - callback.withArgs("HEAD").resolves(currentSha); + callback + .withArgs(sinon.match.any, sinon.match.string, "HEAD") + .resolves(currentSha); - const actualRef = await gitUtils.getRef(); + const actualRef = await gitUtils.getRef(env, tmpDir); t.deepEqual(actualRef, expectedRef); + + t.is(callback.callCount, 1); + t.true(callback.calledOnceWith(env, tmpDir, "HEAD")); }); }, ); @@ -41,18 +51,33 @@ test.serial( "getRef() returns merge PR ref if GITHUB_REF still checked out but sha has changed (actions checkout@v1)", async (t) => { await withTmpDir(async (tmpDir: string) => { - setupActionsVars(tmpDir, tmpDir); const expectedRef = "refs/pull/1/merge"; - process.env["GITHUB_REF"] = expectedRef; - process.env["GITHUB_SHA"] = "b".repeat(40); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); + env.setAll({ + [ActionsEnvVars.GITHUB_REF]: expectedRef, + [ActionsEnvVars.GITHUB_SHA]: "b".repeat(40), + }); const sha = "a".repeat(40); const callback = sinon.stub(gitUtils, "getCommitOid"); - callback.withArgs("refs/remotes/pull/1/merge").resolves(sha); - callback.withArgs("HEAD").resolves(sha); - - const actualRef = await gitUtils.getRef(); + callback + .withArgs( + sinon.match.any, + sinon.match.string, + "refs/remotes/pull/1/merge", + ) + .resolves(sha); + callback + .withArgs(sinon.match.any, sinon.match.string, "HEAD") + .resolves(sha); + + const actualRef = await gitUtils.getRef(env, tmpDir); t.deepEqual(actualRef, expectedRef); + + t.is(callback.callCount, 2); + t.true(callback.calledWith(env, tmpDir, "HEAD")); + t.true(callback.calledWith(env, tmpDir, "refs/remotes/pull/1/merge")); }); }, ); @@ -61,16 +86,28 @@ test.serial( "getRef() returns head PR ref if GITHUB_REF no longer checked out", async (t) => { await withTmpDir(async (tmpDir: string) => { - setupActionsVars(tmpDir, tmpDir); - process.env["GITHUB_REF"] = "refs/pull/1/merge"; - process.env["GITHUB_SHA"] = "a".repeat(40); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); + env.setAll({ + [ActionsEnvVars.GITHUB_REF]: "refs/pull/1/merge", + [ActionsEnvVars.GITHUB_SHA]: "a".repeat(40), + }); const callback = sinon.stub(gitUtils, "getCommitOid"); - callback.withArgs(tmpDir, "refs/pull/1/merge").resolves("a".repeat(40)); - callback.withArgs(tmpDir, "HEAD").resolves("b".repeat(40)); - - const actualRef = await gitUtils.getRef(); + callback + .withArgs(sinon.match.any, tmpDir, "refs/remotes/pull/1/merge") + .resolves("a".repeat(40)); + callback + .withArgs(sinon.match.any, tmpDir, "HEAD") + .resolves("b".repeat(40)); + callback.throws(new Error("Unexpected getCommitOid call in test.")); + + const actualRef = await gitUtils.getRef(env, tmpDir); t.deepEqual(actualRef, "refs/pull/1/head"); + + t.is(callback.callCount, 2); + t.true(callback.calledWith(env, tmpDir, "refs/remotes/pull/1/merge")); + t.true(callback.calledWith(env, tmpDir, "HEAD")); }); }, ); @@ -79,7 +116,6 @@ test.serial( "getRef() returns ref provided as an input and ignores current HEAD", async (t) => { await withTmpDir(async (tmpDir: string) => { - setupActionsVars(tmpDir, tmpDir); const getAdditionalInputStub = sinon.stub( actionsUtil, "getOptionalInput", @@ -88,15 +124,26 @@ test.serial( getAdditionalInputStub.withArgs("sha").resolves("b".repeat(40)); // These values are be ignored - process.env["GITHUB_REF"] = "refs/pull/1/merge"; - process.env["GITHUB_SHA"] = "a".repeat(40); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); + env.setAll({ + [ActionsEnvVars.GITHUB_REF]: "refs/pull/1/merge", + [ActionsEnvVars.GITHUB_SHA]: "a".repeat(40), + }); const callback = sinon.stub(gitUtils, "getCommitOid"); - callback.withArgs("refs/pull/1/merge").resolves("b".repeat(40)); - callback.withArgs("HEAD").resolves("b".repeat(40)); - - const actualRef = await gitUtils.getRef(); + callback + .withArgs(sinon.match.any, tmpDir, "refs/pull/1/merge") + .resolves("b".repeat(40)); + callback + .withArgs(sinon.match.any, sinon.match.string, "HEAD") + .resolves("b".repeat(40)); + + const actualRef = await gitUtils.getRef(env, tmpDir); t.deepEqual(actualRef, "refs/pull/2/merge"); + + // getCommitOid shouldn't be called, because the ref should be taken from the input + t.is(callback.callCount, 0); }); }, ); @@ -105,14 +152,17 @@ test.serial( "getRef() returns CODE_SCANNING_REF as a fallback for GITHUB_REF", async (t) => { await withTmpDir(async (tmpDir: string) => { - setupActionsVars(tmpDir, tmpDir); const expectedRef = "refs/pull/1/HEAD"; const currentSha = "a".repeat(40); - process.env["CODE_SCANNING_REF"] = expectedRef; - process.env["GITHUB_REF"] = ""; - process.env["GITHUB_SHA"] = currentSha; + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); + env.setAll({ + [EnvVar.CODE_SCANNING_REF]: expectedRef, + [ActionsEnvVars.GITHUB_REF]: "", + [ActionsEnvVars.GITHUB_SHA]: currentSha, + }); - const actualRef = await gitUtils.getRef(); + const actualRef = await gitUtils.getRef(env, tmpDir); t.deepEqual(actualRef, expectedRef); }); }, @@ -122,14 +172,17 @@ test.serial( "getRef() returns GITHUB_REF over CODE_SCANNING_REF if both are provided", async (t) => { await withTmpDir(async (tmpDir: string) => { - setupActionsVars(tmpDir, tmpDir); const expectedRef = "refs/pull/1/merge"; const currentSha = "a".repeat(40); - process.env["CODE_SCANNING_REF"] = "refs/pull/1/HEAD"; - process.env["GITHUB_REF"] = expectedRef; - process.env["GITHUB_SHA"] = currentSha; + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); + env.setAll({ + [EnvVar.CODE_SCANNING_REF]: "refs/pull/1/HEAD", + [ActionsEnvVars.GITHUB_REF]: expectedRef, + [ActionsEnvVars.GITHUB_SHA]: currentSha, + }); - const actualRef = await gitUtils.getRef(); + const actualRef = await gitUtils.getRef(env, tmpDir); t.deepEqual(actualRef, expectedRef); }); }, @@ -139,7 +192,9 @@ test.serial( "getRef() throws an error if only `ref` is provided as an input", async (t) => { await withTmpDir(async (tmpDir: string) => { - setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); + const getAdditionalInputStub = sinon.stub( actionsUtil, "getOptionalInput", @@ -148,7 +203,7 @@ test.serial( await t.throwsAsync( async () => { - await gitUtils.getRef(); + await gitUtils.getRef(env, tmpDir); }, { instanceOf: Error, @@ -164,8 +219,12 @@ test.serial( "getRef() throws an error if only `sha` is provided as an input", async (t) => { await withTmpDir(async (tmpDir: string) => { - setupActionsVars(tmpDir, tmpDir); - process.env["GITHUB_WORKSPACE"] = "/tmp"; + const env = getTestEnv(); + setupActionsVars(tmpDir, tmpDir, {}, env); + env.setAll({ + [ActionsEnvVars.GITHUB_WORKSPACE]: "/tmp", + }); + const getAdditionalInputStub = sinon.stub( actionsUtil, "getOptionalInput", @@ -174,7 +233,7 @@ test.serial( await t.throwsAsync( async () => { - await gitUtils.getRef(); + await gitUtils.getRef(env, tmpDir); }, { instanceOf: Error, @@ -187,13 +246,16 @@ test.serial( ); test.serial("isAnalyzingDefaultBranch()", async (t) => { - process.env["GITHUB_EVENT_NAME"] = "push"; - process.env["CODE_SCANNING_IS_ANALYZING_DEFAULT_BRANCH"] = "true"; - t.deepEqual(await gitUtils.isAnalyzingDefaultBranch(), true); - process.env["CODE_SCANNING_IS_ANALYZING_DEFAULT_BRANCH"] = "false"; + const env = getTestEnv({ + [ActionsEnvVars.GITHUB_EVENT_NAME]: "push", + CODE_SCANNING_IS_ANALYZING_DEFAULT_BRANCH: "true", + }); + t.deepEqual(await gitUtils.isAnalyzingDefaultBranch(env, ""), true); + + env.set("CODE_SCANNING_IS_ANALYZING_DEFAULT_BRANCH", "false"); await withTmpDir(async (tmpDir) => { - setupActionsVars(tmpDir, tmpDir); + setupActionsVars(tmpDir, tmpDir, {}, env); const envFile = path.join(tmpDir, "event.json"); fs.writeFileSync( envFile, @@ -203,17 +265,17 @@ test.serial("isAnalyzingDefaultBranch()", async (t) => { }, }), ); - process.env["GITHUB_EVENT_PATH"] = envFile; + env.set(ActionsEnvVars.GITHUB_EVENT_PATH, envFile); - process.env["GITHUB_REF"] = "main"; - process.env["GITHUB_SHA"] = "1234"; - t.deepEqual(await gitUtils.isAnalyzingDefaultBranch(), true); + env.set(ActionsEnvVars.GITHUB_REF, "main"); + env.set(ActionsEnvVars.GITHUB_SHA, "1234"); + t.deepEqual(await gitUtils.isAnalyzingDefaultBranch(env, tmpDir), true); - process.env["GITHUB_REF"] = "refs/heads/main"; - t.deepEqual(await gitUtils.isAnalyzingDefaultBranch(), true); + env.set(ActionsEnvVars.GITHUB_REF, "refs/heads/main"); + t.deepEqual(await gitUtils.isAnalyzingDefaultBranch(env, tmpDir), true); - process.env["GITHUB_REF"] = "feature"; - t.deepEqual(await gitUtils.isAnalyzingDefaultBranch(), false); + env.set(ActionsEnvVars.GITHUB_REF, "feature"); + t.deepEqual(await gitUtils.isAnalyzingDefaultBranch(env, tmpDir), false); fs.writeFileSync( envFile, @@ -221,9 +283,9 @@ test.serial("isAnalyzingDefaultBranch()", async (t) => { schedule: "0 0 * * *", }), ); - process.env["GITHUB_EVENT_NAME"] = "schedule"; - process.env["GITHUB_REF"] = "refs/heads/main"; - t.deepEqual(await gitUtils.isAnalyzingDefaultBranch(), true); + env.set(ActionsEnvVars.GITHUB_EVENT_NAME, "schedule"); + env.set(ActionsEnvVars.GITHUB_REF, "refs/heads/main"); + t.deepEqual(await gitUtils.isAnalyzingDefaultBranch(env, tmpDir), true); const getAdditionalInputStub = sinon.stub(actionsUtil, "getOptionalInput"); getAdditionalInputStub @@ -232,9 +294,9 @@ test.serial("isAnalyzingDefaultBranch()", async (t) => { getAdditionalInputStub .withArgs("sha") .resolves("0000000000000000000000000000000000000000"); - process.env["GITHUB_EVENT_NAME"] = "schedule"; - process.env["GITHUB_REF"] = "refs/heads/main"; - t.deepEqual(await gitUtils.isAnalyzingDefaultBranch(), false); + env.set(ActionsEnvVars.GITHUB_EVENT_NAME, "schedule"); + env.set(ActionsEnvVars.GITHUB_REF, "refs/heads/main"); + t.deepEqual(await gitUtils.isAnalyzingDefaultBranch(env, tmpDir), false); }); }); diff --git a/src/git-utils.ts b/src/git-utils.ts index 0f5bf52a47..9045a7c3d7 100644 --- a/src/git-utils.ts +++ b/src/git-utils.ts @@ -13,6 +13,7 @@ import { getWorkflowEvent, getWorkflowEventName, } from "./actions-util"; +import { ActionsEnvVars, EnvVar, type ReadOnlyEnv } from "./environment"; import { ConfigurationError, getRequiredEnvParam } from "./util"; /** @@ -101,6 +102,7 @@ export const runGitCommand = async function ( * Gets the SHA of the commit that is currently checked out. */ export const getCommitOid = async function ( + env: ReadOnlyEnv, checkoutPath: string, ref = "HEAD", ): Promise { @@ -119,7 +121,9 @@ export const getCommitOid = async function ( ); return stdout.trim(); } catch { - return getOptionalInput("sha") || getRequiredEnvParam("GITHUB_SHA"); + return ( + getOptionalInput("sha") || env.getRequired(ActionsEnvVars.GITHUB_SHA) + ); } }; @@ -241,7 +245,7 @@ export const getGitRoot = async function ( ["rev-parse", "--show-toplevel"], `Cannot find Git repository root from the source root ${sourceRoot}.`, ); - return stdout.trim(); + return path.resolve(stdout.trim()); } catch { // Errors are already logged by runGitCommand() return undefined; @@ -314,18 +318,18 @@ export const getFileOidsUnderPath = async function ( return fileOidMap; }; -function getRefFromEnv(): string { +function getRefFromEnv(env: ReadOnlyEnv): string { // To workaround a limitation of Actions dynamic workflows not setting // the GITHUB_REF in some cases, we accept also the ref within the // CODE_SCANNING_REF variable. When possible, however, we prefer to use // the GITHUB_REF as that is a protected variable and cannot be overwritten. let refEnv: string; try { - refEnv = getRequiredEnvParam("GITHUB_REF"); + refEnv = env.getRequired(ActionsEnvVars.GITHUB_REF); } catch (e) { // If the GITHUB_REF is not set, we try to rescue by getting the // CODE_SCANNING_REF. - const maybeRef = process.env["CODE_SCANNING_REF"]; + const maybeRef = env.getOptional(EnvVar.CODE_SCANNING_REF); if (maybeRef === undefined || maybeRef.length === 0) { throw e; } @@ -337,15 +341,16 @@ function getRefFromEnv(): string { /** * Get the ref currently being analyzed. */ -export async function getRef(): Promise { +export async function getRef( + env: ReadOnlyEnv, + checkoutPath: string | undefined, +): Promise { // Will be in the form "refs/heads/master" on a push event // or in the form "refs/pull/N/merge" on a pull_request event const refInput = getOptionalInput("ref"); const shaInput = getOptionalInput("sha"); - const checkoutPath = - getOptionalInput("checkout_path") || - getOptionalInput("source-root") || - getRequiredEnvParam("GITHUB_WORKSPACE"); + checkoutPath = + checkoutPath ?? env.getRequired(ActionsEnvVars.GITHUB_WORKSPACE); const hasRefInput = !!refInput; const hasShaInput = !!shaInput; @@ -356,8 +361,8 @@ export async function getRef(): Promise { ); } - const ref = refInput || getRefFromEnv(); - const sha = shaInput || getRequiredEnvParam("GITHUB_SHA"); + const ref = refInput || getRefFromEnv(env); + const sha = shaInput || env.getRequired(ActionsEnvVars.GITHUB_SHA); // If the ref is a user-provided input, we have to skip logic // and assume that it is really where they want to upload the results. @@ -374,7 +379,7 @@ export async function getRef(): Promise { return ref; } - const head = await getCommitOid(checkoutPath, "HEAD"); + const head = await getCommitOid(env, checkoutPath, "HEAD"); // in actions/checkout@v2+ we can check if git rev-parse HEAD == GITHUB_SHA // in actions/checkout@v1 this may not be true as it checks out the repository @@ -384,6 +389,7 @@ export async function getRef(): Promise { const hasChangedRef = sha !== head && (await getCommitOid( + env, checkoutPath, ref.replace(/^refs\/pull\//, "refs/remotes/pull/"), )) !== head; @@ -410,20 +416,23 @@ function removeRefsHeadsPrefix(ref: string): string { * environment variable can be set in cases where repository information might not be available, for * example dynamic workflows. */ -export async function isAnalyzingDefaultBranch(): Promise { - if (process.env.CODE_SCANNING_IS_ANALYZING_DEFAULT_BRANCH === "true") { +export async function isAnalyzingDefaultBranch( + env: ReadOnlyEnv, + checkoutPath: string | undefined, +): Promise { + if (env.getOptional("CODE_SCANNING_IS_ANALYZING_DEFAULT_BRANCH") === "true") { return true; } // Get the current ref and trim and refs/heads/ prefix - let currentRef = await getRef(); + let currentRef = await getRef(env, checkoutPath); currentRef = removeRefsHeadsPrefix(currentRef); - const event = getWorkflowEvent(); + const event = getWorkflowEvent(env); let defaultBranch = event?.repository?.default_branch; - if (getWorkflowEventName() === "schedule") { - defaultBranch = removeRefsHeadsPrefix(getRefFromEnv()); + if (getWorkflowEventName(env) === "schedule") { + defaultBranch = removeRefsHeadsPrefix(getRefFromEnv(env)); } return currentRef === defaultBranch; diff --git a/src/github.test.ts b/src/github.test.ts new file mode 100644 index 0000000000..79dbb23311 --- /dev/null +++ b/src/github.test.ts @@ -0,0 +1,111 @@ +import test from "ava"; + +import { ActionsEnvVars } from "./environment"; +import * as github from "./github"; +import { getTestEnv, setupTests } from "./testing-utils"; + +setupTests(test); + +test("parseGitHubUrl", (t) => { + t.deepEqual(github.parseGitHubUrl("github.com"), "https://github.com"); + t.deepEqual( + github.parseGitHubUrl("https://github.com"), + "https://github.com", + ); + t.deepEqual( + github.parseGitHubUrl("https://api.github.com"), + "https://github.com", + ); + t.deepEqual( + github.parseGitHubUrl("https://github.com/foo/bar"), + "https://github.com", + ); + + t.deepEqual( + github.parseGitHubUrl("github.example.com"), + "https://github.example.com/", + ); + t.deepEqual( + github.parseGitHubUrl("https://github.example.com"), + "https://github.example.com/", + ); + t.deepEqual( + github.parseGitHubUrl("https://api.github.example.com"), + "https://github.example.com/", + ); + t.deepEqual( + github.parseGitHubUrl("https://github.example.com/api/v3"), + "https://github.example.com/", + ); + t.deepEqual( + github.parseGitHubUrl("https://github.example.com:1234"), + "https://github.example.com:1234/", + ); + t.deepEqual( + github.parseGitHubUrl("https://api.github.example.com:1234"), + "https://github.example.com:1234/", + ); + t.deepEqual( + github.parseGitHubUrl("https://github.example.com:1234/api/v3"), + "https://github.example.com:1234/", + ); + t.deepEqual( + github.parseGitHubUrl("https://github.example.com/base/path"), + "https://github.example.com/base/path/", + ); + t.deepEqual( + github.parseGitHubUrl("https://github.example.com/base/path/api/v3"), + "https://github.example.com/base/path/", + ); + + t.throws(() => github.parseGitHubUrl(""), { + message: '"" is not a valid URL', + }); + t.throws(() => github.parseGitHubUrl("ssh://github.com"), { + message: '"ssh://github.com" is not a http or https URL', + }); + t.throws(() => github.parseGitHubUrl("http:///::::433"), { + message: '"http:///::::433" is not a valid URL', + }); +}); + +test("getCurrentInstance throws if required env vars aren't set", (t) => { + t.throws(() => github.getCurrentInstance(getTestEnv())); + t.throws(() => { + const env = getTestEnv({ + [ActionsEnvVars.GITHUB_SERVER_URL]: "https://localhost", + }); + github.getCurrentInstance(env); + }); + t.throws(() => { + const env = getTestEnv({ + [ActionsEnvVars.GITHUB_API_URL]: "https://api.localhost", + }); + github.getCurrentInstance(env); + }); +}); + +test("getCurrentInstance constructs instance from environment", (t) => { + const url = "https://localhost"; + const apiUrl = "https://api.localhost"; + + const env = getTestEnv({ + [ActionsEnvVars.GITHUB_SERVER_URL]: url, + [ActionsEnvVars.GITHUB_API_URL]: apiUrl, + }); + const instance = github.getCurrentInstance(env); + + t.is(instance.url, url); + t.is(instance.apiURL, apiUrl); +}); + +test("getCurrentInstance constructs dotcom instance with dotcom env vars", (t) => { + const env = getTestEnv({ + [ActionsEnvVars.GITHUB_SERVER_URL]: github.GITHUB_DOTCOM_URL, + [ActionsEnvVars.GITHUB_API_URL]: github.GITHUB_DOTCOM_API_URL, + }); + const instance = github.getCurrentInstance(env); + const dotcomInstance = github.getDotcomInstance(); + + t.deepEqual(dotcomInstance, instance); +}); diff --git a/src/github.ts b/src/github.ts new file mode 100644 index 0000000000..e39cddfb05 --- /dev/null +++ b/src/github.ts @@ -0,0 +1,124 @@ +import { ActionsEnvVars, type ReadOnlyEnv } from "./environment"; +import { ConfigurationError } from "./errors"; + +export enum GitHubVariant { + /** [GitHub.com](https://github.com) */ + DOTCOM = "GitHub.com", + /** [GitHub Enterprise Server](https://docs.github.com/en/enterprise-server@latest/admin/overview/about-github-enterprise-server) */ + GHES = "GitHub Enterprise Server", + /** [GitHub Enterprise Cloud with data residency](https://docs.github.com/en/enterprise-cloud@latest/admin/data-residency/about-github-enterprise-cloud-with-data-residency) */ + GHEC_DR = "GitHub Enterprise Cloud with data residency", +} + +export type GitHubVersion = + | { type: GitHubVariant.DOTCOM } + | { type: GitHubVariant.GHEC_DR } + | { type: GitHubVariant.GHES; version: string }; + +/** A string representing a GitHub instance address. */ +export type InstanceURL = string; + +/** + * The URL for github.com. + */ +export const GITHUB_DOTCOM_URL: InstanceURL = "https://github.com"; + +/** A string representing a GitHub API instance address. */ +export type InstanceApiURL = string; + +/** + * The URL for api.github.com. + */ +export const GITHUB_DOTCOM_API_URL: InstanceApiURL = "https://api.github.com"; + +/** + * Represents information about a GitHub instance, how to authenticate to it, + * and how to authenticate to other repos on it. + */ +export type GitHubApiCombinedDetails = GitHubApiDetails & + GitHubApiExternalRepoDetails; + +/** Represents information about a GitHub instance. */ +export type GitHubInstance = { + /** The base URL of the GitHub instance, such as `https://github.com`. */ + url: string; + /** + * The API base URL of the GitHub instance, such as `https://api.github.com`. + * Typically this is the `api.` subdomain of the `url` domain. + */ + apiURL: string | undefined; +}; + +/** Represents a {@link GitHubInstance} with a token for accessing the API. */ +export type GitHubApiDetails = GitHubInstance & { + /** The token to use for accessing the API of the GitHub instance. */ + auth?: string; +}; + +/** + * Represents information for accessing a repository on the same GitHub instance as the Action + * is currently running on. + */ +export type GitHubApiExternalRepoDetails = { + /** An optional token for accessing repo(s) on the same GitHub instance. */ + externalRepoAuth?: string; +}; + +/** + * Parses user input of a github.com or GHES URL to a canonical form. + * Removes any API prefix or suffix if one is present. + */ +export function parseGitHubUrl(inputUrl: string): string { + const originalUrl = inputUrl; + if (inputUrl.indexOf("://") === -1) { + inputUrl = `https://${inputUrl}`; + } + if (!inputUrl.startsWith("http://") && !inputUrl.startsWith("https://")) { + throw new ConfigurationError(`"${originalUrl}" is not a http or https URL`); + } + + let url: URL; + try { + url = new URL(inputUrl); + } catch { + throw new ConfigurationError(`"${originalUrl}" is not a valid URL`); + } + + // If we detect this is trying to be to github.com + // then return with a fixed canonical URL. + if (url.hostname === "github.com" || url.hostname === "api.github.com") { + return GITHUB_DOTCOM_URL; + } + + // Remove the API prefix if it's present + if (url.pathname.indexOf("/api/v3") !== -1) { + url.pathname = url.pathname.substring(0, url.pathname.indexOf("/api/v3")); + } + // Also consider subdomain isolation on GHES + if (url.hostname.startsWith("api.")) { + url.hostname = url.hostname.substring(4); + } + + // Normalise path to having a trailing slash for consistency + if (!url.pathname.endsWith("/")) { + url.pathname = `${url.pathname}/`; + } + + return url.toString(); +} + +/** Retrieves a {@link GitHubInstance} describing the instance we are running on. */ +export function getCurrentInstance(env: ReadOnlyEnv): GitHubInstance { + return { + url: env.getRequired(ActionsEnvVars.GITHUB_SERVER_URL), + apiURL: env.getRequired(ActionsEnvVars.GITHUB_API_URL), + }; +} + +/** Retrieves a {@link GitHubInstance} describing the GitHub.com instance. */ +export function getDotcomInstance(): GitHubInstance { + return { + url: GITHUB_DOTCOM_URL, + apiURL: GITHUB_DOTCOM_API_URL, + }; +} diff --git a/src/init-action-post-helper.test.ts b/src/init-action-post-helper.test.ts index f24cc5e4e4..c0c8983913 100644 --- a/src/init-action-post-helper.test.ts +++ b/src/init-action-post-helper.test.ts @@ -1,3 +1,6 @@ +import * as fs from "fs"; +import * as path from "path"; + import * as core from "@actions/core"; import test, { ExecutionContext } from "ava"; import * as sinon from "sinon"; @@ -8,17 +11,20 @@ import * as apiClient from "./api-client"; import * as codeql from "./codeql"; import * as configUtils from "./config-utils"; import * as debugArtifacts from "./debug-artifacts"; +import { getTempDiagnosticsRoot } from "./diagnostics"; import { EnvVar } from "./environment"; import { Feature } from "./feature-flags"; import * as initActionPostHelper from "./init-action-post-helper"; -import { getRunnerLogger } from "./logging"; import { OverlayDatabaseMode } from "./overlay/overlay-database-mode"; import * as overlayStatus from "./overlay/status"; import { parseRepositoryNwo } from "./repository"; +import { JobStatus } from "./status-report"; import { createFeatures, createTestConfig, DEFAULT_ACTIONS_VARS, + getCodeQLForTesting, + getTestEnv, makeMacro, makeVersionInfo, RecordingLogger, @@ -33,6 +39,47 @@ const NUM_BYTES_PER_GIB = 1024 * 1024 * 1024; setupTests(test); +test.serial("generateFailedSarif picks up unwritten diagnostics", async (t) => + util.withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + + const tempDiagDir = getTempDiagnosticsRoot(tmpDir); + fs.mkdirSync(tempDiagDir, { recursive: true }); + + const codeqlObject = await getCodeQLForTesting(); + const diagnosticsExport = sinon + .stub(codeqlObject, "diagnosticsExport") + .resolves(); + + sinon.stub(codeql, "getCodeQL").resolves(codeqlObject); + + const sarifFile = path.join(tmpDir, "failed.sarif"); + const result = await initActionPostHelper.generateFailedSarif( + logger, + createFeatures([Feature.ExportDiagnosticsEnabled]), + createTestConfig({ + tempDir: tmpDir, + // Explicitly undefined to ensure we get the "no database" path. + dbLocation: undefined, + }), + "category", + "", + sarifFile, + ); + + t.truthy(result); + t.is(diagnosticsExport.callCount, 1); + t.true( + diagnosticsExport.calledOnceWith( + sarifFile, + "category", + sinon.match.any, + tempDiagDir, + ), + ); + }), +); + test.serial("init-post action with debug mode off", async (t) => { return await util.withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); @@ -58,7 +105,9 @@ test.serial("init-post action with debug mode off", async (t) => { createTestConfig({ debugMode: false }), parseRepositoryNwo("github/codeql-action"), createFeatures([]), - getRunnerLogger(true), + "success", + getTestEnv(), + new RecordingLogger(), ); t.assert(uploadAllAvailableDebugArtifactsSpy.notCalled); @@ -80,7 +129,9 @@ test.serial("init-post action with debug mode on", async (t) => { createTestConfig({ debugMode: true }), parseRepositoryNwo("github/codeql-action"), createFeatures([]), - getRunnerLogger(true), + "success", + getTestEnv(), + new RecordingLogger(), ); t.assert(uploadAllAvailableDebugArtifactsSpy.called); @@ -375,7 +426,9 @@ test.serial( }), parseRepositoryNwo("github/codeql-action"), createFeatures([Feature.OverlayAnalysisStatusSave]), - getRunnerLogger(true), + "success", + getTestEnv(), + new RecordingLogger(), ); t.true( @@ -443,7 +496,9 @@ test.serial( }), parseRepositoryNwo("github/codeql-action"), createFeatures([]), - getRunnerLogger(true), + "success", + getTestEnv(), + new RecordingLogger(), ); t.true( @@ -457,8 +512,13 @@ test.serial( test.serial("does not save overlay status when build successful", async (t) => { return await util.withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); - // Mark analyze as having completed successfully. + // Mark analyze as having completed successfully. `tryUploadSarifIfRunFailed` reads this from + // the process environment, while `recordOverlayStatus` reads it from the environment it is + // given. process.env[EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY] = "true"; + const env = getTestEnv({ + [EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY]: "true", + }); sinon.stub(util, "checkDiskUsage").resolves({ numAvailableBytes: 100 * NUM_BYTES_PER_GIB, @@ -480,7 +540,9 @@ test.serial("does not save overlay status when build successful", async (t) => { }), parseRepositoryNwo("github/codeql-action"), createFeatures([Feature.OverlayAnalysisStatusSave]), - getRunnerLogger(true), + "success", + env, + new RecordingLogger(), ); t.true( @@ -517,7 +579,9 @@ test.serial( }), parseRepositoryNwo("github/codeql-action"), createFeatures([]), - getRunnerLogger(true), + "success", + getTestEnv(), + new RecordingLogger(), ); t.true( @@ -528,6 +592,137 @@ test.serial( }, ); +/** + * Runs `uploadFailureInfo` for an overlay-base job that did not complete successfully, with the + * given job status from the Actions runtime environment. + */ +async function runOverlayPostStep({ + jobStatus, + codeQlReportedError = false, +}: { + jobStatus: string | undefined; + codeQlReportedError?: boolean; +}) { + return await util.withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + delete process.env[EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY]; + const env = getTestEnv( + codeQlReportedError + ? { [EnvVar.JOB_STATUS]: JobStatus.FailureStatus } + : {}, + ); + + sinon.stub(util, "checkDiskUsage").resolves({ + numAvailableBytes: 100 * NUM_BYTES_PER_GIB, + numTotalBytes: 200 * NUM_BYTES_PER_GIB, + }); + + const saveOverlayStatusStub = sinon + .stub(overlayStatus, "saveOverlayStatus") + .resolves(true); + + await initActionPostHelper.uploadFailureInfo( + sinon.spy(), + sinon.spy(), + codeql.createStubCodeQL({}), + createTestConfig({ + debugMode: false, + languages: ["javascript"], + overlayDatabaseMode: OverlayDatabaseMode.OverlayBase, + }), + parseRepositoryNwo("github/codeql-action"), + createFeatures([Feature.OverlayAnalysisStatusSave]), + jobStatus, + env, + new RecordingLogger(), + ); + + return { saveOverlayStatusStub }; + }); +} + +test.serial( + "does not save overlay status when the job was cancelled", + async (t) => { + const { saveOverlayStatusStub } = await runOverlayPostStep({ + jobStatus: "cancelled", + }); + + t.true( + saveOverlayStatusStub.notCalled, + "a cancellation tells us nothing about whether the analysis would have succeeded", + ); + }, +); + +test.serial( + "does not save overlay status when the job status is not recognised", + async (t) => { + const { saveOverlayStatusStub } = await runOverlayPostStep({ + jobStatus: "some-new-status", + }); + + t.true( + saveOverlayStatusStub.notCalled, + "a status we do not recognise tells us nothing about whether the analysis would have succeeded", + ); + }, +); + +test.serial( + "does not save overlay status when the job status is unavailable", + async (t) => { + const { saveOverlayStatusStub } = await runOverlayPostStep({ + jobStatus: undefined, + }); + + t.true( + saveOverlayStatusStub.notCalled, + "without a job status we cannot tell whether the analysis would have succeeded", + ); + }, +); + +test.serial( + "saves overlay status when the job failed rather than being cancelled", + async (t) => { + const { saveOverlayStatusStub } = await runOverlayPostStep({ + jobStatus: "failure", + }); + + t.true( + saveOverlayStatusStub.calledOnce, + "a failed job indicates that the analysis itself failed", + ); + }, +); + +test.serial("saves overlay status when the job succeeded", async (t) => { + const { saveOverlayStatusStub } = await runOverlayPostStep({ + jobStatus: "success", + }); + + t.true( + saveOverlayStatusStub.calledOnce, + "the analysis did not complete successfully even though the job as a whole succeeded", + ); +}); + +test.serial( + "saves overlay status when a CodeQL Action reported an error before the run was cancelled", + async (t) => { + const { saveOverlayStatusStub } = await runOverlayPostStep({ + jobStatus: "cancelled", + codeQlReportedError: true, + }); + + t.true( + saveOverlayStatusStub.calledOnce, + "the analysis genuinely failed, even though the run was later cancelled", + ); + }, +); + function createTestWorkflow( steps: workflow.WorkflowJobStep[], ): workflow.Workflow { @@ -587,7 +782,7 @@ async function testFailedSarifUpload( .withArgs("matrix") .returns(JSON.stringify(matrix)); - const codeqlObject = await codeql.getCodeQLForTesting(); + const codeqlObject = await getCodeQLForTesting(); sinon.stub(codeql, "getCodeQL").resolves(codeqlObject); sinon.stub(codeqlObject, "getVersion").resolves(makeVersionInfo("2.17.6")); const databaseExportDiagnosticsStub = sinon.stub( @@ -614,7 +809,7 @@ async function testFailedSarifUpload( config, parseRepositoryNwo("github/codeql-action"), createFeatures(features), - getRunnerLogger(true), + new RecordingLogger(), ); if (expectUpload) { t.deepEqual(result, { @@ -643,6 +838,7 @@ async function testFailedSarifUpload( } t.true( uploadFiles.calledOnceWith( + config, sinon.match.string, sinon.match.string, category, @@ -682,7 +878,7 @@ async function mockRiskAssessmentEnv(matrix: string) { .stub(apiClient, "getGitHubVersion") .resolves({ type: util.GitHubVariant.GHES, version: "3.0.0" }); - const codeqlObject = await codeql.getCodeQLForTesting(); + const codeqlObject = await getCodeQLForTesting(); const databaseExportDiagnostics = sinon .stub(codeqlObject, "databaseExportDiagnostics") .resolves(); diff --git a/src/init-action-post-helper.ts b/src/init-action-post-helper.ts index 7b7b056a1c..060592cac2 100644 --- a/src/init-action-post-helper.ts +++ b/src/init-action-post-helper.ts @@ -7,6 +7,11 @@ import * as actionsUtil from "./actions-util"; import { CodeScanning, RiskAssessment } from "./analyses"; import { getApiClient, getGitHubVersion } from "./api-client"; import { CodeQL, getCodeQL } from "./codeql"; +import { + hasConfigKey, + type AbortedInitConfig, + type ActionConfig, +} from "./config/action-config"; import { Config, isCodeScanningEnabled, @@ -16,9 +21,11 @@ import { getArtifactSuffix, getArtifactUploaderClient, sanitizeArtifactName, + type UploadDebugArtifactsConfig, } from "./debug-artifacts"; import * as dependencyCaching from "./dependency-caching"; -import { EnvVar } from "./environment"; +import { getTempDiagnosticsRoot } from "./diagnostics"; +import { EnvVar, ReadOnlyEnv } from "./environment"; import { Feature, FeatureEnablement } from "./feature-flags"; import { Logger } from "./logging"; import { OverlayDatabaseMode } from "./overlay/overlay-database-mode"; @@ -38,13 +45,14 @@ import { getRequiredEnvParam, parseMatrixInput, Result, + shouldSkipGenerateFailedSarif, shouldSkipSarifUpload, Success, wrapError, } from "./util"; import { getCategoryInputOrThrow, - getCheckoutPathInputOrThrow, + getRepositoryRootOrThrow, getUploadInputOrThrow, getWorkflow, } from "./workflow"; @@ -86,6 +94,11 @@ interface FailedSarifInfo { checkoutPath: string; } +/** The minimal Action configuration required to prepare and upload a failed SARIF. */ +export type FailedSarifConfig = ActionConfig< + "codeQLCmd" | "tempDir" | "analysisKinds" | "languages" +>; + /** * Tries to prepare a SARIF file that contains information about a failed analysis. * @@ -94,7 +107,7 @@ interface FailedSarifInfo { async function prepareFailedSarif( logger: Logger, features: FeatureEnablement, - config: Config, + config: FailedSarifConfig, ): Promise> { if (!config.codeQLCmd) { return new Failure({ @@ -104,7 +117,7 @@ async function prepareFailedSarif( const jobName = getRequiredEnvParam("GITHUB_JOB"); const matrix = parseMatrixInput(actionsUtil.getRequiredInput("matrix")); - if (shouldSkipSarifUpload()) { + if (shouldSkipGenerateFailedSarif()) { return new Failure({ upload_failed_run_skipped_because: "SARIF upload is disabled", }); @@ -144,7 +157,15 @@ async function prepareFailedSarif( }); } const category = getCategoryInputOrThrow(workflow, jobName, matrix); - const checkoutPath = getCheckoutPathInputOrThrow(workflow, jobName, matrix); + + // Try to determine the path at which the repository that we failed to analyse is checked out at. + // We need this to relativise the paths in the SARIF. + const checkoutPath = getRepositoryRootOrThrow( + workflow, + jobName, + matrix, + config, + ); const result = await generateFailedSarif( logger, @@ -157,10 +178,19 @@ async function prepareFailedSarif( } } -async function generateFailedSarif( +/** + * Generates a SARIF file for a failed run, i.e. an analysis where no SARIF was produced as a result of the analysis. + * + * Not intended to be called directly, other than by `prepareFailedSarif`. + * + * @param category The analysis category to include in the SARIF. + * @param checkoutPath The path where the repository was checked out at. + * @param sarifFile The SARIF file to produce. + */ +export async function generateFailedSarif( logger: Logger, features: FeatureEnablement, - config: Config, + config: ActionConfig<"codeQLCmd" | "tempDir">, category: string | undefined, checkoutPath: string, sarifFile?: string, @@ -174,11 +204,26 @@ async function generateFailedSarif( } // If there is no database or the feature flag is off, we run 'export diagnostics' - if ( - databasePath === undefined || - !(await features.getValue(Feature.ExportDiagnosticsEnabled, codeql)) - ) { - await codeql.diagnosticsExport(sarifFile, category, config); + const exportDiagnosticsEnabled = await features.getValue( + Feature.ExportDiagnosticsEnabled, + codeql, + ); + if (databasePath === undefined || !exportDiagnosticsEnabled) { + // If we don't have a database path, then we may have diagnostics that were written to a + // temporary location. Get the path that they would have been written to and check whether + // it exists. If so, pass it on to the CLI. The CLI will not complain if we give it a + // path that doesn't exist, so we are just being extra defensive here. + // We also don't pass the path to the CLI if `exportDiagnosticsEnabled` is not enabled, to preserve + // its intended behaviour of controlling whether diagnostics are included in the SARIF or not. + let diagnosticDir: string | undefined = getTempDiagnosticsRoot( + config.tempDir, + ); + + if (!exportDiagnosticsEnabled || !fs.existsSync(diagnosticDir)) { + diagnosticDir = undefined; + } + + await codeql.diagnosticsExport(sarifFile, category, config, diagnosticDir); } else { // We call 'database export-diagnostics' to find any per-database diagnostics. await codeql.databaseExportDiagnostics(databasePath, sarifFile, category); @@ -192,7 +237,7 @@ async function generateFailedSarif( * category for the workflow. */ async function maybeUploadFailedSarif( - config: Config, + config: FailedSarifConfig, repositoryNwo: RepositoryNwo, features: FeatureEnablement, logger: Logger, @@ -207,6 +252,7 @@ async function maybeUploadFailedSarif( logger.info(`Uploading failed SARIF file ${failedSarif.sarifFile}`); const uploadResult = await uploadLib.uploadFiles( + config, failedSarif.sarifFile, failedSarif.checkoutPath, failedSarif.category, @@ -220,6 +266,14 @@ async function maybeUploadFailedSarif( logger, { isUnsuccessfulExecution: true }, ); + + // If SARIF upload is disabled for testing, `uploadFiles` will not have uploaded the failed + // SARIF file and instead will have written it to disk. Upload it as a workflow artifact so that + // we can inspect it in validation jobs. + if (uploadResult.sarifID && shouldSkipSarifUpload()) { + await uploadSarifArtifact(logger, "test-mode-sarif", failedSarif); + } + return uploadResult ? { ...uploadResult.statusReport, sarifID: uploadResult.sarifID } : {}; @@ -227,7 +281,7 @@ async function maybeUploadFailedSarif( /** Uploads a failed SARIF file as workflow artifact, if it can be generated. */ async function maybeUploadFailedSarifArtifact( - config: Config, + config: FailedSarifConfig, features: FeatureEnablement, logger: Logger, ): Promise { @@ -238,23 +292,34 @@ async function maybeUploadFailedSarifArtifact( } const failedSarif = failedSarifResult.value; + return uploadSarifArtifact(logger, "sarif-artifact", failedSarif); +} - logger.info( - `Uploading failed SARIF file ${failedSarif.sarifFile} as artifact`, - ); - - const gitHubVersion = await getGitHubVersion(); - const client = await getArtifactUploaderClient(logger, gitHubVersion.type); +/** Uploads a failed SARIF file as workflow artifact. */ +async function uploadSarifArtifact( + logger: Logger, + prefix: string, + failedSarif: FailedSarifInfo, +): Promise { + logger.startGroup(`Uploading failed SARIF file as artifact`); + logger.info(`Uploading '${failedSarif.sarifFile}' as artifact`); - const suffix = getArtifactSuffix(actionsUtil.getOptionalInput("matrix")); - const name = sanitizeArtifactName(`sarif-artifact-${suffix}`); - await client.uploadArtifact( - name, - [path.normalize(failedSarif.sarifFile)], - path.normalize(".."), - ); + try { + const gitHubVersion = await getGitHubVersion(); + const client = await getArtifactUploaderClient(logger, gitHubVersion.type); + + const suffix = getArtifactSuffix(actionsUtil.getOptionalInput("matrix")); + const name = sanitizeArtifactName(`${prefix}-${suffix}`); + await client.uploadArtifact( + name, + [path.normalize(failedSarif.sarifFile)], + path.normalize(path.dirname(failedSarif.sarifFile)), + ); - return { sarifID: name }; + return { sarifID: name }; + } finally { + logger.endGroup(); + } } /** @@ -267,7 +332,7 @@ async function maybeUploadFailedSarifArtifact( * @returns The results of uploading the SARIF file for the failure. */ export async function tryUploadSarifIfRunFailed( - config: Config, + config: FailedSarifConfig, repositoryNwo: RepositoryNwo, features: FeatureEnablement, logger: Logger, @@ -316,24 +381,27 @@ export async function tryUploadSarifIfRunFailed( * @param config The CodeQL Action configuration. * @param repositoryNwo The name and owner of the repository. * @param features Information about enabled features. + * @param jobStatus The status of the job, as reported by the Actions runtime environment. + * @param env The environment to read variables from. * @param logger The logger to use. * @returns The results of uploading the SARIF file for the failure. */ export async function uploadFailureInfo( uploadAllAvailableDebugArtifacts: ( codeql: CodeQL, - config: Config, + config: UploadDebugArtifactsConfig, logger: Logger, - codeQlVersion: string, ) => Promise, - printDebugLogs: (config: Config) => Promise, + printDebugLogs: (logger: Logger, config: Partial) => Promise, codeql: CodeQL, - config: Config, + config: Config | AbortedInitConfig, repositoryNwo: RepositoryNwo, features: FeatureEnablement, + jobStatus: string | undefined, + env: ReadOnlyEnv, logger: Logger, ): Promise { - await recordOverlayStatus(codeql, config, features, logger); + await recordOverlayStatus(codeql, config, features, jobStatus, env, logger); const uploadFailedSarifResult = await tryUploadSarifIfRunFailed( config, @@ -373,21 +441,15 @@ export async function uploadFailureInfo( } // Upload appropriate Actions artifacts for debugging - if (config.debugMode) { + if (config.debugMode && hasConfigKey(config, "dbLocation")) { logger.info( "Debug mode is on. Uploading available database bundles and logs as Actions debugging artifacts...", ); - const version = await codeql.getVersion(); - await uploadAllAvailableDebugArtifacts( - codeql, - config, - logger, - version.version, - ); - await printDebugLogs(config); + await uploadAllAvailableDebugArtifacts(codeql, config, logger); + await printDebugLogs(logger, config); } - if (actionsUtil.isSelfHostedRunner()) { + if (actionsUtil.isSelfHostedRunner() && config.dbLocation) { try { fs.rmSync(config.dbLocation, { recursive: true, @@ -402,6 +464,10 @@ export async function uploadFailureInfo( `Failed to clean up database cluster directory ${config.dbLocation}. Details: ${e}`, ); } + } else if (config.dbLocation === undefined) { + logger.debug( + "Skipping cleanup of database cluster directory since the configuration does not include a database path.", + ); } else { logger.debug( "Skipping cleanup of database cluster directory since we are running on a GitHub-hosted " + @@ -412,6 +478,37 @@ export async function uploadFailureInfo( return uploadFailedSarifResult; } +/** + * Whether one of the CodeQL Actions reported an error for this job, which means the analysis + * genuinely failed. + * + * Note that the converse does not hold: an Action that is terminated abruptly, or that fails before + * it can gather telemetry, does not get to report anything. + */ +function didCodeQlReportError(env: ReadOnlyEnv): boolean { + const jobStatus = env.getOptional(EnvVar.JOB_STATUS); + return ( + jobStatus === JobStatus.FailureStatus || + jobStatus === JobStatus.ConfigErrorStatus + ); +} + +/** + * Whether the job status tells us anything about whether the analysis itself would have succeeded. + * + * We check for the statuses we know to be meaningful rather than excluding the ones that are not, + * so that a status we do not recognise is treated as inconclusive. + */ +function isConclusiveJobStatus(jobStatus: string | undefined): boolean { + switch (jobStatus?.trim().toLowerCase()) { + case "failure": + case "success": + return true; + default: + return false; + } +} + /** * If overlay base database creation was attempted but the analysis did not complete * successfully, save the failure status to the Actions cache so that subsequent runs @@ -419,16 +516,35 @@ export async function uploadFailureInfo( */ async function recordOverlayStatus( codeql: CodeQL, - config: Config, + config: Partial, features: FeatureEnablement, + jobStatus: string | undefined, + env: ReadOnlyEnv, logger: Logger, ) { if ( config.overlayDatabaseMode !== OverlayDatabaseMode.OverlayBase || - process.env[EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY] === "true" || + env.getOptional(EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY) === "true" || !(await features.getValue(Feature.OverlayAnalysisStatusSave)) ) { return; + } else if (config.languages === undefined) { + logger.debug( + "Not recording overlay status, because the configuration contains no 'languages'.", + ); + return; + } + + // Only record a failure when the job outcome tells us something about the analysis. A cancelled + // job, or a status we do not recognise, says nothing about whether the analysis would have + // succeeded, so recording a failure would disable overlay analysis needlessly. We still record + // one if a CodeQL Action reported an error before the job ended. + if (!isConclusiveJobStatus(jobStatus) && !didCodeQlReportError(env)) { + logger.info( + "Not recording an improved incremental analysis failure for this job because the job " + + `status (${jobStatus ?? "unset"}) does not tell us whether the analysis itself failed.`, + ); + return; } const checkRunIdInput = actionsUtil.getOptionalInput("check-run-id"); diff --git a/src/init-action-post.ts b/src/init-action-post.ts index 2261b56ea6..5ae78637f5 100644 --- a/src/init-action-post.ts +++ b/src/init-action-post.ts @@ -6,30 +6,35 @@ import * as core from "@actions/core"; +import { runInActions, type Action, type ActionState } from "./action-common"; import { restoreInputs, + getOptionalInput, getTemporaryDirectory, printDebugLogs, } from "./actions-util"; -import { getGitHubVersion } from "./api-client"; +import { getGitHubVersion, wrapApiConfigurationError } from "./api-client"; import { CachingKind } from "./caching-utils"; import { getCodeQL } from "./codeql"; -import { type Config, getConfig } from "./config-utils"; +import { + hasConfigKey, + type AbortedInitConfig, + type Config, +} from "./config/action-config"; +import { getAbortedInitConfig, getConfig } from "./config-utils"; import * as debugArtifacts from "./debug-artifacts"; import { DependencyCachingUsageReport, getDependencyCacheUsage, } from "./dependency-caching"; -import { EnvVar } from "./environment"; +import { EnvVar, type ReadOnlyEnv } from "./environment"; import { initFeatures } from "./feature-flags"; import * as gitUtils from "./git-utils"; import * as initActionPostHelper from "./init-action-post-helper"; -import { getActionsLogger } from "./logging"; import { getRepositoryNwo } from "./repository"; import { StatusReportBase, sendStatusReport, - sendUnhandledErrorStatusReport, createStatusReportBase, getActionsStatus, ActionName, @@ -39,26 +44,45 @@ import { import { checkDiskUsage, checkGitHubVersionInRange, wrapError } from "./util"; interface InitPostStatusReport - extends StatusReportBase, + extends + StatusReportBase, initActionPostHelper.UploadFailedSarifResult, initActionPostHelper.JobStatusReport, initActionPostHelper.DependencyCachingUsageReport {} -async function run(startedAt: Date) { +async function run(action: ActionState<["Base", "Logger", "Env"]>) { // To capture errors appropriately, keep as much code within the try-catch as // possible, and only use safe functions outside. + const logger = action.logger; - const logger = getActionsLogger(); - let config: Config | undefined; + let config: Config | AbortedInitConfig | undefined; let uploadFailedSarifResult: - | initActionPostHelper.UploadFailedSarifResult - | undefined; + initActionPostHelper.UploadFailedSarifResult | undefined; let dependencyCachingUsage: DependencyCachingUsageReport | undefined; + try { + // Read the job status before restoring inputs, since it is provided by the Actions runtime + // environment for this step and would otherwise be overwritten by the value that the `init` + // Action saw, which is always a success. + const jobStatus = getOptionalInput("job-status"); + // Restore inputs from `init` Action. - restoreInputs(); + restoreInputs(logger); + + const tmpDir = getTemporaryDirectory(); + config = await getConfig(tmpDir, logger); - const gitHubVersion = await getGitHubVersion(); + // If we weren't able to read the normal configuration file, the `init` step failed before it could write it. + // Try to load the "failed" configuration file instead which may have been written by the `init` step + // with a minimal configuration for this post-action. + if (config === undefined) { + logger.debug( + "Will try to load the configuration file from an aborted 'init' step, since there is no regular one.", + ); + config = getAbortedInitConfig(action, tmpDir); + } + + const gitHubVersion = config?.gitHubVersion ?? (await getGitHubVersion()); checkGitHubVersionInRange(gitHubVersion, logger); const repositoryNwo = getRepositoryNwo(); @@ -69,7 +93,6 @@ async function run(startedAt: Date) { logger, ); - config = await getConfig(getTemporaryDirectory(), logger); if (config === undefined) { logger.warning( "Debugging artifacts are unavailable since the 'init' Action failed before it could produce any.", @@ -84,6 +107,8 @@ async function run(startedAt: Date) { config, repositoryNwo, features, + jobStatus, + action.env, logger, ); @@ -92,20 +117,24 @@ async function run(startedAt: Date) { // do this under these circumstances to avoid slowing down analyses for PRs // and where caching may not be enabled. if ( - (await gitUtils.isAnalyzingDefaultBranch()) && + (await gitUtils.isAnalyzingDefaultBranch( + action.env, + config.repositoryRoot, + )) && + hasConfigKey(config, "dependencyCachingEnabled") && config.dependencyCachingEnabled !== CachingKind.None ) { dependencyCachingUsage = await getDependencyCacheUsage(logger); } } } catch (unwrappedError) { - const error = wrapError(unwrappedError); + const error = wrapApiConfigurationError(wrapError(unwrappedError)); core.setFailed(error.message); const statusReportBase = await createStatusReportBase( - ActionName.InitPost, + action.name, getActionsStatus(error), - startedAt, + action.startedAt, config, await checkDiskUsage(logger), logger, @@ -117,13 +146,13 @@ async function run(startedAt: Date) { } return; } - const jobStatus = getFinalJobStatus(config); + const jobStatus = getFinalJobStatus(action, config); logger.info(`CodeQL job status was ${getJobStatusDisplayName(jobStatus)}.`); const statusReportBase = await createStatusReportBase( - ActionName.InitPost, + action.name, "success", - startedAt, + action.startedAt, config, await checkDiskUsage(logger), logger, @@ -148,16 +177,21 @@ async function run(startedAt: Date) { * Otherwise, we determine the job status based on whether the analyze step * completed successfully and whether we have a valid CodeQL config. */ -function getFinalJobStatus(config: Config | undefined): JobStatus { - const existingJobStatus = getJobStatusFromEnvironment(); +function getFinalJobStatus( + action: ActionState<["Env"]>, + config: Partial | undefined, +): JobStatus { + const existingJobStatus = getJobStatusFromEnvironment(action.env); if (existingJobStatus !== undefined) { return existingJobStatus; } let jobStatus: JobStatus; - if (process.env[EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY] === "true") { - core.exportVariable(EnvVar.JOB_STATUS, JobStatus.SuccessStatus); + if ( + action.env.getOptional(EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY) === "true" + ) { + action.env.export(EnvVar.JOB_STATUS, JobStatus.SuccessStatus); jobStatus = JobStatus.SuccessStatus; } else if (config !== undefined) { // - We have computed a CodeQL config @@ -182,7 +216,7 @@ function getFinalJobStatus(config: Config | undefined): JobStatus { // This shouldn't be necessary, but in the odd case that we run more than one // `init` post step, ensure the job status is consistent between them. - core.exportVariable(EnvVar.JOB_STATUS, jobStatus); + action.env.export(EnvVar.JOB_STATUS, jobStatus); return jobStatus; } @@ -191,8 +225,8 @@ function getFinalJobStatus(config: Config | undefined): JobStatus { * * If the job status is invalid, return `UnknownStatus`. */ -function getJobStatusFromEnvironment(): JobStatus | undefined { - const jobStatusFromEnvironment = process.env[EnvVar.JOB_STATUS]; +function getJobStatusFromEnvironment(env: ReadOnlyEnv): JobStatus | undefined { + const jobStatusFromEnvironment = env.getOptional(EnvVar.JOB_STATUS); if (jobStatusFromEnvironment !== undefined) { // Validate the job status from the environment. If it is invalid, return unknown. @@ -207,18 +241,11 @@ function getJobStatusFromEnvironment(): JobStatus | undefined { return undefined; } +const initPost: Action = { + name: ActionName.InitPost, + run, +}; + export async function runWrapper() { - const startedAt = new Date(); - const logger = getActionsLogger(); - try { - await run(startedAt); - } catch (error) { - core.setFailed(`init post action failed: ${wrapError(error).message}`); - await sendUnhandledErrorStatusReport( - ActionName.InitPost, - startedAt, - error, - logger, - ); - } + return await runInActions(initPost); } diff --git a/src/init-action.ts b/src/init-action.ts index 6b5ed392ef..0998c2e711 100644 --- a/src/init-action.ts +++ b/src/init-action.ts @@ -5,7 +5,12 @@ import * as core from "@actions/core"; import * as io from "@actions/io"; import * as semver from "semver"; -import { Action, ActionState, runInActions } from "./action-common"; +import { + Action, + ActionState, + extendActionState, + runInActions, +} from "./action-common"; import { FileCmdNotFoundError, getActionVersion, @@ -23,6 +28,7 @@ import { shouldRestoreCache, } from "./caching-utils"; import { CodeQL } from "./codeql"; +import { parseUserConfig } from "./config/db-config"; import { getConfigFileInput } from "./config/file"; import { ComputedInput, getToolsInput } from "./config/inputs"; import * as configUtils from "./config-utils"; @@ -34,13 +40,17 @@ import { addDiagnostic, addNoLanguageDiagnostic, flushDiagnostics, - logUnwrittenDiagnostics, + logTemporaryDiagnostics, makeDiagnostic, makeTelemetryDiagnostic, } from "./diagnostics"; -import { EnvVar } from "./environment"; +import { ActionsEnvVars, EnvVar } from "./environment"; import { Feature, FeatureEnablement, initFeatures } from "./feature-flags"; -import { loadRepositoryProperties } from "./feature-flags/properties"; +import { + loadRepositoryProperties, + RepositoryPropertyName, +} from "./feature-flags/properties"; +import * as github from "./github"; import { checkInstallPython311, checkPacksForOverlayCompatibility, @@ -52,24 +62,26 @@ import { runDatabaseInitCluster, } from "./init"; import { JavaEnvVars, BuiltInLanguage } from "./languages"; +import { checkRunnerSupportsTracedAnalysis } from "./languages/traced"; import { Logger, withGroupAsync } from "./logging"; import { downloadOverlayBaseDatabaseFromCache, OverlayBaseDatabaseDownloadStats, } from "./overlay/caching"; import { OverlayDatabaseMode } from "./overlay/overlay-database-mode"; +import { getOtherLanguagePacksReason } from "./per-language-bundles"; import { getRepositoryNwo } from "./repository"; import { ToolsSource } from "./setup-codeql"; import { ActionName, InitStatusReport, - InitToolsDownloadFields, InitWithConfigStatusReport, createInitWithConfigStatusReport, createStatusReportBase, getActionsStatus, sendStatusReport, } from "./status-report"; +import { createInitToolsDownloadFields } from "./status-report/tools-download"; import { ToolsDownloadStatusReport } from "./tools-download"; import { ToolsFeature } from "./tools-features"; import { getCombinedTracerConfig } from "./tracer-config"; @@ -77,19 +89,15 @@ import { checkDiskUsage, checkForTimeout, checkGitHubVersionInRange, - codeQlVersionAtLeast, DEFAULT_DEBUG_ARTIFACT_NAME, DEFAULT_DEBUG_DATABASE_NAME, getCodeQLMemoryLimit, - getRequiredEnvParam, getThreadsFlagValue, - initializeEnvironment, ConfigurationError, wrapError, checkActionVersion, getErrorMessage, BuildMode, - getOptionalEnvVar, } from "./util"; import { checkWorkflow } from "./workflow"; @@ -168,15 +176,10 @@ async function sendCompletedStatusReport( initStatusReport.computed_inputs.tools = toolsInput; } - const initToolsDownloadFields: InitToolsDownloadFields = {}; - - if (toolsDownloadStatusReport?.downloadDurationMs !== undefined) { - initToolsDownloadFields.tools_download_duration_ms = - toolsDownloadStatusReport.downloadDurationMs; - } - if (toolsFeatureFlagsValid !== undefined) { - initToolsDownloadFields.tools_feature_flags_valid = toolsFeatureFlagsValid; - } + const initToolsDownloadFields = createInitToolsDownloadFields( + toolsDownloadStatusReport, + toolsFeatureFlagsValid, + ); if (config !== undefined) { // Append fields that are dependent on `config` @@ -222,7 +225,7 @@ async function run( let toolsVersion: string; try { - initializeEnvironment(getActionVersion()); + actionState.env.initialise(getActionVersion()); // Make inputs accessible in the `post` step. persistInputs(); @@ -230,8 +233,7 @@ async function run( apiDetails = { auth: getRequiredInput("token"), externalRepoAuth: getOptionalInput("external-repository-token"), - url: getRequiredEnvParam("GITHUB_SERVER_URL"), - apiURL: getRequiredEnvParam("GITHUB_API_URL"), + ...github.getCurrentInstance(actionState.env), }; const gitHubVersion = await getGitHubVersion(); @@ -254,13 +256,13 @@ async function run( ); const repositoryProperties = repositoryPropertiesResult.orElse({}); - core.exportVariable(EnvVar.INIT_ACTION_HAS_RUN, "true"); + actionState.env.export(EnvVar.INIT_ACTION_HAS_RUN, "true"); // path.resolve() respects the intended semantics of source-root. If // source-root is relative, it is relative to the GITHUB_WORKSPACE. If // source-root is absolute, it is used as given. sourceRoot = path.resolve( - getRequiredEnvParam("GITHUB_WORKSPACE"), + actionState.env.getRequired(ActionsEnvVars.GITHUB_WORKSPACE), getOptionalInput("source-root") || "", ); @@ -279,7 +281,9 @@ async function run( } // Compute the value of the `config-file` input. - const actionStateWithFeatures = { ...actionState, features }; + const actionStateWithFeatures = extendActionState(actionState, { + features, + }); configFile = await getConfigFileInput( actionStateWithFeatures, repositoryProperties, @@ -308,6 +312,24 @@ async function run( const rawLanguages = configUtils.getRawLanguagesNoAutodetect( getOptionalInput("languages"), ); + const rawConfigInput = getOptionalInput("config"); + const configInput = + rawConfigInput === undefined + ? undefined + : parseUserConfig( + logger, + "`config` input", + rawConfigInput, + await features.getValue(Feature.ValidateDbConfig), + ); + const queriesInput = getOptionalInput("queries"); + const otherLanguagePacksReason = getOtherLanguagePacksReason({ + configFile, + configInput, + queriesInput, + extraQueriesProperty: + repositoryProperties[RepositoryPropertyName.EXTRA_QUERIES], + }); const useOverlayAwareDefaultCliVersion = analysisKinds?.length === 1 && analysisKinds[0] === AnalysisKind.CodeScanning; @@ -318,6 +340,7 @@ async function run( gitHubVersion.type, codeQLDefaultVersionInfo, rawLanguages, + otherLanguagePacksReason, useOverlayAwareDefaultCliVersion, features, logger, @@ -331,7 +354,7 @@ async function run( // to the workflow log. No exceptions are thrown. await checkWorkflow(logger, codeql); - // Set CODEQL_ENABLE_EXPERIMENTAL_FEATURES for Rust if between 2.19.3 (included) and 2.22.1 (excluded) + // Set CODEQL_ENABLE_EXPERIMENTAL_FEATURES for Rust if the CLI is older than 2.22.1. // We need to set this environment variable before initializing the config, otherwise Rust // analysis will not be enabled (experimental language packs are only active with that environment // variable set to `true`). @@ -342,16 +365,10 @@ async function run( .getRawLanguagesNoAutodetect(getOptionalInput("languages")) .includes(BuiltInLanguage.rust) ) { - const experimental = "2.19.3"; const publicPreview = "2.22.1"; const actualVer = (await codeql.getVersion()).version; - if (semver.lt(actualVer, experimental)) { - throw new ConfigurationError( - `Rust analysis is supported by CodeQL CLI version ${experimental} or higher, but found version ${actualVer}`, - ); - } if (semver.lt(actualVer, publicPreview)) { - core.exportVariable(EnvVar.EXPERIMENTAL_FEATURES, "true"); + actionState.env.export(EnvVar.EXPERIMENTAL_FEATURES, "true"); logger.info("Experimental Rust analysis enabled"); } } @@ -368,13 +385,13 @@ async function run( config = await initConfig(actionStateWithFeatures, { analysisKinds, languagesInput: getOptionalInput("languages"), - queriesInput: getOptionalInput("queries"), + queriesInput, packsInput: getOptionalInput("packs"), buildModeInput: getOptionalInput("build-mode"), ramInput: getOptionalInput("ram"), configFile, dbLocation: getOptionalInput("db-location"), - configInput: getOptionalInput("config"), + configInput, dependencyCachingEnabled: getDependencyCachingEnabled(), // Debug mode is enabled if: // - The `init` Action is passed `debug: true`. @@ -388,7 +405,9 @@ async function run( repository: repositoryNwo, tempDir: getTemporaryDirectory(), codeql, - workspacePath: getRequiredEnvParam("GITHUB_WORKSPACE"), + workspacePath: actionState.env.getRequired( + ActionsEnvVars.GITHUB_WORKSPACE, + ), sourceRoot, githubVersion: gitHubVersion, apiDetails, @@ -398,14 +417,11 @@ async function run( logger, }); - if ( - config.languages.includes(BuiltInLanguage.swift) && - process.platform !== "darwin" - ) { - throw new ConfigurationError( - `Swift analysis is only supported on macOS runner images. Please migrate to a macOS runner.`, - ); - } + await checkRunnerSupportsTracedAnalysis( + actionStateWithFeatures, + config, + codeql, + ); if (repositoryPropertiesResult.isFailure()) { addNoLanguageDiagnostic( @@ -437,6 +453,18 @@ async function run( await checkInstallPython311(config.languages, codeql); } catch (unwrappedError) { + // If we have initialised the Action state, then try to save a subset of it for use by the `init-post` action + // so that it can try to create and upload additional diagnostic information. + if (config !== undefined) { + try { + configUtils.saveAbortedInitConfig(actionState, config); + } catch (configSaveError) { + logger.warning( + `Unable to save configuration for '${ActionName.InitPost}' step: ${getErrorMessage(configSaveError)}`, + ); + } + } + const error = wrapError(unwrappedError); core.setFailed(error.message); const statusReportBase = await createStatusReportBase( @@ -452,6 +480,7 @@ async function run( if (statusReportBase !== undefined) { await sendStatusReport(statusReportBase); } + logTemporaryDiagnostics(actionState); return; } @@ -497,9 +526,9 @@ async function run( } // Forward Go flags - const goFlags = process.env["GOFLAGS"]; + const goFlags = actionState.env.getOptional("GOFLAGS"); if (goFlags) { - core.exportVariable("GOFLAGS", goFlags); + actionState.env.export("GOFLAGS", goFlags); core.warning( "Passing the GOFLAGS env parameter to the init action is deprecated. Please move this to the analyze action.", ); @@ -545,7 +574,7 @@ async function run( // Store the original location of our wrapper script somewhere where we can // later retrieve it from and cross-check that it hasn't been changed. - core.exportVariable(EnvVar.GO_BINARY_LOCATION, goWrapperPath); + actionState.env.export(EnvVar.GO_BINARY_LOCATION, goWrapperPath); } catch (e) { logger.warning( `Analyzing Go on Linux, but failed to install wrapper script. Tracing custom builds may fail: ${e}`, @@ -554,7 +583,7 @@ async function run( } else { // Store the location of the original Go binary, so we can check that no setup tasks were performed after the // `init` Action ran. - core.exportVariable(EnvVar.GO_BINARY_LOCATION, goBinaryPath); + actionState.env.export(EnvVar.GO_BINARY_LOCATION, goBinaryPath); } } catch (e) { logger.warning( @@ -589,12 +618,12 @@ async function run( // threads it would ask extractors to use. See help text for the "--ram" and "--threads" // options at https://codeql.github.com/docs/codeql-cli/manual/database-trace-command/ // for details. - core.exportVariable( + actionState.env.export( "CODEQL_RAM", process.env["CODEQL_RAM"] || getCodeQLMemoryLimit(getOptionalInput("ram"), logger).toString(), ); - core.exportVariable( + actionState.env.export( "CODEQL_THREADS", process.env["CODEQL_THREADS"] || getThreadsFlagValue(getOptionalInput("threads"), logger).toString(), @@ -602,21 +631,15 @@ async function run( // Disable Kotlin extractor if feature flag set if (await features.getValue(Feature.DisableKotlinAnalysisEnabled)) { - core.exportVariable("CODEQL_EXTRACTOR_JAVA_AGENT_DISABLE_KOTLIN", "true"); + actionState.env.export( + "CODEQL_EXTRACTOR_JAVA_AGENT_DISABLE_KOTLIN", + "true", + ); } // Emergency override to force the CodeQL CLI back to the JGit-based Git backend. if (await features.getValue(Feature.ForceJGit)) { - core.exportVariable("CODEQL_GIT_BACKEND", "jgit"); - } - - const kotlinLimitVar = - "CODEQL_EXTRACTOR_KOTLIN_OVERRIDE_MAXIMUM_VERSION_LIMIT"; - if ( - (await codeQlVersionAtLeast(codeql, "2.20.3")) && - !(await codeQlVersionAtLeast(codeql, "2.20.4")) - ) { - core.exportVariable(kotlinLimitVar, "2.1.20"); + actionState.env.export("CODEQL_GIT_BACKEND", "jgit"); } // Restore dependency cache(s), if they exist. @@ -660,12 +683,12 @@ async function run( `${EnvVar.JAVA_EXTRACTOR_MINIMIZE_DEPENDENCY_JARS} is already set to '${process.env[EnvVar.JAVA_EXTRACTOR_MINIMIZE_DEPENDENCY_JARS]}', so the Action will not override it.`, ); } else if ( - (await codeQlVersionAtLeast(codeql, CODEQL_VERSION_JAR_MINIMIZATION)) && + (await codeql.isVersionAtLeast(CODEQL_VERSION_JAR_MINIMIZATION)) && config.dependencyCachingEnabled && config.buildMode === BuildMode.None && config.languages.includes(BuiltInLanguage.java) ) { - core.exportVariable( + actionState.env.export( EnvVar.JAVA_EXTRACTOR_MINIMIZE_DEPENDENCY_JARS, "true", ); @@ -720,10 +743,10 @@ async function run( ); } - const tracerConfig = await getCombinedTracerConfig(codeql, config); + const tracerConfig = await getCombinedTracerConfig(logger, codeql, config); if (tracerConfig !== undefined) { for (const [key, value] of Object.entries(tracerConfig.env)) { - core.exportVariable(key, value); + actionState.env.export(key, value); } } @@ -731,23 +754,24 @@ async function run( if (await features.getValue(Feature.JavaNetworkDebugging)) { // Get the existing value of `JAVA_TOOL_OPTIONS`, if any. const existingJavaToolOptions = - getOptionalEnvVar(JavaEnvVars.JAVA_TOOL_OPTIONS) || ""; + actionState.env.getOptional(JavaEnvVars.JAVA_TOOL_OPTIONS) ?? ""; // Add the network debugging options. - core.exportVariable( + actionState.env.export( JavaEnvVars.JAVA_TOOL_OPTIONS, `${existingJavaToolOptions} -Djavax.net.debug=all`, ); } - // Write diagnostics to the database that we previously stored in memory because the database - // did not exist until now. - flushDiagnostics(config); + // Move diagnostics to the database that we previously kept in a temporary location + // because the database did not exist until now + flushDiagnostics(actionState, config); // We save the config here instead of at the end of `initConfig` because we // may have updated the config returned from `initConfig`, e.g. to revert to // `OverlayDatabaseMode.None` if we failed to download an overlay-base // database. + config.successfullyInitialised = true; await configUtils.saveConfig(config, logger); core.setOutput("codeql-path", config.codeQLCmd); @@ -771,7 +795,7 @@ async function run( ); return; } finally { - logUnwrittenDiagnostics(); + logTemporaryDiagnostics(actionState); } await sendCompletedStatusReport( startedAt, diff --git a/src/init.test.ts b/src/init.test.ts index 1f0d2c701c..9cb169fb27 100644 --- a/src/init.test.ts +++ b/src/init.test.ts @@ -1,14 +1,13 @@ import * as fs from "fs"; import path from "path"; -import * as core from "@actions/core"; import * as github from "@actions/github"; import test, { ExecutionContext } from "ava"; import * as sinon from "sinon"; import * as actionsUtil from "./actions-util"; import { createStubCodeQL } from "./codeql"; -import { ActionsEnvVars } from "./environment"; +import * as environment from "./environment"; import { Feature } from "./feature-flags"; import { checkPacksForOverlayCompatibility, @@ -85,7 +84,7 @@ for (const { runnerEnv, ErrorConstructor, message } of [ `cleanupDatabaseClusterDirectory throws a ${ErrorConstructor.name} when cleanup fails on ${runnerEnv} runner`, async (t) => { await withTmpDir(async (tmpDir: string) => { - process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = runnerEnv; + process.env[environment.ActionsEnvVars.RUNNER_ENVIRONMENT] = runnerEnv; const dbLocation = path.resolve(tmpDir, "dbs"); fs.mkdirSync(dbLocation, { recursive: true }); @@ -546,7 +545,7 @@ test.serial( test.serial( "file coverage deprecation warning for org-owned repo with default setup recommends repo property", (t) => { - const exportVariableStub = sinon.stub(core, "exportVariable"); + const exportEnvVarStub = sinon.stub(environment, "exportEnvVar"); sinon.stub(actionsUtil, "isDefaultSetup").returns(true); github.context.payload = { repository: { @@ -566,14 +565,14 @@ test.serial( 'with the name `github-codeql-file-coverage-on-prs` and the type "True/false", then set this property to ' + "`true` in the repository's settings.", ); - t.true(exportVariableStub.calledOnce); + t.true(exportEnvVarStub.calledOnce); }, ); test.serial( "file coverage deprecation warning for org-owned repo with advanced setup recommends env var and repo property", (t) => { - const exportVariableStub = sinon.stub(core, "exportVariable"); + const exportEnvVarStub = sinon.stub(environment, "exportEnvVar"); sinon.stub(actionsUtil, "isDefaultSetup").returns(false); github.context.payload = { repository: { @@ -594,14 +593,14 @@ test.serial( 'with the name `github-codeql-file-coverage-on-prs` and the type "True/false", then set this property to ' + "`true` in the repository's settings.", ); - t.true(exportVariableStub.calledOnce); + t.true(exportEnvVarStub.calledOnce); }, ); test.serial( "file coverage deprecation warning for user-owned repo with default setup recommends advanced setup", (t) => { - const exportVariableStub = sinon.stub(core, "exportVariable"); + const exportEnvVarStub = sinon.stub(environment, "exportEnvVar"); sinon.stub(actionsUtil, "isDefaultSetup").returns(true); github.context.payload = { repository: { @@ -620,14 +619,14 @@ test.serial( "To opt out of this change, switch to an advanced setup workflow and " + "set the `CODEQL_ACTION_FILE_COVERAGE_ON_PRS` environment variable to `true`.", ); - t.true(exportVariableStub.calledOnce); + t.true(exportEnvVarStub.calledOnce); }, ); test.serial( "file coverage deprecation warning for user-owned repo with advanced setup recommends env var", (t) => { - const exportVariableStub = sinon.stub(core, "exportVariable"); + const exportEnvVarStub = sinon.stub(environment, "exportEnvVar"); sinon.stub(actionsUtil, "isDefaultSetup").returns(false); github.context.payload = { repository: { @@ -645,14 +644,14 @@ test.serial( "to improve analysis performance. File coverage information will still be computed on non-PR analyses.\n\n" + "To opt out of this change, set the `CODEQL_ACTION_FILE_COVERAGE_ON_PRS` environment variable to `true`.", ); - t.true(exportVariableStub.calledOnce); + t.true(exportEnvVarStub.calledOnce); }, ); test.serial( "file coverage deprecation warning for unknown owner type with default setup recommends advanced setup", (t) => { - const exportVariableStub = sinon.stub(core, "exportVariable"); + const exportEnvVarStub = sinon.stub(environment, "exportEnvVar"); sinon.stub(actionsUtil, "isDefaultSetup").returns(true); github.context.payload = { repository: undefined }; const messages: LoggedMessage[] = []; @@ -666,14 +665,14 @@ test.serial( "To opt out of this change, switch to an advanced setup workflow and " + "set the `CODEQL_ACTION_FILE_COVERAGE_ON_PRS` environment variable to `true`.", ); - t.true(exportVariableStub.calledOnce); + t.true(exportEnvVarStub.calledOnce); }, ); test.serial( "file coverage deprecation warning for unknown owner type with advanced setup recommends env var", (t) => { - const exportVariableStub = sinon.stub(core, "exportVariable"); + const exportEnvVarStub = sinon.stub(environment, "exportEnvVar"); sinon.stub(actionsUtil, "isDefaultSetup").returns(false); github.context.payload = { repository: undefined }; const messages: LoggedMessage[] = []; @@ -686,7 +685,7 @@ test.serial( "to improve analysis performance. File coverage information will still be computed on non-PR analyses.\n\n" + "To opt out of this change, set the `CODEQL_ACTION_FILE_COVERAGE_ON_PRS` environment variable to `true`.", ); - t.true(exportVariableStub.calledOnce); + t.true(exportEnvVarStub.calledOnce); }, ); @@ -695,10 +694,10 @@ test.serial( (t) => { process.env["CODEQL_ACTION_DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION"] = "true"; - const exportVariableStub = sinon.stub(core, "exportVariable"); + const exportEnvVarStub = sinon.stub(environment, "exportEnvVar"); const messages: LoggedMessage[] = []; logFileCoverageOnPrsDeprecationWarning(getRecordingLogger(messages)); t.is(messages.length, 0); - t.true(exportVariableStub.notCalled); + t.true(exportEnvVarStub.notCalled); }, ); diff --git a/src/init.ts b/src/init.ts index c6a258e58c..11f1eea2e7 100644 --- a/src/init.ts +++ b/src/init.ts @@ -1,7 +1,6 @@ import * as fs from "fs"; import * as path from "path"; -import * as core from "@actions/core"; import * as toolrunner from "@actions/exec/lib/toolrunner"; import * as github from "@actions/github"; import * as io from "@actions/io"; @@ -17,7 +16,7 @@ import { import { GitHubApiDetails } from "./api-client"; import { CodeQL, setupCodeQL } from "./codeql"; import * as configUtils from "./config-utils"; -import { EnvVar } from "./environment"; +import { EnvVar, exportEnvVar } from "./environment"; import { CodeQLDefaultVersionInfo, Feature, @@ -40,6 +39,7 @@ export async function initCodeQL( variant: util.GitHubVariant, defaultCliVersion: CodeQLDefaultVersionInfo, rawLanguages: string[] | undefined, + otherLanguagePacksReason: string | undefined, useOverlayAwareDefaultCliVersion: boolean, features: FeatureEnablement, logger: Logger, @@ -58,6 +58,7 @@ export async function initCodeQL( variant, defaultCliVersion, rawLanguages, + otherLanguagePacksReason, useOverlayAwareDefaultCliVersion, features, logger, @@ -409,5 +410,5 @@ export function logFileCoverageOnPrsDeprecationWarning(logger: Logger): void { } logger.warning(message); - core.exportVariable(EnvVar.DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION, "true"); + exportEnvVar(EnvVar.DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION, "true"); } diff --git a/src/languages/swift.test.ts b/src/languages/swift.test.ts new file mode 100644 index 0000000000..c3d18c476f --- /dev/null +++ b/src/languages/swift.test.ts @@ -0,0 +1,89 @@ +import test from "ava"; +import sinon from "sinon"; + +import { ActionsEnvVars } from "../environment"; +import { + createTestConfig, + getCodeQLForTesting, + getTestEnv, + makeVersionInfo, + RecordingLogger, + setupTests, +} from "../testing-utils"; +import { ToolsFeature } from "../tools-features"; +import { withTmpDir } from "../util"; + +import { checkSwiftCompatibility } from "./swift"; + +import { BuiltInLanguage } from "."; + +setupTests(test); + +test("checkSwiftCompatibility doesn't throw for non-Swift languages", async (t) => { + for (const language of Object.values(BuiltInLanguage)) { + if (language === BuiltInLanguage.swift) { + continue; + } + + const codeql = await getCodeQLForTesting(); + await t.notThrowsAsync( + checkSwiftCompatibility( + createTestConfig({ languages: [language] }), + codeql, + // A value of `undefined` should make `checkSwiftCompatibility` throw for Swift by default + // since it means we are on a platform other than macOS + undefined, + ), + ); + } +}); + +test("checkSwiftCompatibility doesn't throw for Swift if CLI supports swiftSupportsAllPlatforms", async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + + const codeql = await getCodeQLForTesting("codeql-for-testing", logger, env); + const supportsFeature = sinon + .stub(codeql, "supportsFeature") + .withArgs(ToolsFeature.SwiftSupportsAllPlatforms) + .resolves(true); + + await t.notThrowsAsync( + checkSwiftCompatibility( + createTestConfig({ languages: [BuiltInLanguage.swift] }), + codeql, + // A value of `undefined` should make `checkSwiftCompatibility` throw for Swift by default + // since it means we are on a platform other than macOS + undefined, + ), + ); + + t.is(supportsFeature.callCount, 1); + t.deepEqual(supportsFeature.args[0], [ + ToolsFeature.SwiftSupportsAllPlatforms, + ]); + })); + +test("checkSwiftCompatibility doesn't throw for Swift on darwin", async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + + const codeql = await getCodeQLForTesting("codeql-for-testing", logger, env); + sinon.stub(codeql, "getVersion").resolves(makeVersionInfo("2.27.0")); + + await t.notThrowsAsync( + checkSwiftCompatibility( + createTestConfig({ + tempDir: tmpDir, + languages: [BuiltInLanguage.swift], + }), + codeql, + // A value other than `undefined` means we are on macOS. + "some-macos-version", + ), + ); + })); diff --git a/src/languages/swift.ts b/src/languages/swift.ts new file mode 100644 index 0000000000..e617684e05 --- /dev/null +++ b/src/languages/swift.ts @@ -0,0 +1,42 @@ +import type { SemVer } from "semver"; + +import { CodeQL } from "../codeql"; +import type { ActionConfig } from "../config/action-config"; +import { ToolsFeature } from "../tools-features"; +import { ConfigurationError } from "../util"; + +import { BuiltInLanguage } from "."; + +/** + * Determines whether we can run a Swift analysis on the current runner. + * + * @param config The Action configuration. + * @param codeql The {@link CodeQL} CLI instance. + * @param darwinVersion The version of the Darwin kernel on macOS, if any. + * + * @throws {ConfigurationError} If Swift analysis is not possible on the current runner. + */ +export async function checkSwiftCompatibility( + config: ActionConfig<"languages">, + codeql: CodeQL, + darwinVersion: SemVer | string | undefined, +) { + // The checks are not relevant if we are not trying to analyse Swift. + if (!config.languages.includes(BuiltInLanguage.swift)) { + return; + } + + // Skip the checks if the `swiftSupportsAllPlatforms` feature is supported by the CLI. + // This is a forward-looking measure that allows a future CLI update to disable these + // platform checks in the Action when they shouldn't be enforced anymore. + if (await codeql.supportsFeature(ToolsFeature.SwiftSupportsAllPlatforms)) { + return; + } + + // If `darwinVersion` is undefined, then we are not on macOS and Swift analysis is unsupported. + if (darwinVersion === undefined) { + throw new ConfigurationError( + `Swift analysis is only supported on macOS runner images. Please migrate to a macOS runner.`, + ); + } +} diff --git a/src/languages/traced.test.ts b/src/languages/traced.test.ts new file mode 100644 index 0000000000..631a647ae3 --- /dev/null +++ b/src/languages/traced.test.ts @@ -0,0 +1,717 @@ +import fs from "fs"; + +import type { ExecOptions } from "@actions/exec"; +import * as toolrunner from "@actions/exec/lib/toolrunner"; +import * as io from "@actions/io"; +import test from "ava"; +import * as sinon from "sinon"; + +import { type CodeQL } from "../codeql"; +import * as diagnostics from "../diagnostics"; +import { ActionsEnvVars, type Env } from "../environment"; +import { Feature } from "../feature-flags"; +import type { Logger } from "../logging"; +import { XCODE_SELECT_LINK_PATH } from "../platform"; +import { + checkExpectedLogMessages, + checkUnexpectedLogMessages, + createFeatures, + createTestConfig, + getCodeQLForTesting, + getTestEnv, + initAllState, + makeVersionInfo, + RecordingLogger, + setupTests, +} from "../testing-utils"; +import { BuildMode, ConfigurationError, withTmpDir } from "../util"; + +import { checkRunnerSupportsTracedAnalysis } from "./traced"; + +import { BuiltInLanguage } from "."; + +setupTests(test); + +const TEST_DEFAULT_TRACED_LANGUAGES = { + [BuiltInLanguage.swift]: true, + [BuiltInLanguage.go]: true, +}; + +async function getCodeQLWithTracedStub( + cmd: string, + logger: Logger, + env: Env, + tracedLanguages: Partial< + Record + > = TEST_DEFAULT_TRACED_LANGUAGES, +): Promise { + const codeql = await getCodeQLForTesting(cmd, logger, env); + sinon.stub(codeql, "isTracedLanguage").callsFake(async (language) => { + return tracedLanguages[language] === true; + }); + return codeql; +} + +const nonDarwinPlatforms: NodeJS.Platform[] = ["linux", "win32"]; +for (const nonDarwinPlatform of nonDarwinPlatforms) { + test(`checkRunnerSupportsTracedAnalysis throws for Swift on ${nonDarwinPlatform}`, async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + + const codeql = await getCodeQLWithTracedStub( + "codeql-for-testing", + logger, + env, + ); + sinon.stub(codeql, "getVersion").resolves(makeVersionInfo("2.27.0")); + + await t.throwsAsync( + checkRunnerSupportsTracedAnalysis( + initAllState({ platform: nonDarwinPlatform, env, logger }), + createTestConfig({ + tempDir: tmpDir, + languages: [BuiltInLanguage.swift], + }), + codeql, + ), + { + instanceOf: ConfigurationError, + message: /^Swift analysis is only supported on macOS runner images/, + }, + ); + })); +} + +test(`checkRunnerSupportsTracedAnalysis doesn't throw for BMN`, async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + const features = createFeatures([Feature.CheckUnsupportedTracedAnalysis]); + + const codeql = await getCodeQLWithTracedStub( + "codeql-for-testing", + logger, + env, + ); + sinon.stub(codeql, "getVersion").resolves(makeVersionInfo("2.27.0")); + + await t.notThrowsAsync( + checkRunnerSupportsTracedAnalysis( + initAllState({ + platform: "darwin", + osRelease: "27.0.0", + env, + logger, + features, + }), + createTestConfig({ tempDir: tmpDir, buildMode: BuildMode.None }), + codeql, + ), + ); + + checkExpectedLogMessages(t, logger.messages, [ + "Skipping traced analysis compatibility checks because the build mode is 'none'.", + ]); + })); + +// Some languages not in `TEST_DEFAULT_TRACED_LANGUAGES`. +const nonTracedLanguages: BuiltInLanguage[] = [ + BuiltInLanguage.javascript, + BuiltInLanguage.actions, +]; +for (const nonTracedLanguage of nonTracedLanguages) { + test(`checkRunnerSupportsTracedAnalysis doesn't throw for ${nonTracedLanguage} on unsupported macOS`, async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + const features = createFeatures([Feature.CheckUnsupportedTracedAnalysis]); + + const codeql = await getCodeQLWithTracedStub( + "codeql-for-testing", + logger, + env, + ); + sinon.stub(codeql, "getVersion").resolves(makeVersionInfo("2.27.0")); + + await t.notThrowsAsync( + checkRunnerSupportsTracedAnalysis( + initAllState({ + platform: "darwin", + osRelease: "27.0.0", + env, + logger, + features, + }), + createTestConfig({ tempDir: tmpDir, languages: [nonTracedLanguage] }), + codeql, + ), + ); + + checkExpectedLogMessages(t, logger.messages, [ + "Skipping traced analysis compatibility checks because no traced languages are being analyzed.", + ]); + })); +} + +test("checkRunnerSupportsTracedAnalysis doesn't perform checks if FF is not enabled", async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + const features = createFeatures([]); + + const codeql = await getCodeQLWithTracedStub( + "codeql-for-testing", + logger, + env, + ); + sinon.stub(codeql, "getVersion").resolves(makeVersionInfo("2.27.0")); + + await checkRunnerSupportsTracedAnalysis( + initAllState({ + logger, + platform: "darwin", + osRelease: "unexpected", + env, + features, + }), + createTestConfig({ tempDir: tmpDir, languages: [BuiltInLanguage.go] }), + codeql, + ); + + checkExpectedLogMessages(t, logger.messages, [ + "Skipping traced analysis compatibility checks because the feature is not enabled.", + ]); + })); + +test("checkRunnerSupportsTracedAnalysis warns if version string is not a semver", async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + const features = createFeatures([Feature.CheckUnsupportedTracedAnalysis]); + + const codeql = await getCodeQLWithTracedStub( + "codeql-for-testing", + logger, + env, + ); + sinon.stub(codeql, "getVersion").resolves(makeVersionInfo("2.27.0")); + + await checkRunnerSupportsTracedAnalysis( + initAllState({ + logger, + platform: "darwin", + osRelease: "unexpected", + env, + features, + }), + createTestConfig({ tempDir: tmpDir, languages: [BuiltInLanguage.go] }), + codeql, + ); + + checkExpectedLogMessages(t, logger.messages, [ + "Unable to parse Darwin kernel version, got: unexpected", + ]); + })); + +// `addDiagnostic` changes global state and we must stub it, so this test must be serial. +test.serial( + "checkRunnerSupportsTracedAnalysis logs and adds diagnostic if macOS version is unsupported", + async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const features = createFeatures([Feature.CheckUnsupportedTracedAnalysis]); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + + const codeql = await getCodeQLWithTracedStub( + "codeql-for-testing", + logger, + env, + ); + sinon.stub(codeql, "getVersion").resolves(makeVersionInfo("2.27.0")); + + const addDiagnostic = sinon.stub(diagnostics, "addDiagnostic"); + + const config = createTestConfig({ + tempDir: tmpDir, + languages: [BuiltInLanguage.swift], + }); + await checkRunnerSupportsTracedAnalysis( + initAllState({ + logger, + platform: "darwin", + osRelease: "27.0.0", + env, + features, + }), + config, + codeql, + ); + + checkExpectedLogMessages(t, logger.messages, [ + "Traced analysis is not supported on macOS 27", + ]); + + t.is(addDiagnostic.callCount, 1); + t.like(addDiagnostic.args[0], [ + config, + BuiltInLanguage.swift, + { + attributes: { + languages: [BuiltInLanguage.swift], + darwinVersion: "27.0.0", + }, + severity: "warning", + source: { + id: "codeql-action/unsupported-traced-analysis-macos", + name: "Traced analysis is not supported on this version of macOS", + }, + visibility: { + cliSummaryTable: true, + statusPage: true, + telemetry: true, + }, + } satisfies Partial, + ]); + }), +); + +// `addDiagnostic` changes global state and we must stub it, so this test must be serial. +test.serial( + "checkRunnerSupportsTracedAnalysis throws if macOS version is unsupported and FF is enabled", + async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + + const features = createFeatures([ + Feature.CheckUnsupportedTracedAnalysis, + Feature.AbortUnsupportedTracedAnalysis, + ]); + + const codeql = await getCodeQLWithTracedStub( + "codeql-for-testing", + logger, + env, + ); + sinon.stub(codeql, "getVersion").resolves(makeVersionInfo("2.27.0")); + + const addDiagnostic = sinon.stub(diagnostics, "addDiagnostic"); + + const config = createTestConfig({ + tempDir: tmpDir, + languages: [BuiltInLanguage.swift], + }); + await t.throwsAsync( + checkRunnerSupportsTracedAnalysis( + initAllState({ + logger, + platform: "darwin", + osRelease: "27.0.0", + env, + features, + }), + config, + codeql, + ), + ); + + t.is(addDiagnostic.callCount, 1); + t.like(addDiagnostic.args[0], [ + config, + BuiltInLanguage.swift, + { + attributes: { + languages: [BuiltInLanguage.swift], + darwinVersion: "27.0.0", + }, + severity: "error", + source: { + id: "codeql-action/unsupported-traced-analysis-macos", + name: "Traced analysis is not supported on this version of macOS", + }, + visibility: { + cliSummaryTable: true, + statusPage: true, + telemetry: true, + }, + } satisfies Partial, + ]); + }), +); + +// `addDiagnostic` changes global state and we must stub it, so this test must be serial. +test.serial( + "checkRunnerSupportsTracedAnalysis doesn't add a diagnostic if Xcode version is supported", + async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + const features = createFeatures([Feature.CheckUnsupportedTracedAnalysis]); + + const readlinkSync = sinon + .stub(fs, "readlinkSync") + .returns("/Applications/Xcode_26.0.app/Contents/Developer"); + + const codeql = await getCodeQLWithTracedStub( + "codeql-for-testing", + logger, + env, + ); + sinon.stub(codeql, "getVersion").resolves(makeVersionInfo("2.27.0")); + + const addDiagnostic = sinon.stub(diagnostics, "addDiagnostic"); + + const config = createTestConfig({ + tempDir: tmpDir, + languages: [BuiltInLanguage.swift], + }); + await checkRunnerSupportsTracedAnalysis( + initAllState({ + logger, + platform: "darwin", + osRelease: "26.0.0", + env, + features, + }), + config, + codeql, + ); + + t.is(readlinkSync.callCount, 1); + t.deepEqual(readlinkSync.args[0], [XCODE_SELECT_LINK_PATH]); + + checkUnexpectedLogMessages(t, logger.messages, [ + "Traced analysis is not supported on Xcode 27", + ]); + + t.is(addDiagnostic.callCount, 0); + }), +); + +test.serial( + "checkRunnerSupportsTracedAnalysis attempts fallbacks if needed", + async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + const features = createFeatures([Feature.CheckUnsupportedTracedAnalysis]); + + const readlinkSync = sinon + .stub(fs, "readlinkSync") + .throws(new Error("Not found")); + const which = sinon.stub(io, "which").resolves("/path/to/xcrun"); + const exec = sinon.stub<[], Promise>().callsFake(async () => { + throw new Error("Error to force next fallback"); + }); + const runner = sinon.createStubInstance(toolrunner.ToolRunner, { exec }); + const toolrunnerStub = sinon + .stub(toolrunner, "ToolRunner") + .callsFake(() => { + return runner; + }); + + const codeql = await getCodeQLWithTracedStub( + "codeql-for-testing", + logger, + env, + ); + sinon.stub(codeql, "getVersion").resolves(makeVersionInfo("2.27.0")); + + const addDiagnostic = sinon.stub(diagnostics, "addDiagnostic"); + + const config = createTestConfig({ + tempDir: tmpDir, + languages: [BuiltInLanguage.swift], + }); + await checkRunnerSupportsTracedAnalysis( + initAllState({ + logger, + platform: "darwin", + osRelease: "26.0.0", + env, + features, + }), + config, + codeql, + ); + + t.is(readlinkSync.callCount, 1); + t.deepEqual(readlinkSync.args[0], [XCODE_SELECT_LINK_PATH]); + t.is(which.callCount, 2); + t.deepEqual(which.args[0], ["xcrun", true]); + t.deepEqual(which.args[1], ["xcrun", true]); + + t.is(toolrunnerStub.callCount, 2); + t.is(exec.callCount, 2); + + t.is(toolrunnerStub.args[0][0], "/path/to/xcrun"); + t.deepEqual(toolrunnerStub.args[0][1], ["xcodebuild", "-version"]); + + t.is(toolrunnerStub.args[1][0], "/path/to/xcrun"); + t.deepEqual(toolrunnerStub.args[1][1], [ + "--sdk", + "macosx", + "--show-sdk-version", + ]); + + checkExpectedLogMessages(t, logger.messages, [ + "Unable to determine Xcode version: Not found", + "Unable to determine Xcode version from xcodebuild: Error to force next fallback", + "Unable to determine Xcode SDK version: Error to force next fallback", + ]); + checkUnexpectedLogMessages(t, logger.messages, [ + "Traced analysis is not supported on Xcode 27", + ]); + + t.is(addDiagnostic.callCount, 0); + }), +); + +// `addDiagnostic` changes global state and we must stub it, so this test must be serial. +test.serial( + "checkRunnerSupportsTracedAnalysis logs and adds diagnostic if Xcode version is unsupported", + async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + const features = createFeatures([Feature.CheckUnsupportedTracedAnalysis]); + + const readlinkSync = sinon + .stub(fs, "readlinkSync") + .returns("/Applications/Xcode_27.0.app/Contents/Developer"); + + const codeql = await getCodeQLWithTracedStub( + "codeql-for-testing", + logger, + env, + ); + sinon.stub(codeql, "getVersion").resolves(makeVersionInfo("2.27.0")); + + const addDiagnostic = sinon.stub(diagnostics, "addDiagnostic"); + + const config = createTestConfig({ + tempDir: tmpDir, + languages: [BuiltInLanguage.swift], + }); + await checkRunnerSupportsTracedAnalysis( + initAllState({ + logger, + platform: "darwin", + osRelease: "26.0.0", + env, + features, + }), + config, + codeql, + ); + + t.is(readlinkSync.callCount, 1); + t.deepEqual(readlinkSync.args[0], [XCODE_SELECT_LINK_PATH]); + + checkExpectedLogMessages(t, logger.messages, [ + "Traced analysis is not supported on Xcode 27", + ]); + + t.is(addDiagnostic.callCount, 1); + t.like(addDiagnostic.args[0], [ + config, + BuiltInLanguage.swift, + { + attributes: { + languages: [BuiltInLanguage.swift], + xcodeVersion: "27.0.0", + }, + severity: "warning", + source: { + id: "codeql-action/unsupported-traced-analysis-xcode", + name: "Traced analysis is not supported on this version of Xcode", + }, + visibility: { + cliSummaryTable: true, + statusPage: true, + telemetry: true, + }, + } satisfies Partial, + ]); + }), +); + +// `addDiagnostic` changes global state and we must stub it, so this test must be serial. +test.serial( + "checkRunnerSupportsTracedAnalysis logs and adds diagnostic if Xcode SDK version is unsupported", + async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + const features = createFeatures([Feature.CheckUnsupportedTracedAnalysis]); + + const readlinkSync = sinon + .stub(fs, "readlinkSync") + .throws(new Error("Not found")); + const which = sinon.stub(io, "which").resolves("/path/to/xcrun"); + + let stdoutListener: ((data: Buffer) => void) | undefined = undefined; + const exec = sinon.stub<[], Promise>().callsFake(async () => { + if (stdoutListener !== undefined) { + stdoutListener(Buffer.from("27.5")); + return 0; + } else { + throw new Error("Error to force next fallback"); + } + }); + const runner = sinon.createStubInstance(toolrunner.ToolRunner, { + exec, + }); + const toolrunnerStub = sinon + .stub(toolrunner, "ToolRunner") + .callsFake((_cmd, args: string[], opts: ExecOptions) => { + if (args[0] !== "xcodebuild") { + stdoutListener = opts.listeners?.stdout; + } + return runner; + }); + + const codeql = await getCodeQLWithTracedStub( + "codeql-for-testing", + logger, + env, + ); + sinon.stub(codeql, "getVersion").resolves(makeVersionInfo("2.27.0")); + + const addDiagnostic = sinon.stub(diagnostics, "addDiagnostic"); + + const config = createTestConfig({ + tempDir: tmpDir, + languages: [BuiltInLanguage.swift], + }); + await checkRunnerSupportsTracedAnalysis( + initAllState({ + logger, + platform: "darwin", + osRelease: "26.0.0", + env, + features, + }), + config, + codeql, + ); + + t.is(readlinkSync.callCount, 1); + t.deepEqual(readlinkSync.args[0], [XCODE_SELECT_LINK_PATH]); + + t.is(which.callCount, 2); + t.is(toolrunnerStub.callCount, 2); + t.is(exec.callCount, 2); + + checkExpectedLogMessages(t, logger.messages, [ + "Unable to determine Xcode version from xcodebuild", + "Traced analysis is not supported on Xcode SDK 27", + ]); + + t.is(addDiagnostic.callCount, 1); + t.like(addDiagnostic.args[0], [ + config, + BuiltInLanguage.swift, + { + attributes: { + languages: [BuiltInLanguage.swift], + xcodeSdkVersion: "27.5.0", + }, + severity: "warning", + source: { + id: "codeql-action/unsupported-traced-analysis-xcode-sdk", + name: "Traced analysis is not supported on this version of Xcode SDK", + }, + visibility: { + cliSummaryTable: true, + statusPage: true, + telemetry: true, + }, + } satisfies Partial, + ]); + }), +); + +// `addDiagnostic` changes global state and we must stub it, so this test must be serial. +test.serial( + "checkRunnerSupportsTracedAnalysis throws if Xcode version is unsupported and FF is enabled", + async (t) => + withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + const env = getTestEnv(); + env.set(ActionsEnvVars.RUNNER_TEMP, tmpDir); + + const readlinkSync = sinon + .stub(fs, "readlinkSync") + .returns("/Applications/Xcode_27.0.app/Contents/Developer"); + + const features = createFeatures([ + Feature.CheckUnsupportedTracedAnalysis, + Feature.AbortUnsupportedTracedAnalysis, + ]); + + const codeql = await getCodeQLWithTracedStub( + "codeql-for-testing", + logger, + env, + ); + sinon.stub(codeql, "getVersion").resolves(makeVersionInfo("2.27.0")); + + const addDiagnostic = sinon.stub(diagnostics, "addDiagnostic"); + + const config = createTestConfig({ + tempDir: tmpDir, + languages: [BuiltInLanguage.swift], + }); + await t.throwsAsync( + checkRunnerSupportsTracedAnalysis( + initAllState({ + logger, + platform: "darwin", + osRelease: "26.0.0", + env, + features, + }), + config, + codeql, + ), + ); + + t.is(readlinkSync.callCount, 1); + t.deepEqual(readlinkSync.args[0], [XCODE_SELECT_LINK_PATH]); + + t.is(addDiagnostic.callCount, 1); + t.like(addDiagnostic.args[0], [ + config, + BuiltInLanguage.swift, + { + attributes: { + languages: [BuiltInLanguage.swift], + xcodeVersion: "27.0.0", + }, + severity: "error", + source: { + id: "codeql-action/unsupported-traced-analysis-xcode", + name: "Traced analysis is not supported on this version of Xcode", + }, + visibility: { + cliSummaryTable: true, + statusPage: true, + telemetry: true, + }, + } satisfies Partial, + ]); + }), +); diff --git a/src/languages/traced.ts b/src/languages/traced.ts new file mode 100644 index 0000000000..406afc9b35 --- /dev/null +++ b/src/languages/traced.ts @@ -0,0 +1,252 @@ +import * as semver from "semver"; + +import type { ActionState, Logger } from "../action-common"; +import type { CodeQL } from "../codeql"; +import type { ActionConfig } from "../config/action-config"; +import { addDiagnostic, makeDiagnostic } from "../diagnostics"; +import { DocUrl } from "../doc-url"; +import { Feature } from "../feature-flags"; +import { + darwinVersion, + xcodeVersionFromLink, + xcodeSdkVersion, + xcodeVersionFromXcodeBuild, +} from "../platform"; +import { ConfigurationError } from "../util"; + +import { checkSwiftCompatibility } from "./swift"; + +/** macOS 27 and above do not support traced extraction. */ +export const UNSUPPORTED_DARWIN_FOR_TRACED = 27; + +/** Xcode 27 and above do not support traced extraction. */ +export const UNSUPPORTED_XCODE_FOR_TRACED = 27; + +/** Names of products that we check the versions of here. */ +type ProductName = "macOS" | "Xcode" | "Xcode SDK"; + +/** A version along with the product it relates to. */ +type ProductVersion = { + product: ProductName; + version: semver.SemVer; +}; + +/** Gets the appropriate attribute name for the diagnostic based on {@link product}. */ +function diagnosticAttributeName(product: ProductName): string { + switch (product) { + case "macOS": + return "darwinVersion"; + case "Xcode": + return "xcodeVersion"; + case "Xcode SDK": + return "xcodeSdkVersion"; + } +} + +/** + * Creates a diagnostic indicating that `version` of `product` is unsupported for traced analysis. + * Depending on `skipUnsupportedTracedAnalysis`, this function then either throws a {@link ConfigurationError} + * or logs the problem as a warning. + * + * @param logger The logger to use. + * @param config The CodeQL Action configuration. + * @param tracedLanguages Traced languages that are configured for analysis. + * @param abortUnsupportedTracedAnalysis Whether this is a fatal error. + * @param productVersion A description of the product and its version that is unsupported. + */ +function handleUnsupportedVersion( + logger: Logger, + config: ActionConfig<"dbLocation" | "tempDir">, + tracedLanguages: string[], + abortUnsupportedTracedAnalysis: boolean, + productVersion: ProductVersion, +) { + const { product, version } = productVersion; + const unsupportedVersion = + product === "macOS" + ? UNSUPPORTED_DARWIN_FOR_TRACED + : // We use the same constant for both Xcode and the Xcode SDK since we treat them + // as equivalent indicators for whether traced analysis is unsupported. + UNSUPPORTED_XCODE_FOR_TRACED; + + const baseMessage = [ + `Traced analysis is not supported on ${product} ${unsupportedVersion} or above.`, + `Configure your analysis to run on macOS ${UNSUPPORTED_DARWIN_FOR_TRACED - 1} or below`, + `and Xcode ${UNSUPPORTED_XCODE_FOR_TRACED - 1} or below.`, + ].join(" "); + + const attributeName = diagnosticAttributeName(product); + + // Create a diagnostic that will show up on the TSP. + for (const language of tracedLanguages) { + addDiagnostic( + config, + language, + makeDiagnostic( + `codeql-action/unsupported-traced-analysis-${product.toLowerCase().replaceAll(" ", "-")}`, + `Traced analysis is not supported on this version of ${product}`, + { + attributes: { + languages: config.languages, + [attributeName]: version.toString(), + }, + markdownMessage: [ + baseMessage, + `For more information, see [this announcement](${DocUrl.UNSUPPORTED_TRACED_ANALYSIS_MACOS27}).`, + ].join(" "), + severity: abortUnsupportedTracedAnalysis ? "error" : "warning", + visibility: { + cliSummaryTable: true, + statusPage: true, + telemetry: true, + }, + }, + ), + ); + } + + // Log messages generally don't render as markdown, so we include the URL verbatim there. + const logMessage = [ + baseMessage, + `For more information, see ${DocUrl.UNSUPPORTED_TRACED_ANALYSIS_MACOS27}`, + ].join(" "); + + // Throw an error to abort the analysis if the FF is enabled or log the message. + if (abortUnsupportedTracedAnalysis) { + throw new ConfigurationError(logMessage); + } else { + // This will also show up as a workflow annotation. + logger.warning(logMessage); + } +} + +/** + * Returns traced languages from {@link config} by looking for tracer + * configurations in the {@link codeql} CLI installation. + */ +export async function hasTracedLanguages( + config: ActionConfig<"languages">, + codeql: CodeQL, +): Promise { + const tracedLanguages: string[] = []; + + for (const language of config.languages) { + if (await codeql.isTracedLanguage(language)) { + tracedLanguages.push(language); + } + } + + return tracedLanguages; +} + +/** + * Determines whether we can run a traced analysis on the current runner. + * + * @throws {ConfigurationError} If traced analysis is not possible on the current runner. + */ +export async function checkRunnerSupportsTracedAnalysis( + action: ActionState<["Base", "Env", "Logger", "FeatureFlags"]>, + config: ActionConfig<"languages" | "dbLocation" | "tempDir">, + codeql: CodeQL, +) { + // Try to get the Darwin version on macOS. + const version = darwinVersion(action); + + // Perform some initial, Swift-specific checks. + await checkSwiftCompatibility(config, codeql, version); + + // Skip the checks for unsupported traced analysis if the FF is not enabled. + if ( + !(await action.features.getValue(Feature.CheckUnsupportedTracedAnalysis)) + ) { + action.logger.debug( + "Skipping traced analysis compatibility checks because the feature is not enabled.", + ); + return; + } + + // `build-mode: none` doesn't use the tracer, so it is always supported. + if (config.buildMode !== undefined && config.buildMode === "none") { + action.logger.debug( + "Skipping traced analysis compatibility checks because the build mode is 'none'.", + ); + return; + } + + // These checks don't apply if we are not on macOS. + if (version === undefined) { + action.logger.debug( + "Skipping traced analysis compatibility checks because we are not on macOS.", + ); + return; + } + + // If none of the languages are traced, then we can skip the compatibility checks below as well. + const tracedLanguages = await hasTracedLanguages(config, codeql); + if (tracedLanguages.length === 0) { + action.logger.debug( + "Skipping traced analysis compatibility checks because no traced languages are being analyzed.", + ); + return; + } + + const abortUnsupportedTracedAnalysis = await action.features.getValue( + Feature.AbortUnsupportedTracedAnalysis, + ); + if (typeof version === "string") { + // If we got a string, we are on macOS but couldn't parse the version string. + action.logger.warning( + `Unable to parse Darwin kernel version, got: ${version}. Skipping macOS compatibility check.`, + ); + } else if (version.major >= UNSUPPORTED_DARWIN_FOR_TRACED) { + handleUnsupportedVersion( + action.logger, + config, + tracedLanguages, + abortUnsupportedTracedAnalysis, + { product: "macOS", version }, + ); + + // Return early so that we don't end up producing more-or-less the same log message/diagnostic + // twice. The ones for macOS already comment on the Xcode requirement. + return; + } + + // Determining whether the Xcode version is supported only makes sense on macOS, so we only do it + // after determining that we are running on macOS. We first try to obtain the version of Xcode itself + // starting with the cheapest approach and then call out to an external program. If neither works, we try + // to obtain the version from the SDK instead. Since either Xcode or the SDK at version 27 or above is + // incompatible, either is fine as we only check the major version below. + const xcodeVer = + xcodeVersionFromLink(action.logger) ?? + (await xcodeVersionFromXcodeBuild(action.logger)); + let xcodeProduct: ProductVersion | undefined = undefined; + + if (xcodeVer !== undefined) { + xcodeProduct = { product: "Xcode", version: xcodeVer }; + } else { + // Fallback to checking the SDK version, which may be available even if a full Xcode installation is not. + const xcodeSdkVer = await xcodeSdkVersion(action.logger); + xcodeProduct = + xcodeSdkVer !== undefined + ? { product: "Xcode SDK", version: xcodeSdkVer } + : undefined; + } + + if ( + xcodeProduct !== undefined && + xcodeProduct.version.major >= UNSUPPORTED_XCODE_FOR_TRACED + ) { + handleUnsupportedVersion( + action.logger, + config, + tracedLanguages, + abortUnsupportedTracedAnalysis, + xcodeProduct, + ); + } else if (xcodeProduct === undefined) { + action.logger.info( + "Unable to determine Xcode version. Skipping Xcode compatibility check.", + ); + } +} diff --git a/src/logging.test.ts b/src/logging.test.ts new file mode 100644 index 0000000000..33f6f8c162 --- /dev/null +++ b/src/logging.test.ts @@ -0,0 +1,17 @@ +import test from "ava"; + +import { joinMessageStrings } from "./logging"; +import { setupTests } from "./testing-utils"; + +setupTests(test); + +test("joinMessageStrings", async (t) => { + // For strings and errors, it is the identity function. + t.deepEqual(joinMessageStrings("Hello"), "Hello"); + + const error = new Error("Some error"); + t.deepEqual(joinMessageStrings(error), error); + + // For arrays of strings, we get a join-ed string. + t.deepEqual(joinMessageStrings(["foo", "bar"]), "foo bar"); +}); diff --git a/src/logging.ts b/src/logging.ts index 2c34cb54d4..da67168725 100644 --- a/src/logging.ts +++ b/src/logging.ts @@ -1,45 +1,92 @@ import * as core from "@actions/core"; -export interface Logger { - debug: (message: string) => void; - info: (message: string) => void; - warning: (message: string | Error) => void; - error: (message: string | Error) => void; +/** Types that all of our logging functions accept. */ +export type Loggable = string | string[]; + +/** Some logging functions also accept errors directly. */ +export type LoggableError = Loggable | Error; +export interface Logger { + /** + * Logs {@link message} at debug-level. + * In Actions, this will only be output if workflow debugging is enabled. + * + * @param message + * A string or an array of strings. If an array of strings is provided, they are joined using + * space as the delimiter and printed as a single line. + */ + debug: (message: Loggable) => void; + /** + * Logs {@link message} at info-level. + * In Actions, this will always be output. + * + * @param message + * A string or an array of strings. If an array of strings is provided, they are joined using + * space as the delimiter and printed as a single line. + */ + info: (message: Loggable) => void; + /** + * Logs {@link message} at warning-level. + * In Actions, this will always be output and highlighted as a warning. It will additionally + * result in a warning-level workflow annotation. + * + * @param message + * A string or an array of strings. If an array of strings is provided, they are joined using + * space as the delimiter and printed as a single line. + */ + warning: (message: LoggableError) => void; + /** + * Logs {@link message} at error-level. + * In Actions, this will always be output and highlighted as an error. It will additionally + * result in an error-level workflow annotation. + * + * @param message + * A string or an array of strings. If an array of strings is provided, they are joined using + * space as the delimiter and printed as a single line. + */ + error: (message: LoggableError) => void; + /** + * Gets a value indicating whether debugging is enabled. + */ isDebug: () => boolean; startGroup: (name: string) => void; endGroup: () => void; } +/** If `message` is an array of strings, the array is `join`-ed into one string separated by spaces. */ +export const joinMessageStrings = ( + message: string[] | string | T, +): string | T => { + if (Array.isArray(message)) { + return message.join(" "); + } else { + return message; + } +}; + +/** + * Wraps a logging function so that `joinMessageStrings` is applied to the input before + * calling the wrapped logging function. + */ +const autoJoinMessageStrings = (fn: (msg: string | T) => void) => { + return (message: string[] | string | T) => { + return fn(joinMessageStrings(message)); + }; +}; + export function getActionsLogger(): Logger { return { - debug: core.debug, - info: core.info, - warning: core.warning, - error: core.error, + debug: autoJoinMessageStrings(core.debug), + info: autoJoinMessageStrings(core.info), + warning: autoJoinMessageStrings(core.warning), + error: autoJoinMessageStrings(core.error), isDebug: core.isDebug, startGroup: core.startGroup, endGroup: core.endGroup, }; } -export function getRunnerLogger(debugMode: boolean): Logger { - return { - // eslint-disable-next-line no-console - debug: debugMode ? console.debug : () => undefined, - // eslint-disable-next-line no-console - info: console.info, - // eslint-disable-next-line no-console - warning: console.warn, - // eslint-disable-next-line no-console - error: console.error, - isDebug: () => debugMode, - startGroup: () => undefined, - endGroup: () => undefined, - }; -} - export function withGroup(groupName: string, f: () => T): T { core.startGroup(groupName); try { diff --git a/src/overlay/caching.test.ts b/src/overlay/caching.test.ts index daf3483ed5..e965b06a7f 100644 --- a/src/overlay/caching.test.ts +++ b/src/overlay/caching.test.ts @@ -8,13 +8,14 @@ import * as sinon from "sinon"; import * as actionsUtil from "../actions-util"; import * as apiClient from "../api-client"; import type { ResolveDatabaseOutput } from "../codeql"; +import * as environment from "../environment"; import * as gitUtils from "../git-utils"; import { BuiltInLanguage } from "../languages"; -import { getRunnerLogger } from "../logging"; import { createTestConfig, makeMacro, mockCodeQLVersion, + RecordingLogger, setupTests, } from "../testing-utils"; import * as utils from "../util"; @@ -62,7 +63,7 @@ const testDownloadOverlayBaseDatabaseFromCache = makeMacro({ const dbLocation = path.join(tmpDir, "db"); await fs.promises.mkdir(dbLocation, { recursive: true }); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const testCase = { ...defaultDownloadTestCase, ...partialTestCase }; const config = createTestConfig({ dbLocation, @@ -82,7 +83,7 @@ const testDownloadOverlayBaseDatabaseFromCache = makeMacro({ sinon.stub(apiClient, "getAutomationID").resolves("test-automation-id/"); - sinon.stub(utils, "isInTestMode").returns(testCase.isInTestMode); + sinon.stub(environment, "isInTestMode").returns(testCase.isInTestMode); if (testCase.restoreCacheResult instanceof Error) { sinon @@ -213,7 +214,7 @@ testDownloadOverlayBaseDatabaseFromCache.serial( ); test.serial("overlay-base database cache keys remain stable", async (t) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const config = createTestConfig({ languages: ["python", "javascript"] }); const codeQlVersion = "2.23.0"; const commitOid = "abc123def456"; @@ -260,7 +261,7 @@ test.serial("overlay-base database cache keys remain stable", async (t) => { test.serial( "getCodeQlVersionsForOverlayBaseDatabases returns unique versions sorted latest first", async (t) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); sinon.stub(apiClient, "getAutomationID").resolves("test-automation-id/"); sinon.stub(apiClient, "listActionsCaches").resolves([ @@ -286,7 +287,7 @@ test.serial( test.serial( "getCodeQlVersionsForOverlayBaseDatabases returns empty list when no caches exist", async (t) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); sinon.stub(apiClient, "getAutomationID").resolves("test-automation-id/"); sinon.stub(apiClient, "listActionsCaches").resolves([]); @@ -302,7 +303,7 @@ test.serial( test.serial( "getCodeQlVersionsForOverlayBaseDatabases returns empty list when cache keys are unparseable", async (t) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); sinon.stub(apiClient, "getAutomationID").resolves("test-automation-id/"); sinon.stub(apiClient, "listActionsCaches").resolves([ @@ -323,7 +324,7 @@ test.serial( test.serial( "getCodeQlVersionsForOverlayBaseDatabases returns the single version when only one cache exists", async (t) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); sinon.stub(apiClient, "getAutomationID").resolves("test-automation-id/"); sinon.stub(apiClient, "listActionsCaches").resolves([ @@ -343,7 +344,7 @@ test.serial( test.serial( "getCodeQlVersionsForOverlayBaseDatabases resolves language aliases", async (t) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); // The alias `c++` should be resolved to "cpp" and match cache entries keyed with "cpp" sinon.stub(apiClient, "getAutomationID").resolves("test-automation-id/"); @@ -364,7 +365,7 @@ test.serial( test.serial( "getCodeQlVersionsForOverlayBaseDatabases de-duplicates resolved language aliases", async (t) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); sinon.stub(apiClient, "getAutomationID").resolves("test-automation-id/"); const listActionsCachesStub = sinon @@ -390,7 +391,7 @@ test.serial( test.serial( "getCodeQlVersionsForOverlayBaseDatabases ignores nightly versions with build metadata", async (t) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); sinon.stub(apiClient, "getAutomationID").resolves("test-automation-id/"); sinon.stub(apiClient, "listActionsCaches").resolves([ diff --git a/src/overlay/caching.ts b/src/overlay/caching.ts index c4557cd4ef..02a3534bdb 100644 --- a/src/overlay/caching.ts +++ b/src/overlay/caching.ts @@ -3,11 +3,7 @@ import * as fs from "fs"; import * as actionsCache from "@actions/cache"; import * as semver from "semver"; -import { - getRequiredInput, - getWorkflowRunAttempt, - getWorkflowRunID, -} from "../actions-util"; +import { getWorkflowRunAttempt, getWorkflowRunID } from "../actions-util"; import { getAutomationID, listActionsCaches } from "../api-client"; import { createCacheKeyHash } from "../caching-utils"; import { type CodeQL } from "../codeql"; @@ -19,6 +15,7 @@ import { CleanupLevel, getBaseDatabaseOidsFilePath, getCodeQLDatabasePath, + getEnv, getErrorMessage, isInTestMode, tryGetFolderBytes, @@ -107,12 +104,13 @@ async function checkOverlayBaseDatabase( * Uploads the overlay-base database to the GitHub Actions cache. If conditions * for uploading are not met, the function does nothing and returns false. * - * This function uses the `checkout_path` input to determine the repository path + * This function uses the `checkoutPath` to determine the repository path * and works only when called from `analyze` or `upload-sarif`. * * @param codeql The CodeQL instance * @param config The configuration object * @param logger The logger instance + * @param checkoutPath The path at which the repository is checked out at. * @returns A promise that resolves to true if the upload was performed and * successfully completed, or false otherwise */ @@ -120,6 +118,7 @@ export async function cleanupAndUploadOverlayBaseDatabaseToCache( codeql: CodeQL, config: Config, logger: Logger, + checkoutPath: string, ): Promise { const overlayDatabaseMode = config.overlayDatabaseMode; if (overlayDatabaseMode !== OverlayDatabaseMode.OverlayBase) { @@ -180,7 +179,6 @@ export async function cleanupAndUploadOverlayBaseDatabaseToCache( } const codeQlVersion = (await codeql.getVersion()).version; - const checkoutPath = getRequiredInput("checkout_path"); const cacheSaveKey = await getCacheSaveKey( config, codeQlVersion, @@ -293,7 +291,7 @@ export async function downloadOverlayBaseDatabaseFromCache( actionsCache.restoreCache( [dbLocation], cacheRestoreKeyPrefix, - undefined, + [cacheRestoreKeyPrefix], { // Azure SDK download (which is the default) uses 128MB segments; see // https://github.com/actions/toolkit/blob/main/packages/cache/README.md. @@ -380,7 +378,7 @@ export async function getCacheSaveKey( `Failed to get workflow run ID or attempt ID. Reason: ${getErrorMessage(e)}`, ); } - const sha = await getCommitOid(checkoutPath); + const sha = await getCommitOid(getEnv(), checkoutPath); const restoreKeyPrefix = await getCacheRestoreKeyPrefix( config, codeQlVersion, diff --git a/src/overlay/index.test.ts b/src/overlay/index.test.ts index 967ccf3a7d..4534006f80 100644 --- a/src/overlay/index.test.ts +++ b/src/overlay/index.test.ts @@ -6,8 +6,11 @@ import * as sinon from "sinon"; import * as actionsUtil from "../actions-util"; import * as gitUtils from "../git-utils"; -import { getRunnerLogger } from "../logging"; -import { createTestConfig, setupTests } from "../testing-utils"; +import { + createTestConfig, + RecordingLogger, + setupTests, +} from "../testing-utils"; import { withTmpDir } from "../util"; import { writeBaseDatabaseOidsFile, writeOverlayChangesFile } from "."; @@ -27,7 +30,7 @@ test.serial( ), ); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const config = createTestConfig({ dbLocation }); // Mock the getFileOidsUnderPath function to return base OIDs @@ -91,7 +94,7 @@ test.serial( ), ); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const config = createTestConfig({ dbLocation }); // Mock the getFileOidsUnderPath function to return base OIDs @@ -169,7 +172,7 @@ test.serial( ), ); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const config = createTestConfig({ dbLocation }); // Mock the getFileOidsUnderPath function to return base OIDs @@ -232,7 +235,7 @@ test.serial( ), ); - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const config = createTestConfig({ dbLocation }); // Base OIDs (sourceRoot-relative paths) diff --git a/src/overlay/status.ts b/src/overlay/status.ts index 3acf382965..1a321af420 100644 --- a/src/overlay/status.ts +++ b/src/overlay/status.ts @@ -130,7 +130,7 @@ export async function getOverlayStatus( await fs.promises.mkdir(path.dirname(statusFile), { recursive: true }); const foundKey = await waitForResultWithTimeLimit( MAX_CACHE_OPERATION_MS, - actionsCache.restoreCache([statusFile], cacheKey), + actionsCache.restoreCache([statusFile], cacheKey, [cacheKey]), () => { logger.warning("Timed out restoring overlay status from cache."); }, diff --git a/src/per-language-bundles.test.ts b/src/per-language-bundles.test.ts new file mode 100644 index 0000000000..6998892507 --- /dev/null +++ b/src/per-language-bundles.test.ts @@ -0,0 +1,269 @@ +import test from "ava"; + +import { ActionsEnvVars } from "./environment"; +import { BuiltInLanguage } from "./languages"; +import { + getOtherLanguagePacksReason, + getPerLanguageBundleLanguage, + MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION, + PerLanguageBundleOptions, + QueryConfigInputs, +} from "./per-language-bundles"; +import { BundlePlatform } from "./platform"; +import { + getRecordingLogger, + getTestEnv, + initAllState, + LoggedMessage, +} from "./testing-utils"; +import { ConfigurationError, GitHubVariant } from "./util"; + +/** Options for which we would use a per-language bundle. */ +const ELIGIBLE_OPTIONS: PerLanguageBundleOptions = { + rawLanguages: ["java"], + otherLanguagePacksReason: undefined, + // Any version at least as new as the minimum will do. + cliVersion: MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION, + compressionMethod: "zstd", + platform: BundlePlatform.Linux64, + variant: GitHubVariant.DOTCOM, +}; + +async function checkEligibility( + overrides: Partial, + stateOverrides: Partial> = {}, +) { + return getPerLanguageBundleLanguage( + initAllState({ + env: getTestEnv({ + [ActionsEnvVars.RUNNER_ENVIRONMENT]: "github-hosted", + }), + ...stateOverrides, + }), + { ...ELIGIBLE_OPTIONS, ...overrides }, + ); +} + +for (const platform of Object.values(BundlePlatform)) { + test(`getPerLanguageBundleLanguage selects only supported languages on ${platform}`, async (t) => { + for (const language of Object.values(BuiltInLanguage)) { + const supported = + language === BuiltInLanguage.swift + ? platform === BundlePlatform.Osx64 + : platform === BundlePlatform.Linux64; + t.is( + await checkEligibility({ rawLanguages: [language], platform }), + supported ? language : undefined, + language, + ); + } + }); +} + +test("getPerLanguageBundleLanguage normalizes aliases before selecting a bundle", async (t) => { + t.is( + await checkEligibility({ rawLanguages: ["java-kotlin"] }), + BuiltInLanguage.java, + ); +}); + +test("getPerLanguageBundleLanguage rejects unknown platforms", async (t) => { + t.is(await checkEligibility({ platform: undefined }), undefined); +}); + +test("getPerLanguageBundleLanguage requires exactly one language", async (t) => { + t.is(await checkEligibility({ rawLanguages: undefined }), undefined); + t.is(await checkEligibility({ rawLanguages: [] }), undefined); + t.is(await checkEligibility({ rawLanguages: ["java", "python"] }), undefined); +}); + +test("getPerLanguageBundleLanguage requires a known language", async (t) => { + t.is(await checkEligibility({ rawLanguages: ["cobol"] }), undefined); +}); + +test("getPerLanguageBundleLanguage explains why the CodeQL CLI may need packs for other languages before checking the languages", async (t) => { + // Without a language, the explanation would otherwise suggest requesting a single language. + for (const rawLanguages of [["java"], undefined]) { + const messages: LoggedMessage[] = []; + const language = await checkEligibility( + { rawLanguages, otherLanguagePacksReason: "an example reason" }, + { logger: getRecordingLogger(messages, { logToConsole: false }) }, + ); + + t.is(language, undefined); + t.deepEqual( + messages.map((message) => message.message), + ["Not using a per-language CodeQL bundle since an example reason."], + ); + } +}); + +test("getPerLanguageBundleLanguage requires a zstd bundle", async (t) => { + t.is(await checkEligibility({ compressionMethod: "gzip" }), undefined); +}); + +test("getPerLanguageBundleLanguage requires GitHub.com", async (t) => { + // Other products resolve the combined bundle against their own instance, so asking for a + // per-language bundle they do not mirror would move the download off that instance. + for (const variant of [GitHubVariant.GHES, GitHubVariant.GHEC_DR]) { + t.is(await checkEligibility({ variant }), undefined); + } +}); + +test("getPerLanguageBundleLanguage requires a GitHub-hosted runner", async (t) => { + // A self-hosted runner may have a toolcache that persists between jobs, which is worth more than + // a smaller download. + t.is( + await checkEligibility( + {}, + { + env: getTestEnv({ [ActionsEnvVars.RUNNER_ENVIRONMENT]: "self-hosted" }), + }, + ), + undefined, + ); + + // Self-hosted runners are routinely configured to look like hosted ones, for example by mounting + // a persistent volume at `/opt/hostedtoolcache`, so we require the service to tell us explicitly. + t.is( + await checkEligibility( + {}, + { + env: getTestEnv({ RUNNER_TOOL_CACHE: "/opt/hostedtoolcache" }), + }, + ), + undefined, + ); +}); + +test("getPerLanguageBundleLanguage requires a supported release version", async (t) => { + t.is(await checkEligibility({ cliVersion: undefined }), undefined); + t.is(await checkEligibility({ cliVersion: "2.27.0" }), undefined); + t.is(await checkEligibility({ cliVersion: "2.27.1" }), BuiltInLanguage.java); +}); + +test("getPerLanguageBundleLanguage skips only the release version check for the latest nightly", async (t) => { + const nightly = { isLatestNightly: true, cliVersion: undefined }; + t.is(await checkEligibility(nightly), BuiltInLanguage.java); + + for (const overrides of [ + { rawLanguages: undefined }, + { rawLanguages: ["java", "python"] }, + { otherLanguagePacksReason: "an example reason" }, + { compressionMethod: "gzip" as const }, + { platform: BundlePlatform.Osx64 }, + { variant: GitHubVariant.GHES }, + { variant: GitHubVariant.GHEC_DR }, + ]) { + t.is(await checkEligibility({ ...nightly, ...overrides }), undefined); + } + t.is( + await checkEligibility(nightly, { + env: getTestEnv({ [ActionsEnvVars.RUNNER_ENVIRONMENT]: "self-hosted" }), + }), + undefined, + ); +}); + +/** Query configuration inputs that configure nothing. */ +const NO_QUERY_CONFIG: QueryConfigInputs = { + configFile: undefined, + configInput: undefined, + queriesInput: undefined, + extraQueriesProperty: undefined, +}; + +test("getOtherLanguagePacksReason returns undefined when no queries are configured", (t) => { + t.is(getOtherLanguagePacksReason(NO_QUERY_CONFIG), undefined); +}); + +test("getOtherLanguagePacksReason returns undefined for built-in query suites", (t) => { + for (const queries of [ + "security-extended", + "+security-and-quality", + " security-extended , code-quality ", + ]) { + t.is( + getOtherLanguagePacksReason({ + ...NO_QUERY_CONFIG, + queriesInput: queries, + extraQueriesProperty: queries, + }), + undefined, + queries, + ); + } +}); + +test("getOtherLanguagePacksReason returns undefined for a config input that only uses default setup properties", (t) => { + t.is( + getOtherLanguagePacksReason({ + ...NO_QUERY_CONFIG, + // The configuration from the `config` input that default setup passes. + configInput: { + "default-setup": { + org: { "model-packs": ["github/immutable-actions-list@0.0.1"] }, + }, + "threat-models": [], + }, + }), + undefined, + ); +}); + +test("getOtherLanguagePacksReason explains a configuration file", (t) => { + t.is( + getOtherLanguagePacksReason({ + ...NO_QUERY_CONFIG, + configFile: "./.github/codeql/codeql-config.yml", + }), + "the configuration file './.github/codeql/codeql-config.yml' may use queries that need " + + "library packs for other languages", + ); +}); + +test("getOtherLanguagePacksReason explains a config input that uses other properties", (t) => { + t.is( + getOtherLanguagePacksReason({ + ...NO_QUERY_CONFIG, + configInput: { queries: [{ uses: "./queries/show_ifs.ql" }] }, + }), + "the 'config' input may use queries that need library packs for other languages", + ); +}); + +test("getOtherLanguagePacksReason explains the first query in the queries input that isn't a built-in query suite", (t) => { + t.is( + getOtherLanguagePacksReason({ + ...NO_QUERY_CONFIG, + queriesInput: + "+security-extended, ./queries/show_ifs.ql, octo-org/queries@main", + }), + "the query './queries/show_ifs.ql' from the 'queries' input may need library packs for " + + "other languages", + ); +}); + +test("getOtherLanguagePacksReason explains a query in the extra queries repository property that isn't a built-in query suite", (t) => { + t.is( + getOtherLanguagePacksReason({ + ...NO_QUERY_CONFIG, + extraQueriesProperty: "+octo-org/queries/show_ifs.ql@main", + }), + "the query 'octo-org/queries/show_ifs.ql@main' from the 'github-codeql-extra-queries' " + + "repository property may need library packs for other languages", + ); +}); + +test("getOtherLanguagePacksReason throws a ConfigurationError for a '+' with no queries after it", (t) => { + // Loading the configuration would throw the same errors. + for (const inputs of [ + { queriesInput: "+" }, + { extraQueriesProperty: " + " }, + ]) { + t.throws( + () => getOtherLanguagePacksReason({ ...NO_QUERY_CONFIG, ...inputs }), + { instanceOf: ConfigurationError }, + ); + } +}); diff --git a/src/per-language-bundles.ts b/src/per-language-bundles.ts new file mode 100644 index 0000000000..14c8830203 --- /dev/null +++ b/src/per-language-bundles.ts @@ -0,0 +1,240 @@ +import * as semver from "semver"; + +import { ActionState } from "./action-common"; +import { isGitHubHostedRunner } from "./actions-util"; +import { + defaultSuites, + matchesDefaultSetupConfigSchema, + parseQueriesFromInput, + QuerySpec, + UserConfig, +} from "./config/db-config"; +import { RepositoryPropertyName } from "./feature-flags/properties"; +import { BuiltInLanguage, parseBuiltInLanguage } from "./languages"; +import { BundlePlatform } from "./platform"; +import * as tar from "./tar"; +import { GitHubVariant } from "./util"; + +/** Minimum CLI version for selecting a per-language release bundle. */ +export const MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION = "2.27.1"; + +/** Languages with per-language bundles published for each platform. */ +const PER_LANGUAGE_BUNDLE_LANGUAGES: Readonly< + Record> +> = { + [BundlePlatform.Linux64]: new Set([ + BuiltInLanguage.actions, + BuiltInLanguage.cpp, + BuiltInLanguage.csharp, + BuiltInLanguage.go, + BuiltInLanguage.java, + BuiltInLanguage.javascript, + BuiltInLanguage.python, + BuiltInLanguage.ruby, + BuiltInLanguage.rust, + ]), + [BundlePlatform.LinuxArm64]: new Set(), + [BundlePlatform.Osx64]: new Set([BuiltInLanguage.swift]), + [BundlePlatform.Win64]: new Set(), +}; + +/** Query configuration that is known before CodeQL is set up. */ +export interface QueryConfigInputs { + /** The configuration file from the `config-file` input or repository property. */ + configFile: string | undefined; + /** The configuration from the `config` input. */ + configInput: UserConfig | undefined; + /** The `queries` input. */ + queriesInput: string | undefined; + /** The `github-codeql-extra-queries` repository property. */ + extraQueriesProperty: string | undefined; +} + +/** + * Explains why the configured queries may need library packs for languages other than the one + * being analyzed, which a per-language bundle doesn't contain. Returns `undefined` if the only + * queries that these inputs add are built-in query suites. The `packs` input doesn't matter, since + * query packs are downloaded together with their dependencies. + * + * Any configuration file is assumed to configure such queries, since reading it may need file or API + * access. So is the `config` input, unless it only sets the properties that default setup is known + * to set (see `matchesDefaultSetupConfigSchema`). + * + * @throws A `ConfigurationError` if the `queries` input or the `github-codeql-extra-queries` + * repository property is a '+' with no queries after it, unless an input that's checked earlier + * already gives a reason. + */ +export function getOtherLanguagePacksReason( + inputs: QueryConfigInputs, +): string | undefined { + if (inputs.configFile !== undefined) { + return ( + `the configuration file '${inputs.configFile}' may use queries that need library packs ` + + "for other languages" + ); + } + + // The `config` input can configure queries in the same way as a configuration file. The + // properties that default setup is known to set, listed in `DEFAULT_SETUP_CONFIG_SCHEMA` in + // `config/db-config.ts`, don't add queries. + if ( + inputs.configInput !== undefined && + !matchesDefaultSetupConfigSchema(inputs.configInput) + ) { + return "the 'config' input may use queries that need library packs for other languages"; + } + + // We can't tell which language a local query or a query from another repository is for without + // loading it, and CodeQL resolves the library packs for every configured query, including those + // for languages that aren't being analyzed. + const query = findNonBuiltInQuery( + parseQueriesFromInput(inputs.queriesInput).input, + ); + if (query !== undefined) { + return `the query '${query}' from the 'queries' input may need library packs for other languages`; + } + const extraQuery = findNonBuiltInQuery( + parseQueriesFromInput( + inputs.extraQueriesProperty, + RepositoryPropertyName.EXTRA_QUERIES, + ).input, + ); + if (extraQuery !== undefined) { + return ( + `the query '${extraQuery}' from the '${RepositoryPropertyName.EXTRA_QUERIES}' repository ` + + "property may need library packs for other languages" + ); + } + + return undefined; +} + +/** Returns the `uses` value of the first of `queries` that isn't a built-in query suite. */ +function findNonBuiltInQuery( + queries: QuerySpec[] | undefined, +): string | undefined { + return queries?.find((query) => !defaultSuites.has(query.uses))?.uses; +} + +/** Inputs that determine whether we may download a per-language bundle. */ +export interface PerLanguageBundleOptions { + /** Explicit input only: autodetection needs a CLI instance. */ + rawLanguages: string[] | undefined; + /** + * Why the CodeQL CLI may need packs for other languages, for example because of the configured + * queries, or `undefined` if it won't. If defined, the combined bundle is used, and this reason is + * logged to complete the sentence "Not using a per-language CodeQL bundle since ...". See + * `getOtherLanguagePacksReason`. + */ + otherLanguagePacksReason: string | undefined; + /** Requested CLI version, if known. Ignored when requesting the latest nightly. */ + cliVersion: string | undefined; + compressionMethod: tar.CompressionMethod; + /** Platform for which the bundle is requested. */ + platform: BundlePlatform | undefined; + variant: GitHubVariant; + /** Whether the Action is selecting the latest nightly rather than a release version. */ + isLatestNightly?: boolean; +} + +/** Returns the eligible bundle language, or undefined for the combined bundle. */ +export function getPerLanguageBundleLanguage( + action: ActionState<["Logger", "ReadOnlyEnv"]>, + options: PerLanguageBundleOptions, +): BuiltInLanguage | undefined { + const { + rawLanguages, + otherLanguagePacksReason, + cliVersion, + compressionMethod, + platform, + variant, + isLatestNightly, + } = options; + + const explain = (reason: string) => { + action.logger.debug( + `Not using a per-language CodeQL bundle since ${reason}.`, + ); + return undefined; + }; + + // A defined reason means the CodeQL CLI may need packs for other languages, for example because + // of the configured queries. That applies whichever languages were requested, so check it first + // to avoid suggesting that requesting a single language would be enough. + if (otherLanguagePacksReason !== undefined) { + return explain(otherLanguagePacksReason); + } + + if (rawLanguages?.length !== 1) { + return explain( + `exactly one language must be requested via the 'languages' input, but ${ + rawLanguages?.length ?? 0 + } were`, + ); + } + + const language = parseBuiltInLanguage(rawLanguages[0]); + if (language === undefined) { + return explain(`'${rawLanguages[0]}' is not a known CodeQL language`); + } + + if (compressionMethod !== "zstd") { + // Per-language bundles are only published as zstd archives. + return explain(`the bundle would be downloaded as '${compressionMethod}'`); + } + + if (variant !== GitHubVariant.DOTCOM) { + // Tenant mirrors may lack these assets, and an unreachable github.com fails with a + // connection error rather than a recoverable 404. + return explain(`we are running against ${variant}`); + } + + if (!isGitHubHostedRunner(action.env)) { + // Per-language installs stay out of the toolcache; self-hosted runners should retain + // the reusable combined bundle instead. + return explain("the job is not running on a GitHub-hosted runner"); + } + + // Nightly releases are identified by dates rather than versions. If + // `isLatestNightly` is `true`, the latest nightly is requested with + // `tools: nightly` and we don't yet have the corresponding tag at this point. + // Therefore, we skip the version check and don't have an equivalent. + // We can safely assume that the latest nightly will have per-language bundles. + if (!isLatestNightly) { + if (cliVersion === undefined) { + return explain("the requested CLI version is unknown"); + } + + if (!semver.gte(cliVersion, MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION)) { + return explain( + `the requested CodeQL version ${cliVersion} is older than ${MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION}, which is the ` + + "first version for which per-language bundles are published", + ); + } + } + + if ( + platform === undefined || + !PER_LANGUAGE_BUNDLE_LANGUAGES[platform].has(language) + ) { + return explain( + `no per-language bundle is published for ${language} on ${platform ?? "an unknown platform"}`, + ); + } + + return language; +} + +/** Explains why an eligible per-language bundle is being replaced by a combined bundle. */ +export function logPerLanguageBundleFallback( + { logger }: ActionState<["Logger"]>, + language: BuiltInLanguage, + location: string, +): void { + logger.warning( + `No per-language CodeQL bundle for '${language}' was found at ${location}, so ` + + "falling back to the bundle that contains all languages. This analysis will still " + + "produce correct results, but will take longer to set up.", + ); +} diff --git a/src/platform.test.ts b/src/platform.test.ts new file mode 100644 index 0000000000..e696142027 --- /dev/null +++ b/src/platform.test.ts @@ -0,0 +1,362 @@ +import fs from "fs"; + +import type { ExecOptions } from "@actions/exec/lib/interfaces"; +import * as toolrunner from "@actions/exec/lib/toolrunner"; +import * as io from "@actions/io"; +import test from "ava"; +import * as sinon from "sinon"; + +import { + BundlePlatform, + getBundlePlatform, + darwinVersion, + XCODE_SELECT_LINK_PATH, + xcodeVersionFromLink, + xcodeSdkVersion, + xcodeVersionFromXcodeBuild, +} from "./platform"; +import { + checkExpectedLogMessages, + initAllState, + RecordingLogger, + setupTests, +} from "./testing-utils"; + +setupTests(test); + +for (const [platform, arch, expected] of [ + ["linux", "x64", BundlePlatform.Linux64], + ["linux", "arm64", BundlePlatform.LinuxArm64], + ["linux", "ia32", BundlePlatform.Linux64], + ["darwin", "x64", BundlePlatform.Osx64], + ["darwin", "arm64", BundlePlatform.Osx64], + ["win32", "x64", BundlePlatform.Win64], + ["win32", "arm64", BundlePlatform.Win64], + ["freebsd", "x64", undefined], +] as const) { + test(`getBundlePlatform maps ${platform}/${arch} to ${expected ?? "an all-platform bundle"}`, (t) => { + t.is(getBundlePlatform(platform, arch), expected); + }); +} + +const platforms: NodeJS.Platform[] = ["linux", "win32", "freebsd"]; +for (const platform of platforms) { + test(`darwinVersion returns undefined on ${platform}`, (t) => { + t.is(darwinVersion(initAllState({ platform })), undefined); + }); +} + +test("darwinVersion returns raw string if semver parsing fails", (t) => { + const invalidSemVer = "sealOS-2026"; + t.is( + darwinVersion( + initAllState({ platform: "darwin", osRelease: invalidSemVer }), + ), + invalidSemVer, + ); +}); + +test("darwinVersion returns semver if parsing succeeds", (t) => { + const validSemVer = "27.0.1"; + + const version = darwinVersion( + initAllState({ platform: "darwin", osRelease: validSemVer }), + ); + + // Check that `version` is not undefined and narrow the type; throws if undefined. + if (t.truthy(version)) { + // Check that it's also not just a string. + t.not(typeof version, "string"); + + // Should be an object with the expected properties. + t.is(typeof version, "object"); + t.is(version["major"], 27); + t.is(version["minor"], 0); + t.is(version["patch"], 1); + } +}); + +test.serial( + "xcodeVersionFromLink returns undefined if symlink doesn't exist", + (t) => { + const logger = new RecordingLogger(); + + const readlinkSync = sinon + .stub(fs, "readlinkSync") + .throws(new Error("ENOENT: no such file or directory")); + + t.is(xcodeVersionFromLink(logger), undefined); + t.is(readlinkSync.callCount, 1); + t.deepEqual(readlinkSync.args[0], [XCODE_SELECT_LINK_PATH]); + + checkExpectedLogMessages(t, logger.messages, [ + "Unable to determine Xcode version: ENOENT: no such file or directory", + ]); + }, +); + +test.serial( + "xcodeVersionFromLink returns undefined if file is not a symlink", + (t) => { + const logger = new RecordingLogger(); + + const readlinkSync = sinon + .stub(fs, "readlinkSync") + .throws(new Error("EINVAL: invalid argument")); + + t.is(xcodeVersionFromLink(logger), undefined); + t.is(readlinkSync.callCount, 1); + t.deepEqual(readlinkSync.args[0], [XCODE_SELECT_LINK_PATH]); + + checkExpectedLogMessages(t, logger.messages, [ + "Unable to determine Xcode version: EINVAL: invalid argument", + ]); + }, +); + +test.serial( + "xcodeVersionFromLink returns undefined if resolving the symlink returns nothing", + (t) => { + const logger = new RecordingLogger(); + + const readlinkSync = sinon.stub(fs, "readlinkSync").returns(""); + + t.is(xcodeVersionFromLink(logger), undefined); + t.is(readlinkSync.callCount, 1); + t.deepEqual(readlinkSync.args[0], [XCODE_SELECT_LINK_PATH]); + + checkExpectedLogMessages(t, logger.messages, [ + "unexpectedly returned nothing", + ]); + }, +); + +test.serial( + "xcodeVersionFromLink returns undefined if resolved path doesn't include pattern", + (t) => { + const logger = new RecordingLogger(); + + const readlinkSync = sinon + .stub(fs, "readlinkSync") + .returns("/Applications/Xcode.app/Contents/Developer"); + + t.is(xcodeVersionFromLink(logger), undefined); + t.is(readlinkSync.callCount, 1); + t.deepEqual(readlinkSync.args[0], [XCODE_SELECT_LINK_PATH]); + + checkExpectedLogMessages(t, logger.messages, [ + "does not contain expected pattern", + ]); + }, +); + +test.serial( + "xcodeVersionFromLink returns undefined if match can't be parsed", + (t) => { + const logger = new RecordingLogger(); + + const readlinkSync = sinon + .stub(fs, "readlinkSync") + .returns("/Applications/Xcode_00.0.app/Contents/Developer"); + + t.is(xcodeVersionFromLink(logger), undefined); + t.is(readlinkSync.callCount, 1); + t.deepEqual(readlinkSync.args[0], [XCODE_SELECT_LINK_PATH]); + + checkExpectedLogMessages(t, logger.messages, [ + "Couldn't parse '00.0' as a semantic version.", + ]); + }, +); + +test.serial("xcodeVersionFromLink returns version from resolved path", (t) => { + const logger = new RecordingLogger(); + + const readlinkSync = sinon + .stub(fs, "readlinkSync") + .returns("/Applications/Xcode_16.4.app/Contents/Developer"); + + const result = xcodeVersionFromLink(logger); + + if (t.truthy(result)) { + t.is(result.major, 16); + t.is(result.minor, 4); + } + + t.is(readlinkSync.callCount, 1); + t.deepEqual(readlinkSync.args[0], [XCODE_SELECT_LINK_PATH]); +}); + +test.serial( + "xcodeVersionFromLink returns major version from resolved path", + (t) => { + const logger = new RecordingLogger(); + + const readlinkSync = sinon + .stub(fs, "readlinkSync") + .returns("/Applications/Xcode_16.app/Contents/Developer"); + + const result = xcodeVersionFromLink(logger); + + if (t.truthy(result)) { + t.is(result.major, 16); + t.is(result.minor, 0); + } + + t.is(readlinkSync.callCount, 1); + t.deepEqual(readlinkSync.args[0], [XCODE_SELECT_LINK_PATH]); + }, +); + +test.serial( + "xcodeVersionFromLink allows more version components in resolved path", + (t) => { + const logger = new RecordingLogger(); + + const readlinkSync = sinon + .stub(fs, "readlinkSync") + .returns("/Applications/Xcode_16.5.9.app/Contents/Developer"); + + const result = xcodeVersionFromLink(logger); + + if (t.truthy(result)) { + t.is(result.major, 16); + t.is(result.minor, 5); + } + + t.is(readlinkSync.callCount, 1); + t.deepEqual(readlinkSync.args[0], [XCODE_SELECT_LINK_PATH]); + }, +); + +test.serial( + "xcodeVersionFromXcodeBuild returns undefined for non-zero exit code", + async (t) => { + const logger = new RecordingLogger(); + + const which = sinon.stub(io, "which").resolves("/path/to/xcrun"); + const exec = sinon.stub<[], Promise>().resolves(1); + const runner = sinon.createStubInstance(toolrunner.ToolRunner, { exec }); + const toolrunnerStub = sinon.stub(toolrunner, "ToolRunner").returns(runner); + + await t.notThrowsAsync(async () => { + const result = await xcodeVersionFromXcodeBuild(logger); + + t.is(result, undefined); + + t.is(which.callCount, 1); + t.deepEqual(which.args[0], ["xcrun", true]); + + t.is(toolrunnerStub.callCount, 1); + t.is(exec.callCount, 1); + + checkExpectedLogMessages(t, logger.messages, [ + "xcodebuild returned exit code 1", + ]); + }); + }, +); + +test.serial( + "xcodeVersionFromXcodeBuild extracts version from xcrun stdout", + async (t) => { + const logger = new RecordingLogger(); + + const which = sinon.stub(io, "which").resolves("/path/to/xcrun"); + + let stdoutListener: ((data: Buffer) => void) | undefined = undefined; + const exec = sinon.stub<[], Promise>().callsFake(async () => { + if (stdoutListener !== undefined) { + stdoutListener(Buffer.from("Xcode 26.5")); + stdoutListener(Buffer.from("Build version 26F9")); + } + return 0; + }); + const runner = sinon.createStubInstance(toolrunner.ToolRunner, { exec }); + + const toolrunnerStub = sinon + .stub(toolrunner, "ToolRunner") + .callsFake((_cmd, _args, opts: ExecOptions) => { + stdoutListener = opts.listeners?.stdout; + return runner; + }); + + await t.notThrowsAsync(async () => { + const result = await xcodeVersionFromXcodeBuild(logger); + + t.not(result, undefined); + t.is(result?.major, 26); + t.is(result?.minor, 5); + + t.is(which.callCount, 1); + t.deepEqual(which.args[0], ["xcrun", true]); + + t.is(toolrunnerStub.callCount, 1); + t.is(exec.callCount, 1); + }); + }, +); + +test.serial( + "xcodeSdkVersion returns undefined for non-zero exit code", + async (t) => { + const logger = new RecordingLogger(); + + const which = sinon.stub(io, "which").resolves("/path/to/xcrun"); + const exec = sinon.stub<[], Promise>().resolves(1); + const runner = sinon.createStubInstance(toolrunner.ToolRunner, { exec }); + const toolrunnerStub = sinon.stub(toolrunner, "ToolRunner").returns(runner); + + await t.notThrowsAsync(async () => { + const result = await xcodeSdkVersion(logger); + + t.is(result, undefined); + + t.is(which.callCount, 1); + t.deepEqual(which.args[0], ["xcrun", true]); + + t.is(toolrunnerStub.callCount, 1); + t.is(exec.callCount, 1); + + checkExpectedLogMessages(t, logger.messages, [ + "xcrun returned exit code 1", + ]); + }); + }, +); + +test.serial("xcodeSdkVersion extracts version from xcrun stdout", async (t) => { + const logger = new RecordingLogger(); + + const which = sinon.stub(io, "which").resolves("/path/to/xcrun"); + + let stdoutListener: ((data: Buffer) => void) | undefined = undefined; + const exec = sinon.stub<[], Promise>().callsFake(async () => { + if (stdoutListener !== undefined) { + stdoutListener(Buffer.from("26.5")); + } + return 0; + }); + const runner = sinon.createStubInstance(toolrunner.ToolRunner, { exec }); + + const toolrunnerStub = sinon + .stub(toolrunner, "ToolRunner") + .callsFake((_cmd, _args, opts: ExecOptions) => { + stdoutListener = opts.listeners?.stdout; + return runner; + }); + + await t.notThrowsAsync(async () => { + const result = await xcodeSdkVersion(logger); + + t.not(result, undefined); + t.is(result?.major, 26); + t.is(result?.minor, 5); + + t.is(which.callCount, 1); + t.deepEqual(which.args[0], ["xcrun", true]); + + t.is(toolrunnerStub.callCount, 1); + t.is(exec.callCount, 1); + }); +}); diff --git a/src/platform.ts b/src/platform.ts new file mode 100644 index 0000000000..283a789c0b --- /dev/null +++ b/src/platform.ts @@ -0,0 +1,245 @@ +import fs from "fs"; + +import * as toolrunner from "@actions/exec/lib/toolrunner"; +import * as io from "@actions/io"; +import * as semver from "semver"; + +import type { ActionState, Logger } from "./action-common"; +import { getErrorMessage } from "./util"; + +/** Platform identifiers used in CodeQL bundle asset names. */ +export enum BundlePlatform { + Linux64 = "linux64", + LinuxArm64 = "linux-arm64", + Osx64 = "osx64", + Win64 = "win64", +} + +/** Returns the bundle platform, or undefined when an all-platform bundle is required. */ +export function getBundlePlatform( + platform: NodeJS.Platform = process.platform, + arch: NodeJS.Architecture = process.arch, +): BundlePlatform | undefined { + switch (platform) { + case "win32": + return BundlePlatform.Win64; + case "linux": + return arch === "arm64" + ? BundlePlatform.LinuxArm64 + : BundlePlatform.Linux64; + case "darwin": + return BundlePlatform.Osx64; + default: + return undefined; + } +} + +/** + * Tries to determine the version of the Darwin kernel. We use this to approximate the macOS version based + * on the Darwin kernel version so that we don't have to launch an external process. Note that the Darwin + * kernel major version does not correspond perfectly to the macOS major version. + * + * @returns + * The version as either a semantic version object, the raw version string + * if it is not a semantic version, or `undefined` if we are not on macOS. + */ +export function darwinVersion( + action: ActionState<["Base"]>, +): semver.SemVer | string | undefined { + // Skip if we are not running on macOS. + if (action.platform !== "darwin") { + return undefined; + } + + // Try to parse the kernel version string. + const version = semver.parse(action.osRelease); + + if (version === null) { + return action.osRelease; + } + + return version; +} + +/** The static path we check for a symbolic link to the (dynamic) Xcode location. */ +export const XCODE_SELECT_LINK_PATH = "/private/var/db/xcode_select_link"; + +/** The pattern we expect to find in the Xcode path. */ +export const XCODE_APP_FILENAME_PATTERN = new RegExp( + /(?Xcode_(?\d+(\.\d+)?).*\.app)/, +); + +/** + * Tries to determine the version of Xcode that is installed from the resolved symbolic link + * at {@link XCODE_SELECT_LINK_PATH}. + * + * @param logger The logger to use. + * @returns The Xcode version or `undefined` if it couldn't be determined. + */ +export function xcodeVersionFromLink( + logger: Logger, +): semver.SemVer | undefined { + try { + // Read what the symbolic link points to. This will throw if `XCODE_SELECT_LINK_PATH` does not + // exist (`ENOENT`) or is not a symbolic link (`EINVAL`). + const xcodePath = fs.readlinkSync(XCODE_SELECT_LINK_PATH); + + if (xcodePath.trim() === "") { + logger.debug( + `Resolving ${XCODE_SELECT_LINK_PATH} unexpectedly returned nothing.`, + ); + return undefined; + } + + // Try to extract the version from the path. + const matchResult = xcodePath.match(XCODE_APP_FILENAME_PATTERN); + + if (matchResult?.groups === undefined) { + logger.debug( + `Xcode path '${xcodePath}' does not contain expected pattern.`, + ); + return undefined; + } + + const majorMinor = matchResult.groups["majorMinor"]; + const version = semver.coerce(majorMinor); + + if (version === null) { + logger.debug(`Couldn't parse '${majorMinor}' as a semantic version.`); + return undefined; + } + return version; + } catch (err) { + logger.debug(`Unable to determine Xcode version: ${getErrorMessage(err)}`); + return undefined; + } +} + +/** + * Tries to determine the version of Xcode that is installed by running `xcrun xcodebuild -version`. + * + * @param logger The logger to use. + * @returns The Xcode version or `undefined` if it couldn't be determined. + */ +export async function xcodeVersionFromXcodeBuild( + logger: Logger, +): Promise { + try { + const xcrun = await io.which("xcrun", true); + let stdout = ""; + let stderr = ""; + + const exitCode = await new toolrunner.ToolRunner( + xcrun, + ["xcodebuild", "-version"], + { + silent: true, + ignoreReturnCode: true, + listeners: { + stdout: (data: Buffer) => { + stdout += data.toString("utf-8"); + }, + stderr: (data: Buffer) => { + stderr += data.toString("utf-8"); + }, + }, + }, + ).exec(); + + if (exitCode !== 0) { + logger.debug(`xcodebuild returned exit code ${exitCode}`); + logger.debug(`stdout:\n${stdout}`); + logger.debug(`stderr:\n${stderr}`); + return undefined; + } + + // The output contains a couple of lines, but we only care about the product version. + const match = stdout.match(/^Xcode (\d+(\.\d+)?)/); + + if (match === null) { + logger.debug( + `Output doesn't appear to contain the Xcode product version.`, + ); + logger.debug(`stdout:\n${stdout}`); + logger.debug(`stderr:\n${stderr}`); + return undefined; + } + + // We expect the output to only be a version string. Try to parse it into a semver. + const version = semver.coerce(match[1].trim()); + + if (version === null) { + logger.debug( + `xcodebuild's output couldn't be parsed as a version:\n${stdout}`, + ); + logger.debug(`stderr:\n${stderr}`); + return undefined; + } + + return version; + } catch (err) { + logger.debug( + `Unable to determine Xcode version from xcodebuild: ${getErrorMessage(err)}`, + ); + return undefined; + } +} + +/** + * Tries to determine the version of the Xcode SDK that is installed by running + * `xcrun --sdk macosx --show-sdk-version`. + * + * @param logger The logger to use. + * @returns The Xcode SDK version or `undefined` if it couldn't be determined. + */ +export async function xcodeSdkVersion( + logger: Logger, +): Promise { + try { + const xcrun = await io.which("xcrun", true); + let stdout = ""; + let stderr = ""; + + const exitCode = await new toolrunner.ToolRunner( + xcrun, + ["--sdk", "macosx", "--show-sdk-version"], + { + silent: true, + ignoreReturnCode: true, + listeners: { + stdout: (data: Buffer) => { + stdout += data.toString("utf-8"); + }, + stderr: (data: Buffer) => { + stderr += data.toString("utf-8"); + }, + }, + }, + ).exec(); + + if (exitCode !== 0) { + logger.debug(`xcrun returned exit code ${exitCode}`); + logger.debug(`stdout:\n${stdout}`); + logger.debug(`stderr:\n${stderr}`); + return undefined; + } + + // We expect the output to only be a version string. Try to parse it into a semver. + const version = semver.coerce(stdout.trim()); + + if (version === null) { + logger.debug( + `xcrun's output couldn't be parsed as a version:\n${stdout}`, + ); + logger.debug(`stderr:\n${stderr}`); + return undefined; + } + + return version; + } catch (err) { + logger.debug( + `Unable to determine Xcode SDK version: ${getErrorMessage(err)}`, + ); + return undefined; + } +} diff --git a/src/repository.ts b/src/repository.ts index f1e7f369bc..652521fe33 100644 --- a/src/repository.ts +++ b/src/repository.ts @@ -6,6 +6,14 @@ export interface RepositoryNwo { repo: string; } +/** An approximation of what a repository NWO string looks like. */ +export type RepositoryNwoStr = `${string}/${string}`; + +/** A basic check that `val` looks like a `RepositoryNwoStr`. */ +export function isRepositoryNwoStr(val: string): val is RepositoryNwoStr { + return val.includes("/"); +} + /** * Get the repository name with owner from the environment variable * `GITHUB_REPOSITORY`. diff --git a/src/sarif/index.ts b/src/sarif/index.ts index 3cd537dafb..ecb603a273 100644 --- a/src/sarif/index.ts +++ b/src/sarif/index.ts @@ -1,6 +1,7 @@ import * as fs from "fs"; import { Logger } from "../logging"; +import { getErrorMessage } from "../util"; import * as sarif from "sarif"; @@ -48,7 +49,13 @@ export function getToolNames(sarifFile: Partial): string[] { * @returns The resulting JSON value, cast to a SARIF `Log`. */ export function readSarifFile(sarifFilePath: string): Partial { - return JSON.parse(fs.readFileSync(sarifFilePath, "utf8")) as sarif.Log; + try { + return JSON.parse(fs.readFileSync(sarifFilePath, "utf8")) as sarif.Log; + } catch (err) { + throw new Error( + `Parsing SARIF file at '${sarifFilePath}' failed: ${getErrorMessage(err)}`, + ); + } } // Takes a list of paths to sarif files and combines them together, diff --git a/src/setup-codeql-action.ts b/src/setup-codeql-action.ts index 7873449f9c..1bbfdacecc 100644 --- a/src/setup-codeql-action.ts +++ b/src/setup-codeql-action.ts @@ -1,6 +1,11 @@ import * as core from "@actions/core"; -import { Action, ActionState, runInActions } from "./action-common"; +import { + Action, + ActionState, + extendActionState, + runInActions, +} from "./action-common"; import { getActionVersion, getOptionalInput, @@ -15,6 +20,7 @@ import { getRawLanguagesNoAutodetect } from "./config-utils"; import { EnvVar } from "./environment"; import { initFeatures } from "./feature-flags"; import { loadRepositoryProperties } from "./feature-flags/properties"; +import * as github from "./github"; import { initCodeQL } from "./init"; import { Logger } from "./logging"; import { getRepositoryNwo } from "./repository"; @@ -22,18 +28,16 @@ import { ToolsSource } from "./setup-codeql"; import { ActionName, InitStatusReport, - InitToolsDownloadFields, createStatusReportBase, getActionsStatus, sendStatusReport, } from "./status-report"; +import { createInitToolsDownloadFields } from "./status-report/tools-download"; import { ToolsDownloadStatusReport } from "./tools-download"; import { checkDiskUsage, checkForTimeout, checkGitHubVersionInRange, - getRequiredEnvParam, - initializeEnvironment, ConfigurationError, wrapError, checkActionVersion, @@ -79,15 +83,10 @@ async function sendCompletedStatusReport( initStatusReport.computed_inputs.tools = toolsInput; } - const initToolsDownloadFields: InitToolsDownloadFields = {}; - - if (toolsDownloadStatusReport?.downloadDurationMs !== undefined) { - initToolsDownloadFields.tools_download_duration_ms = - toolsDownloadStatusReport.downloadDurationMs; - } - if (toolsFeatureFlagsValid !== undefined) { - initToolsDownloadFields.tools_feature_flags_valid = toolsFeatureFlagsValid; - } + const initToolsDownloadFields = createInitToolsDownloadFields( + toolsDownloadStatusReport, + toolsFeatureFlagsValid, + ); await sendStatusReport({ ...initStatusReport, ...initToolsDownloadFields }); } @@ -108,13 +107,12 @@ async function run( let toolsVersion: string; try { - initializeEnvironment(getActionVersion()); + actionState.env.initialise(getActionVersion()); const apiDetails = { auth: getRequiredInput("token"), externalRepoAuth: getOptionalInput("external-repository-token"), - url: getRequiredEnvParam("GITHUB_SERVER_URL"), - apiURL: getRequiredEnvParam("GITHUB_API_URL"), + ...github.getCurrentInstance(actionState.env), }; const gitHubVersion = await getGitHubVersion(); @@ -137,7 +135,9 @@ async function run( ); const repositoryProperties = repositoryPropertiesResult.orElse({}); - const actionStateWithFeatures = { ...actionState, features }; + const actionStateWithFeatures = extendActionState(actionState, { + features, + }); const statusReportBase = await createStatusReportBase( ActionName.SetupCodeQL, @@ -171,6 +171,12 @@ async function run( gitHubVersion.type, codeQLDefaultVersionInfo, rawLanguages, + // CodeQL resolves the dependencies of queries that aren't in compiled packs from the bundle, + // so the queries that the workflow runs with this CLI may need library packs for languages + // other than those in the `languages` input. That input therefore only informs the choice of + // CLI version. + "the 'setup-codeql' Action can't tell whether the queries that the workflow runs will need " + + "library packs for other languages", analysisKinds.length === 1 && analysisKinds[0] === AnalysisKind.CodeScanning, features, @@ -184,7 +190,7 @@ async function run( core.setOutput("codeql-path", codeql.getPath()); core.setOutput("codeql-version", (await codeql.getVersion()).version); - core.exportVariable(EnvVar.SETUP_CODEQL_ACTION_HAS_RUN, "true"); + actionState.env.export(EnvVar.SETUP_CODEQL_ACTION_HAS_RUN, "true"); } catch (unwrappedError) { const error = wrapError(unwrappedError); core.setFailed(error.message); diff --git a/src/setup-codeql.test.ts b/src/setup-codeql.test.ts index 219e39984c..a244501c38 100644 --- a/src/setup-codeql.test.ts +++ b/src/setup-codeql.test.ts @@ -1,4 +1,7 @@ +import * as fs from "fs"; +import * as os from "os"; import * as path from "path"; +import { performance } from "perf_hooks"; import * as github from "@actions/github"; import * as toolcache from "@actions/tool-cache"; @@ -7,39 +10,90 @@ import * as sinon from "sinon"; import * as actionsUtil from "./actions-util"; import * as api from "./api-client"; -import { EnvVar } from "./environment"; +import * as diagnostics from "./diagnostics"; +import { + ActionsEnvVars, + Env, + EnvVar, + getEnv, + ReadOnlyEnv, +} from "./environment"; import { Feature } from "./feature-flags"; -import { getRunnerLogger } from "./logging"; +import { BuiltInLanguage } from "./languages"; import { getCacheRestoreKeyPrefix } from "./overlay/caching"; +import { MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION } from "./per-language-bundles"; import * as setupCodeql from "./setup-codeql"; import * as tar from "./tar"; import { LINKED_CLI_VERSION, LoggedMessage, + RecordingLogger, SAMPLE_DEFAULT_CLI_VERSION, SAMPLE_DOTCOM_API_DETAILS, checkExpectedLogMessages, + checkUnexpectedLogMessages, createFeatures, createTestConfig, getRecordingLogger, + getTestEnv, + initAllState, makeMacro, mockBundleDownloadApi, setupActionsVars, setupTests, } from "./testing-utils"; -import { - getErrorMessage, - GitHubVariant, - initializeEnvironment, - withTmpDir, -} from "./util"; +import * as toolsDownload from "./tools-download"; +import { getErrorMessage, GitHubVariant, HTTPError, withTmpDir } from "./util"; setupTests(test); test.beforeEach(() => { - initializeEnvironment("1.2.3"); + getEnv().initialise("1.2.3"); }); +function stubDownloadAndExtract() { + return sinon + .stub(toolsDownload, "downloadAndExtract") + .callsFake(async (_url, _compressionMethod, dest) => { + fs.mkdirSync(dest, { recursive: true }); + return { downloadDurationMs: 200, totalDurationMs: 300 }; + }); +} + +/** Models a hosted Linux runner with zstd and the latest nightly release. */ +function stubHostedNightly(tagName: string) { + sinon.stub(process, "platform").value("linux"); + sinon.stub(process, "arch").value("x64"); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + sinon.stub(tar, "isZstdAvailable").resolves({ + available: true, + foundZstdBinary: true, + }); + const client = github.getOctokit("123", { + request: { + fetch: async () => { + throw new Error("Unexpected API request in nightly bundle test"); + }, + }, + }); + const listReleases = sinon + .stub(client.rest.repos, "listReleases") + .rejects(new Error("Unexpected release request in nightly bundle test")); + listReleases + .withArgs({ + owner: "dsp-testing", + repo: "codeql-cli-nightlies", + per_page: 1, + page: 1, + prerelease: true, + }) + .resolves({ + data: [{ tag_name: tagName }], + } as Awaited>); + sinon.stub(api, "getApiClient").value(() => client); + return listReleases; +} + test.serial("parse codeql bundle url version", (t) => { t.deepEqual( setupCodeql.getCodeQLURLVersion( @@ -63,7 +117,7 @@ test.serial("convert to semver", (t) => { try { const parsedVersion = setupCodeql.convertToSemVer( version, - getRunnerLogger(true), + new RecordingLogger(), ); t.deepEqual(parsedVersion, expectedVersion); } catch (e) { @@ -72,24 +126,6 @@ test.serial("convert to semver", (t) => { } }); -test.serial("getCodeQLActionRepository", (t) => { - const logger = getRunnerLogger(true); - - initializeEnvironment("1.2.3"); - - // isRunningLocalAction() === true - delete process.env["GITHUB_ACTION_REPOSITORY"]; - process.env["RUNNER_TEMP"] = path.dirname(__dirname); - const repoLocalRunner = setupCodeql.getCodeQLActionRepository(logger); - t.deepEqual(repoLocalRunner, "github/codeql-action"); - - // isRunningLocalAction() === false - sinon.stub(actionsUtil, "isRunningLocalAction").returns(false); - process.env["GITHUB_ACTION_REPOSITORY"] = "xxx/yyy"; - const repoEnv = setupCodeql.getCodeQLActionRepository(logger); - t.deepEqual(repoEnv, "xxx/yyy"); -}); - test.serial( "getCodeQLSource sets CLI version for a semver tagged bundle", async (t) => { @@ -98,21 +134,28 @@ test.serial( await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); const tagName = "codeql-bundle-v1.2.3"; - mockBundleDownloadApi({ tagName }); + const url = mockBundleDownloadApi({ tagName }); const source = await setupCodeql.getCodeQLSource( - `https://github.com/github/codeql-action/releases/download/${tagName}/codeql-bundle-linux64.tar.gz`, + url, SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion SAMPLE_DOTCOM_API_DETAILS, GitHubVariant.DOTCOM, false, features, - getRunnerLogger(true), + new RecordingLogger(), ); - t.is(source.sourceType, "download"); - t.is(source["cliVersion"], "1.2.3"); + t.deepEqual(source, { + bundle: { kind: "combined", url }, + bundleVersion: "v1.2.3", + cliVersion: "1.2.3", + compressionMethod: "gzip", + sourceType: "download", + toolsVersion: "1.2.3", + } satisfies setupCodeql.CodeQLDownloadSource); }); }, ); @@ -120,24 +163,42 @@ test.serial( const LINKED_BUNDLE_TEST_CASES = [ { platform: "linux", + arch: "x64", tarSupportsZstd: true, expectedBundleName: "codeql-bundle-linux64.tar.zst", expectedCompressionMethod: "zstd", }, + { + platform: "linux", + arch: "arm64", + tarSupportsZstd: true, + expectedBundleName: "codeql-bundle-linux-arm64.tar.zst", + expectedCompressionMethod: "zstd", + }, + { + platform: "darwin", + arch: "arm64", + tarSupportsZstd: true, + expectedBundleName: "codeql-bundle-osx64.tar.zst", + expectedCompressionMethod: "zstd", + }, { platform: "darwin", + arch: "x64", tarSupportsZstd: true, expectedBundleName: "codeql-bundle-osx64.tar.zst", expectedCompressionMethod: "zstd", }, { platform: "win32", + arch: "x64", tarSupportsZstd: true, expectedBundleName: "codeql-bundle-win64.tar.gz", expectedCompressionMethod: "gzip", }, { platform: "linux", + arch: "x64", tarSupportsZstd: false, expectedBundleName: "codeql-bundle-linux64.tar.gz", expectedCompressionMethod: "gzip", @@ -146,15 +207,17 @@ const LINKED_BUNDLE_TEST_CASES = [ for (const { platform, + arch, tarSupportsZstd, expectedBundleName, expectedCompressionMethod, } of LINKED_BUNDLE_TEST_CASES) { test.serial( - `getCodeQLSource selects ${expectedBundleName} for linked tools`, + `getCodeQLSource selects ${expectedBundleName} for linked tools on ${platform}/${arch}`, async (t) => { const features = createFeatures([]); sinon.stub(process, "platform").value(platform); + sinon.stub(process, "arch").value(arch); await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); @@ -162,19 +225,21 @@ for (const { "linked", SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion SAMPLE_DOTCOM_API_DETAILS, GitHubVariant.DOTCOM, tarSupportsZstd, features, - getRunnerLogger(true), + new RecordingLogger(), ); t.is(source.toolsVersion, LINKED_CLI_VERSION.cliVersion); t.is(source.sourceType, "download"); if (source.sourceType === "download") { t.is(source.compressionMethod, expectedCompressionMethod); - t.true(source.codeqlURL.endsWith(`/${expectedBundleName}`)); + t.is(source.bundle.kind, "combined"); + t.true(source.bundle.url.endsWith(`/${expectedBundleName}`)); } }); }, @@ -194,6 +259,7 @@ test.serial( "latest", SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion SAMPLE_DOTCOM_API_DETAILS, GitHubVariant.DOTCOM, @@ -228,25 +294,18 @@ test.serial( const logger = getRecordingLogger(loggedMessages); const features = createFeatures([]); - // Stub the downloadCodeQL function to prevent downloading artefacts - // during testing from being called. - sinon.stub(setupCodeql, "downloadCodeQL").resolves({ - codeqlFolder: "codeql", - statusReport: { - downloadDurationMs: 200, - }, - toolsVersion: LINKED_CLI_VERSION.cliVersion, - }); + const extractStub = stubDownloadAndExtract(); await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); const result = await setupCodeql.setupCodeQLBundle( "linked", SAMPLE_DOTCOM_API_DETAILS, - "tmp/codeql_action_test/", + tmpDir, GitHubVariant.DOTCOM, SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion features, logger, @@ -255,6 +314,19 @@ test.serial( // Basic sanity check that the version we got back is indeed // the linked (default) CLI version. t.is(result.toolsVersion, LINKED_CLI_VERSION.cliVersion); + t.true(extractStub.calledOnce); + t.is( + result.codeqlFolder, + toolcache.find("CodeQL", LINKED_CLI_VERSION.cliVersion), + ); + t.deepEqual(result.toolsDownloadStatusReport, { + downloadDurationMs: 200, + totalDurationMs: 300, + }); + checkUnexpectedLogMessages(t, loggedMessages, [ + "Not caching the CodeQL tools", + "Could not cache CodeQL tools", + ]); // Ensure message logging CodeQL CLI version was present in user logs. const expected_message: string = `Using CodeQL CLI version ${LINKED_CLI_VERSION.cliVersion}`; @@ -280,25 +352,18 @@ test.serial( "https://github.com/github/codeql-action/releases/download/codeql-bundle-v2.16.0/codeql-bundle-linux64.tar.gz"; const expectedVersion = "2.16.0"; - // Stub the downloadCodeQL function to prevent downloading artefacts - // during testing from being called. - sinon.stub(setupCodeql, "downloadCodeQL").resolves({ - codeqlFolder: "codeql", - statusReport: { - downloadDurationMs: 200, - }, - toolsVersion: expectedVersion, - }); + const extractStub = stubDownloadAndExtract(); await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); const result = await setupCodeql.setupCodeQLBundle( bundleUrl, SAMPLE_DOTCOM_API_DETAILS, - "tmp/codeql_action_test/", + tmpDir, GitHubVariant.DOTCOM, SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion features, logger, @@ -307,6 +372,13 @@ test.serial( // Basic sanity check that the version we got back is indeed the version that the // bundle contains.. t.is(result.toolsVersion, expectedVersion); + t.true(extractStub.calledOnce); + t.is(extractStub.firstCall.args[0], bundleUrl); + t.is(result.codeqlFolder, toolcache.find("CodeQL", expectedVersion)); + t.deepEqual(result.toolsDownloadStatusReport, { + downloadDurationMs: 200, + totalDurationMs: 300, + }); // Ensure message logging CodeQL CLI version was present in user logs. const expected_message: string = `Using CodeQL CLI version 2.16.0 sourced from ${bundleUrl} .`; @@ -322,29 +394,17 @@ test.serial( ); test.serial( - "getCodeQLSource correctly returns nightly CLI version when tools == nightly", + "getCodeQLSource and setupCodeQLBundle preserve the nightly version when tools == nightly", async (t) => { const loggedMessages: LoggedMessage[] = []; const logger = getRecordingLogger(loggedMessages); const features = createFeatures([]); + const extractStub = stubDownloadAndExtract(); const expectedDate = "30260213"; const expectedTag = `codeql-bundle-${expectedDate}`; - // Ensure that we consistently select "zstd" for the test. - sinon.stub(process, "platform").value("linux"); - sinon.stub(tar, "isZstdAvailable").resolves({ - available: true, - foundZstdBinary: true, - }); - - const client = github.getOctokit("123"); - const listReleases = sinon.stub(client.rest.repos, "listReleases"); - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - listReleases.resolves({ - data: [{ tag_name: expectedTag }], - } as any); - sinon.stub(api, "getApiClient").value(() => client); + stubHostedNightly(expectedTag); await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); @@ -352,6 +412,7 @@ test.serial( "nightly", SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion SAMPLE_DOTCOM_API_DETAILS, GitHubVariant.DOTCOM, @@ -362,16 +423,37 @@ test.serial( // Check that the `CodeQLToolsSource` object matches our expectations. const expectedVersion = `0.0.0-${expectedDate}`; - const expectedURL = `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/${expectedTag}/${setupCodeql.getCodeQLBundleName("zstd")}`; + const expectedURL = `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/${expectedTag}/codeql-bundle-linux64.tar.zst`; t.deepEqual(source, { + bundle: { kind: "combined", url: expectedURL }, bundleVersion: expectedDate, cliVersion: undefined, - codeqlURL: expectedURL, compressionMethod: "zstd", sourceType: "download", toolsVersion: expectedVersion, } satisfies setupCodeql.CodeQLToolsSource); + const result = await setupCodeql.setupCodeQLBundle( + "nightly", + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + undefined, // rawLanguages + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + features, + logger, + ); + + t.true(extractStub.calledOnce); + t.is(extractStub.firstCall.args[0], expectedURL); + t.is(result.toolsVersion, source.toolsVersion); + t.is(result.toolsSource, setupCodeql.ToolsSource.Download); + t.is(result.codeqlFolder, toolcache.find("CodeQL", expectedVersion)); + t.true(fs.existsSync(`${result.codeqlFolder}.complete`)); + t.deepEqual(toolcache.findAllVersions("CodeQL"), [expectedVersion]); + // Afterwards, ensure that we see the expected messages in the log. checkExpectedLogMessages(t, loggedMessages, [ "Using the latest CodeQL CLI nightly, as requested by 'tools: nightly'.", @@ -393,20 +475,7 @@ test.serial( const expectedDate = "30260213"; const expectedTag = `codeql-bundle-${expectedDate}`; - // Ensure that we consistently select "zstd" for the test. - sinon.stub(process, "platform").value("linux"); - sinon.stub(tar, "isZstdAvailable").resolves({ - available: true, - foundZstdBinary: true, - }); - - const client = github.getOctokit("123"); - const listReleases = sinon.stub(client.rest.repos, "listReleases"); - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - listReleases.resolves({ - data: [{ tag_name: expectedTag }], - } as any); - sinon.stub(api, "getApiClient").value(() => client); + stubHostedNightly(expectedTag); await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir, { GITHUB_EVENT_NAME: "dynamic" }); @@ -415,6 +484,7 @@ test.serial( undefined, SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion SAMPLE_DOTCOM_API_DETAILS, GitHubVariant.DOTCOM, @@ -425,11 +495,11 @@ test.serial( // Check that the `CodeQLToolsSource` object matches our expectations. const expectedVersion = `0.0.0-${expectedDate}`; - const expectedURL = `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/${expectedTag}/${setupCodeql.getCodeQLBundleName("zstd")}`; + const expectedURL = `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/${expectedTag}/codeql-bundle-linux64.tar.zst`; t.deepEqual(source, { + bundle: { kind: "combined", url: expectedURL }, bundleVersion: expectedDate, cliVersion: undefined, - codeqlURL: expectedURL, compressionMethod: "zstd", sourceType: "download", toolsVersion: expectedVersion, @@ -446,6 +516,333 @@ test.serial( }, ); +for (const bundlePath of [ + "codeql-bundle.tar.gz", + "codeql-bundle.tar.zst", + "codeql-bundle-/codeql-bundle.tar.gz", + "codeql-bundle-linux64.tar.zst", + "codeql-bundle-ruby-linux64.tar.zst", +]) { + test.serial( + `setupCodeQLBundle reports an unknown version for ${bundlePath}`, + async (t) => { + const extractStub = stubDownloadAndExtract(); + const downloadSpy = sinon.spy(setupCodeql, "downloadCodeQL"); + const url = `https://example.com/${bundlePath}`; + const messages: LoggedMessage[] = []; + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const result = await setupCodeql.setupCodeQLBundle( + url, + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + undefined, // rawLanguages + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + createFeatures([]), + getRecordingLogger(messages), + ); + + t.true(extractStub.calledOnce); + t.is(extractStub.firstCall.args[0], url); + t.is(downloadSpy.firstCall.args[0].bundleVersion, undefined); + t.is(downloadSpy.firstCall.args[0].toolsVersion, "unknown"); + t.is(result.toolsVersion, "unknown"); + t.is(result.toolsSource, setupCodeql.ToolsSource.Download); + t.is( + result.toolsDownloadStatusReport?.perLanguage?.tools_bundle_language, + bundlePath === "codeql-bundle-ruby-linux64.tar.zst" + ? BuiltInLanguage.ruby + : undefined, + ); + t.is(path.dirname(result.codeqlFolder), tmpDir); + t.true(fs.existsSync(result.codeqlFolder)); + t.false(fs.existsSync(`${result.codeqlFolder}.complete`)); + t.deepEqual(toolcache.findAllVersions("CodeQL"), []); + checkExpectedLogMessages(t, messages, [ + `Using CodeQL CLI sourced from ${url}`, + bundlePath === "codeql-bundle-ruby-linux64.tar.zst" + ? "Not caching the CodeQL tools because they came from a bundle that contains only a single language." + : `Could not cache CodeQL tools because we could not determine the bundle version from the URL ${url}.`, + ]); + }); + }, + ); +} + +test.serial( + "setupCodeQLBundle preserves local installation without cleaning the toolcache", + async (t) => { + const cleanupSpy = sinon.spy(toolsDownload, "deleteToolcacheBundles"); + const downloadSpy = sinon.spy(setupCodeql, "downloadCodeQL"); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + const cachedDirectory = createToolcacheEntry( + tmpDir, + "CodeQL", + CLEANUP_STALE_VERSION, + ); + const result = await setupCodeql.setupCodeQLBundle( + path.join(__dirname, "../src/testdata/codeql-bundle.tar.gz"), + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + undefined, // rawLanguages + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + createFeatures([]), + new RecordingLogger(), + ); + + t.is(result.toolsVersion, "local"); + t.is(result.toolsSource, setupCodeql.ToolsSource.Local); + t.is(result.toolsDownloadStatusReport, undefined); + t.is(path.dirname(result.codeqlFolder), tmpDir); + t.true(fs.existsSync(result.codeqlFolder)); + t.false(fs.existsSync(`${result.codeqlFolder}.complete`)); + t.true(fs.existsSync(cachedDirectory)); + t.true(cleanupSpy.notCalled); + t.true(downloadSpy.notCalled); + t.is(process.env[EnvVar.HAS_SET_UP_CODEQL], "true"); + }); + }, +); + +for (const toolsInput of ["nightly", "nightly-latest"]) { + test.serial( + `getCodeQLSource selects the latest per-language nightly for tools == ${toolsInput}`, + async (t) => { + const expectedTag = "codeql-bundle-30260213"; + const baseURL = `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/${expectedTag}`; + const latestNightlyRequest = stubHostedNightly(expectedTag); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const source = await setupCodeql.getCodeQLSource( + toolsInput, + SAMPLE_DEFAULT_CLI_VERSION, + ["java"], + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + true, // tarSupportsZstd + createFeatures([]), + new RecordingLogger(), + ); + + t.deepEqual(source, { + sourceType: "download", + bundle: { + kind: "per-language", + language: BuiltInLanguage.java, + url: `${baseURL}/codeql-bundle-java-linux64.tar.zst`, + combinedBundleURL: `${baseURL}/codeql-bundle-linux64.tar.zst`, + }, + bundleVersion: "30260213", + cliVersion: undefined, + compressionMethod: "zstd", + toolsVersion: "0.0.0-30260213", + } satisfies setupCodeql.CodeQLDownloadSource); + t.true(latestNightlyRequest.calledOnce); + }); + }, + ); +} + +test.serial( + "getCodeQLSource downloads a combined nightly bundle when per-language selection is ineligible", + async (t) => { + const expectedTag = "codeql-bundle-30260213"; + stubHostedNightly(expectedTag); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + for (const { languages, otherLanguagePacksReason } of [ + // More than one language requires a combined bundle. + { + languages: ["java", "python"], + otherLanguagePacksReason: undefined, + }, + // The configured queries may need library packs for other languages. + { + languages: ["java"], + otherLanguagePacksReason: "an example reason", + }, + ]) { + const source = await setupCodeql.getCodeQLSource( + "nightly", + SAMPLE_DEFAULT_CLI_VERSION, + languages, + otherLanguagePacksReason, + false, // useOverlayAwareDefaultCliVersion + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + true, // tarSupportsZstd + createFeatures([]), + new RecordingLogger(), + ); + + t.is(source.sourceType, "download"); + if (source.sourceType === "download") { + t.deepEqual(source.bundle, { + kind: "combined", + url: `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/${expectedTag}/codeql-bundle-linux64.tar.zst`, + }); + } + } + }); + }, +); + +test.serial( + "getCodeQLSource uses the latest per-language bundle for a forced nightly", + async (t) => { + const expectedTag = "codeql-bundle-30260213"; + const baseURL = `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/${expectedTag}`; + const latestNightlyRequest = stubHostedNightly(expectedTag); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir, { GITHUB_EVENT_NAME: "dynamic" }); + const source = await setupCodeql.getCodeQLSource( + undefined, // toolsInput: the nightly is selected by ForceNightly + SAMPLE_DEFAULT_CLI_VERSION, + ["java"], + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + true, // tarSupportsZstd + createFeatures([Feature.ForceNightly]), + new RecordingLogger(), + ); + + t.is(source.sourceType, "download"); + t.true(latestNightlyRequest.calledOnce); + if (source.sourceType === "download") { + t.deepEqual(source.bundle, { + kind: "per-language", + language: BuiltInLanguage.java, + url: `${baseURL}/codeql-bundle-java-linux64.tar.zst`, + combinedBundleURL: `${baseURL}/codeql-bundle-linux64.tar.zst`, + }); + } + }); + }, +); + +for (const date of ["20200101", "30260213"]) { + for (const bundle of ["combined", "per-language"] as const) { + test.serial( + `getCodeQLSource preserves an explicit ${bundle} nightly URL for ${date}${ + bundle === "per-language" ? " on GHES" : "" + }`, + async (t) => { + const latestNightlyRequest = stubHostedNightly( + "codeql-bundle-30260213", + ); + const asset = + bundle === "combined" + ? "codeql-bundle-linux64.tar.zst" + : "codeql-bundle-java-linux64.tar.zst"; + const url = `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/codeql-bundle-${date}/${asset}`; + const features = createFeatures([]); + const variant = + bundle === "per-language" ? GitHubVariant.GHES : GitHubVariant.DOTCOM; + const logger = getRecordingLogger([], { logToConsole: false }); + const error = new HTTPError("Not Found", 404); + const extractStub = sinon + .stub(toolsDownload, "downloadAndExtract") + .rejects(error); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const source = await setupCodeql.getCodeQLSource( + url, + SAMPLE_DEFAULT_CLI_VERSION, + ["java"], + undefined, // otherLanguagePacksReason + false, + SAMPLE_DOTCOM_API_DETAILS, + variant, + true, + features, + logger, + ); + t.deepEqual(source, { + sourceType: "download", + bundle: + bundle === "combined" + ? { kind: "combined", url } + : { kind: "per-language", url, language: BuiltInLanguage.java }, + bundleVersion: date, + cliVersion: undefined, + compressionMethod: "zstd", + toolsVersion: `0.0.0-${date}`, + } satisfies setupCodeql.CodeQLDownloadSource); + + await t.throwsAsync( + setupCodeql.setupCodeQLBundle( + url, + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + variant, + SAMPLE_DEFAULT_CLI_VERSION, + ["java"], + undefined, // otherLanguagePacksReason + false, + features, + logger, + ), + { is: error }, + ); + t.true(extractStub.calledOnce); + t.is(extractStub.firstCall.args[0], url); + t.true(latestNightlyRequest.notCalled); + }); + }, + ); + } +} + +test.serial( + "getCodeQLSource reports a missing release tag when a toolcache entry disappears", + async (t) => { + sinon + .stub(toolcache, "findAllVersions") + .returns([MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION]); + sinon.stub(toolcache, "find").returns(""); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir, { GITHUB_EVENT_NAME: "dynamic" }); + await t.throwsAsync( + setupCodeql.getCodeQLSource( + "toolcache", + SAMPLE_DEFAULT_CLI_VERSION, + ["java"], + undefined, // otherLanguagePacksReason + false, + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + true, + createFeatures([]), + new RecordingLogger(), + ), + { + message: + "Could not determine a release tag for the requested CodeQL bundle.", + }, + ); + }); + }, +); + test.serial( "getCodeQLSource correctly returns latest version from toolcache when tools == toolcache", async (t) => { @@ -471,6 +868,7 @@ test.serial( "toolcache", SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion SAMPLE_DOTCOM_API_DETAILS, GitHubVariant.DOTCOM, @@ -540,6 +938,7 @@ const toolcacheInputFallbackMacro = makeMacro({ "toolcache", SAMPLE_DEFAULT_CLI_VERSION, undefined, // rawLanguages + undefined, // otherLanguagePacksReason false, // useOverlayAwareDefaultCliVersion SAMPLE_DOTCOM_API_DETAILS, GitHubVariant.DOTCOM, @@ -605,7 +1004,7 @@ test.serial( t.is( setupCodeql.tryGetTagNameFromUrl( "https://github.com/org/codeql-bundle-testing/releases/download/codeql-bundle-v2.19.0/codeql-bundle-linux64.tar.zst", - getRunnerLogger(true), + new RecordingLogger(), ), "codeql-bundle-v2.19.0", ); @@ -617,7 +1016,7 @@ test.serial( (t) => { sinon.stub(toolcache, "findAllVersions").returns([]); t.is( - setupCodeql.getLatestToolcacheVersion(getRunnerLogger(true)), + setupCodeql.getLatestToolcacheVersion(new RecordingLogger()), undefined, ); }, @@ -629,7 +1028,7 @@ test.serial( const testVersions = ["2.3.1", "3.2.1", "1.2.3"]; sinon.stub(toolcache, "findAllVersions").returns(testVersions); - t.is(setupCodeql.getLatestToolcacheVersion(getRunnerLogger(true)), "3.2.1"); + t.is(setupCodeql.getLatestToolcacheVersion(new RecordingLogger()), "3.2.1"); }, ); @@ -655,7 +1054,7 @@ async function fakeOverlayBaseCacheKey( } test.serial( - "getCodeQLSource uses overlay-aware default version when requested for a PR", + "getCodeQLSource uses overlay-aware default version for a Code Scanning PR", async (t) => { await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); @@ -677,12 +1076,13 @@ test.serial( undefined, overlayMatchEnabledVersions, ["javascript"], + undefined, // otherLanguagePacksReason true, SAMPLE_DOTCOM_API_DETAILS, GitHubVariant.DOTCOM, false, - createFeatures([Feature.OverlayAnalysisMatchCodeqlVersion]), - getRunnerLogger(true), + createFeatures([]), + new RecordingLogger(), ); t.assert(listStub.calledOnce); @@ -693,7 +1093,95 @@ test.serial( ); test.serial( - "getCodeQLSource skips overlay-aware default version when not requested", + "getCodeQLSource skips the Actions cache when only one default version is enabled", + async (t) => { + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + process.env[EnvVar.CODE_SCANNING_REF] = "refs/heads/feature-branch"; + process.env[EnvVar.CODE_SCANNING_BASE_BRANCH] = "main"; + + sinon.stub(api, "getAutomationID").resolves("test/"); + const listStub = sinon.stub(api, "listActionsCaches").resolves([ + { + key: await fakeOverlayBaseCacheKey( + "javascript", + SAMPLE_DEFAULT_CLI_VERSION.enabledVersions[0].cliVersion, + "abc-1-1", + ), + }, + ]); + sinon + .stub(toolcache, "find") + .withArgs( + "CodeQL", + SAMPLE_DEFAULT_CLI_VERSION.enabledVersions[0].cliVersion, + ) + .returns("/path/to/codeql"); + + const source = await setupCodeql.getCodeQLSource( + undefined, + SAMPLE_DEFAULT_CLI_VERSION, + ["javascript"], + undefined, // otherLanguagePacksReason + true, + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + false, + createFeatures([]), + new RecordingLogger(), + ); + + t.assert(listStub.notCalled); + t.is(source.sourceType, "toolcache"); + t.is( + source.toolsVersion, + SAMPLE_DEFAULT_CLI_VERSION.enabledVersions[0].cliVersion, + ); + }); + }, +); + +test.serial( + "getCodeQLSource skips overlay-aware default version outside pull request analysis", + async (t) => { + sinon.stub(actionsUtil, "isAnalyzingPullRequest").returns(false); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + + sinon.stub(api, "getAutomationID").resolves("test/"); + const listStub = sinon.stub(api, "listActionsCaches").resolves([ + { + key: await fakeOverlayBaseCacheKey("javascript", "2.20.1", "abc-1-1"), + }, + ]); + sinon + .stub(toolcache, "find") + .withArgs("CodeQL", "2.20.2") + .returns("/path/to/codeql-2.20.2"); + + const source = await setupCodeql.getCodeQLSource( + undefined, + overlayMatchEnabledVersions, + ["javascript"], + undefined, // otherLanguagePacksReason + true, + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + false, + createFeatures([]), + new RecordingLogger(), + ); + + t.assert(listStub.notCalled); + t.is(source.sourceType, "toolcache"); + t.is(source.toolsVersion, "2.20.2"); + }); + }, +); + +test.serial( + "getCodeQLSource skips overlay-aware default version when not requested for Code Scanning", async (t) => { await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); @@ -715,12 +1203,13 @@ test.serial( undefined, overlayMatchEnabledVersions, ["javascript"], + undefined, // otherLanguagePacksReason false, SAMPLE_DOTCOM_API_DETAILS, GitHubVariant.DOTCOM, false, - createFeatures([Feature.OverlayAnalysisMatchCodeqlVersion]), - getRunnerLogger(true), + createFeatures([]), + new RecordingLogger(), ); t.assert(listStub.notCalled); @@ -730,13 +1219,476 @@ test.serial( }, ); +const PER_LANGUAGE_CLI_VERSION = { + enabledVersions: [ + { + cliVersion: MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION, + tagName: `codeql-bundle-v${MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION}`, + }, + ], +}; + test.serial( - "getEnabledVersionsWithOverlayBaseDatabases returns flag-enabled versions present in cache, sorted desc", + "getCodeQLSource downloads the per-language bundle for a single explicit language", async (t) => { - sinon.stub(api, "getAutomationID").resolves("test/"); - sinon.stub(api, "listActionsCaches").resolves([ - // Flag-enabled versions present in the cache, listed in non-descending - // order so the test exercises the sort. + sinon.stub(process, "platform").value("linux"); + sinon.stub(process, "arch").value("x64"); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const source = await setupCodeql.getCodeQLSource( + undefined, + PER_LANGUAGE_CLI_VERSION, + ["java-kotlin"], + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + true, // tarSupportsZstd + createFeatures([]), + new RecordingLogger(), + ); + + t.is(source.sourceType, "download"); + if (source.sourceType === "download") { + t.true( + source.bundle.url.endsWith("/codeql-bundle-java-linux64.tar.zst"), + `Unexpected URL ${source.bundle.url}`, + ); + t.is(source.bundle.kind, "per-language"); + if (source.bundle.kind === "per-language") { + t.is(source.bundle.language, BuiltInLanguage.java); + t.true( + source.bundle.combinedBundleURL?.endsWith( + "/codeql-bundle-linux64.tar.zst", + ), + ); + } + } + }); + }, +); + +test.serial( + "getCodeQLSource downloads the combined bundle when per-language selection is ineligible", + async (t) => { + sinon.stub(process, "platform").value("linux"); + sinon.stub(process, "arch").value("x64"); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + for (const { otherLanguagePacksReason, variant } of [ + // Automatic per-language selection is limited to GitHub.com. + { + otherLanguagePacksReason: undefined, + variant: GitHubVariant.GHES, + }, + // The configured queries may need library packs for other languages. + { + otherLanguagePacksReason: "an example reason", + variant: GitHubVariant.DOTCOM, + }, + ]) { + const source = await setupCodeql.getCodeQLSource( + undefined, + PER_LANGUAGE_CLI_VERSION, + ["java"], + otherLanguagePacksReason, + false, // useOverlayAwareDefaultCliVersion + SAMPLE_DOTCOM_API_DETAILS, + variant, + true, // tarSupportsZstd + createFeatures([]), + new RecordingLogger(), + ); + + t.is(source.sourceType, "download"); + if (source.sourceType === "download") { + t.true(source.bundle.url.endsWith("/codeql-bundle-linux64.tar.zst")); + t.is(source.bundle.kind, "combined"); + } + } + }); + }, +); + +for (const fallback of [false, true]) { + test.serial( + `setupCodeQLBundle retains the selected release identity for an opaque asset URL${fallback ? " with fallback" : ""}`, + async (t) => { + sinon.stub(process, "platform").value("linux"); + sinon.stub(process, "arch").value("x64"); + sinon.stub(actionsUtil, "isRunningLocalAction").returns(false); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + sinon.stub(tar, "isZstdAvailable").resolves({ + available: true, + foundZstdBinary: true, + }); + const tag = PER_LANGUAGE_CLI_VERSION.enabledVersions[0].tagName; + const assetURL = + "https://api.github.com/repos/codeql-testing/action-fork/releases/assets/123"; + const combinedURL = `${assetURL}4`; + const fetchRelease = sinon + .stub, ReturnType>() + .callsFake( + async () => + new Response( + JSON.stringify({ + assets: [ + { name: "codeql-bundle-java-linux64.tar.zst", url: assetURL }, + { + name: "codeql-bundle-linux64.tar.zst", + url: combinedURL, + }, + ], + }), + { headers: { "content-type": "application/json" } }, + ), + ); + const client = github.getOctokit("123", { + request: { fetch: fetchRelease }, + }); + sinon.stub(api, "getApiClient").value(() => client); + const authorizationSpy = sinon.spy(api, "getAuthorizationHeaderFor"); + const extractStub = stubDownloadAndExtract(); + if (fallback) { + extractStub.onFirstCall().rejects(new HTTPError("Not Found", 404)); + } + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir, { + GITHUB_ACTION_REPOSITORY: "codeql-testing/action-fork", + }); + const result = await setupCodeql.setupCodeQLBundle( + undefined, + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + PER_LANGUAGE_CLI_VERSION, + ["java"], + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + createFeatures([]), + new RecordingLogger(), + ); + + t.true(fetchRelease.calledTwice); + t.is( + fetchRelease.firstCall.args[0], + `https://api.github.com/repos/codeql-testing/action-fork/releases/tags/${tag}`, + ); + t.is(extractStub.callCount, fallback ? 2 : 1); + t.is(extractStub.firstCall.args[0], assetURL); + t.is(extractStub.lastCall.args[0], fallback ? combinedURL : assetURL); + t.is(authorizationSpy.callCount, extractStub.callCount); + t.is(authorizationSpy.firstCall.args[2], assetURL); + t.is( + authorizationSpy.lastCall.args[2], + fallback ? combinedURL : assetURL, + ); + t.is(extractStub.lastCall.args[3], "token token"); + t.is(result.toolsVersion, MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION); + t.is( + result.toolsDownloadStatusReport?.perLanguage?.tools_bundle_language, + fallback ? undefined : BuiltInLanguage.java, + ); + t.is( + result.toolsDownloadStatusReport?.perLanguage + ?.tools_per_language_bundle_fallback, + fallback ? true : undefined, + ); + if (fallback) { + t.is( + result.codeqlFolder, + toolcache.find("CodeQL", MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION), + ); + t.true(fs.existsSync(`${result.codeqlFolder}.complete`)); + } else { + t.is(path.dirname(result.codeqlFolder), tmpDir); + t.deepEqual(toolcache.findAllVersions("CodeQL"), []); + t.false(fs.existsSync(`${result.codeqlFolder}.complete`)); + } + }); + }, + ); +} + +for (const bundle of ["per-language", "combined", "fallback"] as const) { + test.serial( + `setupCodeQLBundle preserves the nightly version for a ${bundle} download`, + async (t) => { + const expectedDate = "30260213"; + const expectedTag = `codeql-bundle-${expectedDate}`; + const expectedVersion = `0.0.0-${expectedDate}`; + const baseURL = `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/${expectedTag}`; + const combinedURL = `${baseURL}/codeql-bundle-linux64.tar.zst`; + const perLanguageURL = `${baseURL}/codeql-bundle-javascript-linux64.tar.zst`; + const loggedMessages: LoggedMessage[] = []; + const logger = getRecordingLogger(loggedMessages); + + stubHostedNightly(expectedTag); + delete process.env[EnvVar.HAS_SET_UP_CODEQL]; + + const downloadSpy = sinon.spy(setupCodeql, "downloadCodeQL"); + let elapsedMs = 1000; + sinon.stub(performance, "now").callsFake(() => elapsedMs); + const extractStub = sinon + .stub(toolsDownload, "downloadAndExtract") + .callsFake(async (_url, _compressionMethod, dest) => { + if (bundle === "fallback" && extractStub.callCount === 1) { + elapsedMs += 700.2; + throw new HTTPError("Not Found", 404); + } + elapsedMs += 300.2; + fs.mkdirSync(dest, { recursive: true }); + return { + downloadDurationMs: 200, + extractionDurationMs: 100, + totalDurationMs: 300, + }; + }); + const addDiagnostic = sinon.stub(diagnostics, "addNoLanguageDiagnostic"); + const features = createFeatures([]); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const result = await setupCodeql.setupCodeQLBundle( + "nightly", + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + bundle === "combined" ? ["javascript", "python"] : ["javascript"], + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + features, + logger, + ); + + const source = downloadSpy.firstCall.args[0]; + t.is(result.toolsVersion, expectedVersion); + t.is(result.toolsVersion, source.toolsVersion); + t.is( + source.bundle.kind, + bundle === "combined" ? "combined" : "per-language", + ); + t.is(result.codeqlFolder, extractStub.lastCall.args[2]); + t.is( + result.toolsDownloadStatusReport?.totalDurationMs, + bundle === "fallback" ? 1000 : 300, + ); + t.is(result.toolsDownloadStatusReport?.downloadDurationMs, 200); + t.is(result.toolsDownloadStatusReport?.extractionDurationMs, 100); + t.is( + (await downloadSpy.lastCall.returnValue).statusReport.perLanguage + ?.tools_bundle_language, + bundle === "per-language" ? BuiltInLanguage.javascript : undefined, + ); + t.is(extractStub.callCount, bundle === "fallback" ? 2 : 1); + t.is(downloadSpy.callCount, extractStub.callCount); + t.is( + extractStub.firstCall.args[0], + bundle === "combined" ? combinedURL : perLanguageURL, + ); + t.is( + extractStub.lastCall.args[0], + bundle === "per-language" ? perLanguageURL : combinedURL, + ); + t.is( + result.toolsDownloadStatusReport?.perLanguage?.tools_bundle_language, + bundle === "per-language" ? BuiltInLanguage.javascript : undefined, + ); + t.is( + result.toolsDownloadStatusReport?.perLanguage + ?.tools_per_language_bundle_fallback, + bundle === "fallback" ? true : undefined, + ); + t.is( + addDiagnostic + .getCalls() + .filter( + (call) => + call.args[1].source?.id === + "codeql-action/toolcache-bundle-cleanup", + ).length, + 1, + ); + if (bundle === "fallback") { + t.deepEqual(downloadSpy.secondCall.args[0], { + ...source, + bundle: { kind: "combined", url: combinedURL }, + }); + checkExpectedLogMessages(t, loggedMessages, [ + `No per-language CodeQL bundle for 'javascript' was found at ${perLanguageURL}`, + ]); + } + if (bundle === "per-language") { + t.is(path.dirname(result.codeqlFolder), tmpDir); + t.deepEqual(toolcache.findAllVersions("CodeQL"), []); + t.false(fs.existsSync(`${result.codeqlFolder}.complete`)); + } else { + t.is( + result.codeqlFolder, + toolsDownload.getToolcacheDirectory(expectedVersion), + ); + t.true(fs.existsSync(`${result.codeqlFolder}.complete`)); + + const cachedResult = await setupCodeql.setupCodeQLBundle( + "nightly", + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + ["javascript"], + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + features, + logger, + ); + t.is(cachedResult.toolsSource, setupCodeql.ToolsSource.Toolcache); + t.is(cachedResult.toolsVersion, expectedVersion); + t.is(cachedResult.codeqlFolder, result.codeqlFolder); + t.is(extractStub.callCount, bundle === "fallback" ? 2 : 1); + } + }); + }, + ); +} + +for (const asset of [ + "codeql-bundle-ruby-linux64.tar.zst", + "codeql-bundle-%72uby-linux64.tar.zst", +]) { + test.serial( + `setupCodeQLBundle keeps explicitly requested ${asset} out of the toolcache`, + async (t) => { + const extractStub = stubDownloadAndExtract(); + const messages: LoggedMessage[] = []; + const url = `https://github.com/github/codeql-action/releases/download/codeql-bundle-v9.9.9/${asset}`; + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "self-hosted"; + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const result = await setupCodeql.setupCodeQLBundle( + url, + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + undefined, // rawLanguages + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + createFeatures([]), + getRecordingLogger(messages), + ); + + t.true(extractStub.calledOnce); + t.is(extractStub.firstCall.args[0], url); + t.is(result.toolsVersion, "9.9.9"); + t.is( + result.toolsDownloadStatusReport?.perLanguage?.tools_bundle_language, + BuiltInLanguage.ruby, + ); + t.is(path.dirname(result.codeqlFolder), tmpDir); + t.deepEqual(toolcache.findAllVersions("CodeQL"), []); + t.false(fs.existsSync(`${result.codeqlFolder}.complete`)); + checkExpectedLogMessages(t, messages, [ + "Not caching the CodeQL tools because they came from a bundle that contains only a single language.", + ]); + checkUnexpectedLogMessages(t, messages, [ + "Could not cache CodeQL tools because we could not determine the bundle version", + ]); + }); + }, + ); +} + +for (const error of [ + new HTTPError("Internal Server Error", 500), + new Error("Connection reset"), +]) { + test.serial( + `setupCodeQLBundle does not fall back after ${error.message}`, + async (t) => { + sinon.stub(process, "platform").value("linux"); + sinon.stub(process, "arch").value("x64"); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + sinon.stub(tar, "isZstdAvailable").resolves({ + available: true, + foundZstdBinary: true, + }); + const extractStub = sinon + .stub(toolsDownload, "downloadAndExtract") + .rejects(error); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + await t.throwsAsync( + setupCodeql.setupCodeQLBundle( + undefined, + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + PER_LANGUAGE_CLI_VERSION, + ["java"], + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + createFeatures([]), + new RecordingLogger(), + ), + { is: error }, + ); + t.true(extractStub.calledOnce); + t.true( + extractStub.firstCall.args[0].endsWith( + "/codeql-bundle-java-linux64.tar.zst", + ), + ); + }); + }, + ); +} + +test.serial( + "setupCodeQLBundle does not substitute a bundle for an explicitly requested one that is missing", + async (t) => { + const error = new HTTPError("Not Found", 404); + const extractStub = sinon + .stub(toolsDownload, "downloadAndExtract") + .rejects(error); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + await t.throwsAsync( + setupCodeql.setupCodeQLBundle( + "https://github.com/github/codeql-action/releases/download/codeql-bundle-v9.9.9/codeql-bundle-ruby-linux64.tar.zst", + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + undefined, // rawLanguages + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + createFeatures([]), + new RecordingLogger(), + ), + { is: error }, + ); + + t.true(extractStub.calledOnce); + }); + }, +); + +test.serial( + "getEnabledVersionsWithOverlayBaseDatabases returns enabled versions present in cache, sorted desc", + async (t) => { + sinon.stub(api, "getAutomationID").resolves("test/"); + sinon.stub(api, "listActionsCaches").resolves([ + // Flag-enabled versions present in the cache, listed in non-descending + // order so the test exercises the sort. { key: await fakeOverlayBaseCacheKey("javascript", "2.20.0", "ghi-3-1"), }, @@ -749,21 +1701,24 @@ test.serial( }, ]); - const result = await setupCodeql.getEnabledVersionsWithOverlayBaseDatabases( - overlayMatchEnabledVersions, - ["javascript"], - createFeatures([Feature.OverlayAnalysisMatchCodeqlVersion]), - getRunnerLogger(true), - ); - t.deepEqual(result, [ - { cliVersion: "2.20.1", tagName: "codeql-bundle-v2.20.1" }, - { cliVersion: "2.20.0", tagName: "codeql-bundle-v2.20.0" }, - ]); + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const result = + await setupCodeql.getEnabledVersionsWithOverlayBaseDatabases( + overlayMatchEnabledVersions, + ["javascript"], + new RecordingLogger(), + ); + t.deepEqual(result, [ + { cliVersion: "2.20.1", tagName: "codeql-bundle-v2.20.1" }, + { cliVersion: "2.20.0", tagName: "codeql-bundle-v2.20.0" }, + ]); + }); }, ); test.serial( - "getEnabledVersionsWithOverlayBaseDatabases returns empty when no cached version is flag-enabled", + "getEnabledVersionsWithOverlayBaseDatabases returns empty when no cached version is enabled", async (t) => { sinon.stub(api, "getAutomationID").resolves("test/"); sinon.stub(api, "listActionsCaches").resolves([ @@ -775,8 +1730,7 @@ test.serial( const result = await setupCodeql.getEnabledVersionsWithOverlayBaseDatabases( overlayMatchEnabledVersions, ["javascript"], - createFeatures([Feature.OverlayAnalysisMatchCodeqlVersion]), - getRunnerLogger(true), + new RecordingLogger(), ); t.deepEqual(result, []); }, @@ -792,8 +1746,7 @@ const noLanguagesMacro = makeMacro({ const result = await setupCodeql.getEnabledVersionsWithOverlayBaseDatabases( overlayMatchEnabledVersions, rawLanguages, - createFeatures([Feature.OverlayAnalysisMatchCodeqlVersion]), - getRunnerLogger(true), + new RecordingLogger(), ); t.deepEqual(result, []); t.assert( @@ -817,8 +1770,7 @@ test.serial( const result = await setupCodeql.getEnabledVersionsWithOverlayBaseDatabases( overlayMatchEnabledVersions, ["javascript"], - createFeatures([Feature.OverlayAnalysisMatchCodeqlVersion]), - getRunnerLogger(true), + new RecordingLogger(), ); t.deepEqual(result, []); }, @@ -837,8 +1789,7 @@ test.serial( const result = await setupCodeql.getEnabledVersionsWithOverlayBaseDatabases( overlayMatchEnabledVersions, ["javascript"], - createFeatures([Feature.OverlayAnalysisMatchCodeqlVersion]), - getRunnerLogger(true), + new RecordingLogger(), ); t.deepEqual(result, [ { cliVersion: "2.20.2", tagName: "codeql-bundle-v2.20.2" }, @@ -846,74 +1797,665 @@ test.serial( }, ); -test.serial( - "getEnabledVersionsWithOverlayBaseDatabases does not list caches when both gates are off", - async (t) => { - const listStub = sinon.stub(api, "listActionsCaches").resolves([]); +/** The CLI version that the toolcache cleanup tests download. */ +const CLEANUP_CLI_VERSION = "2.21.0"; +/** The bundle version that the toolcache cleanup tests download. */ +const CLEANUP_BUNDLE_VERSION = "20240101"; +/** A version of the CodeQL tools that is already in the toolcache but that we are not going to use. */ +const CLEANUP_STALE_VERSION = "2.20.0"; + +/** Creates a directory in the toolcache that looks like a tool that `tool-cache` has cached. */ +function createToolcacheEntry( + toolcacheRoot: string, + tool: string, + version: string, +): string { + const versionDirectory = path.join(toolcacheRoot, tool, version); + const archDirectory = path.join(versionDirectory, os.arch()); + fs.mkdirSync(archDirectory, { recursive: true }); + fs.writeFileSync(path.join(archDirectory, "contents"), "x".repeat(1024)); + fs.writeFileSync(`${archDirectory}.complete`, ""); + return versionDirectory; +} - const result = await setupCodeql.getEnabledVersionsWithOverlayBaseDatabases( - overlayMatchEnabledVersions, - ["javascript"], - createFeatures([]), - getRunnerLogger(true), +/** + * Stubs out the download and the diagnostic sink, then downloads the CodeQL tools. + * + * @returns the extraction directory and the toolcache cleanup diagnostic, if emitted. + */ +async function runDownloadCodeQL( + toolcacheRoot: string, + bundleVersion: string | undefined, + { + env = getTestEnv({ + [ActionsEnvVars.RUNNER_ENVIRONMENT]: "github-hosted", + [ActionsEnvVars.RUNNER_TOOL_CACHE]: toolcacheRoot, + }), + }: { + env?: Env; + } = {}, +): Promise<{ + codeqlFolder: string; + cleanupDiagnostic: toolsDownload.ToolcacheCleanupResult | undefined; +}> { + stubDownloadAndExtract(); + const addDiagnostic = sinon.stub(diagnostics, "addNoLanguageDiagnostic"); + + const { codeqlFolder } = await setupCodeql.downloadCodeQLBundle( + initAllState({ + env, + }), + { + bundle: { + kind: "combined", + url: "https://example.com/codeql-bundle.tar.gz", + }, + compressionMethod: "gzip", + bundleVersion, + cliVersion: CLEANUP_CLI_VERSION, + sourceType: "download", + toolsVersion: CLEANUP_CLI_VERSION, + }, + SAMPLE_DOTCOM_API_DETAILS, + undefined, // tarVersion + toolcacheRoot, // tempDir + ); + + const diagnostic = addDiagnostic + .getCalls() + .map((call) => call.args[1]) + .find((d) => d.source?.id === "codeql-action/toolcache-bundle-cleanup"); + + return { + codeqlFolder, + cleanupDiagnostic: diagnostic?.attributes as + toolsDownload.ToolcacheCleanupResult | undefined, + }; +} + +/** + * Sets up a toolcache containing the version of the CodeQL tools that we are about to download, a + * different version of the CodeQL tools, and an unrelated tool, then downloads the CodeQL tools. + */ +async function testToolcacheCleanup( + t: ExecutionContext, + { + runnerEnvironment, + setUp, + }: { + runnerEnvironment: string | undefined; + setUp?: (env: Env) => void; + }, + check: (context: { + cleanupDiagnostic: toolsDownload.ToolcacheCleanupResult | undefined; + destinationDirectory: string; + staleDirectory: string; + }) => void, +) { + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const env = getTestEnv({ + [ActionsEnvVars.RUNNER_ENVIRONMENT]: runnerEnvironment, + [ActionsEnvVars.RUNNER_TOOL_CACHE]: tmpDir, + }); + setUp?.(env); + + // The extraction of the bundle would normally create this directory. + const destinationDirectory = createToolcacheEntry( + tmpDir, + "CodeQL", + CLEANUP_CLI_VERSION, ); - t.deepEqual(result, []); - t.assert( - listStub.notCalled, - "Should not list Actions caches when both gating feature flags are off.", + const staleDirectory = createToolcacheEntry( + tmpDir, + "CodeQL", + CLEANUP_STALE_VERSION, + ); + const otherToolDirectory = createToolcacheEntry(tmpDir, "Node", "20.0.0"); + + const { cleanupDiagnostic } = await runDownloadCodeQL( + tmpDir, + CLEANUP_BUNDLE_VERSION, + { env }, + ); + + t.true( + fs.existsSync(otherToolDirectory), + "Should never delete other tools from the toolcache.", + ); + + check({ cleanupDiagnostic, destinationDirectory, staleDirectory }); + }); +} + +test.serial( + "downloadCodeQLBundle does not clean up the toolcache when the runner is not GitHub-hosted", + async (t) => { + await testToolcacheCleanup( + t, + { + runnerEnvironment: "self-hosted", + }, + ({ cleanupDiagnostic, destinationDirectory, staleDirectory }) => { + t.true(fs.existsSync(staleDirectory)); + t.true(fs.existsSync(destinationDirectory)); + t.is(cleanupDiagnostic, undefined); + }, ); }, ); test.serial( - "getEnabledVersionsWithOverlayBaseDatabases dry-run returns empty but lists caches", + "downloadCodeQLBundle does not clean up the toolcache when the runner environment is unknown", async (t) => { - sinon.stub(api, "getAutomationID").resolves("test/"); - const listStub = sinon.stub(api, "listActionsCaches").resolves([ + // A runner that doesn't report its environment must be treated as not GitHub-hosted, since its + // toolcache may well outlive the job. + await testToolcacheCleanup( + t, { - key: await fakeOverlayBaseCacheKey("javascript", "2.20.1", "abc-1-1"), + runnerEnvironment: undefined, }, - ]); + ({ cleanupDiagnostic, destinationDirectory, staleDirectory }) => { + t.true(fs.existsSync(staleDirectory)); + t.true(fs.existsSync(destinationDirectory)); + t.is(cleanupDiagnostic, undefined); + }, + ); + }, +); - const result = await setupCodeql.getEnabledVersionsWithOverlayBaseDatabases( - overlayMatchEnabledVersions, - ["javascript"], - createFeatures([Feature.OverlayAnalysisMatchCodeqlVersionDryRun]), - getRunnerLogger(true), +test.serial( + "downloadCodeQLBundle deletes other CodeQL bundles from the toolcache on a GitHub-hosted runner", + async (t) => { + await testToolcacheCleanup( + t, + { + runnerEnvironment: "github-hosted", + }, + ({ cleanupDiagnostic, destinationDirectory, staleDirectory }) => { + t.false( + fs.existsSync(staleDirectory), + "Should delete the version directory, including the `tool-cache` marker file it contains.", + ); + t.false( + fs.existsSync(path.join(destinationDirectory, os.arch(), "contents")), + "Should also delete a partial entry for the version we are about to download, rather " + + "than extracting over it.", + ); + t.deepEqual(cleanupDiagnostic, { + deletedVersions: [CLEANUP_STALE_VERSION, CLEANUP_CLI_VERSION].sort(), + failed: false, + }); + }, ); + }, +); + +test.serial( + "downloadCodeQLBundle reports no deleted versions when the toolcache has no CodeQL bundles", + async (t) => { + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + + // A toolcache with other tools in it, but no CodeQL. + const otherToolDirectory = createToolcacheEntry(tmpDir, "Node", "20.0.0"); + + const { cleanupDiagnostic } = await runDownloadCodeQL( + tmpDir, + CLEANUP_BUNDLE_VERSION, + ); + + t.true(fs.existsSync(otherToolDirectory)); + t.deepEqual(cleanupDiagnostic, { deletedVersions: [], failed: false }); + }); + }, +); + +test.serial( + "downloadCodeQLBundle continues when deleting a CodeQL bundle from the toolcache fails", + async (t) => { + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + + createToolcacheEntry(tmpDir, "CodeQL", CLEANUP_CLI_VERSION); + const staleDirectory = createToolcacheEntry( + tmpDir, + "CodeQL", + CLEANUP_STALE_VERSION, + ); + + const rmStub = sinon + .stub(fs.promises, "rm") + .rejects(new Error("EACCES: permission denied")); + + const { cleanupDiagnostic } = await runDownloadCodeQL( + tmpDir, + CLEANUP_BUNDLE_VERSION, + ); + + // Restore before `withTmpDir` cleans up after itself. + rmStub.restore(); + + t.true(fs.existsSync(staleDirectory)); + t.deepEqual( + cleanupDiagnostic, + { deletedVersions: [], failed: true }, + "Should not report versions that we failed to delete.", + ); + }); + }, +); + +test.serial( + "deleteToolcacheBundles reports a failure when the toolcache location is unknown", + async (t) => { + const messages: LoggedMessage[] = []; + + const result = await toolsDownload.deleteToolcacheBundles({ + env: new ReadOnlyEnv({}), + logger: getRecordingLogger(messages), + }); + t.deepEqual( result, - [], - "Dry-run should return an empty list so the caller falls back.", - ); - t.assert( - listStub.calledOnce, - "Dry-run should still list Actions caches to populate the diagnostic.", + { deletedVersions: [], failed: true }, + "Should report a failure rather than throwing, so the download can continue.", ); + checkExpectedLogMessages(t, messages, [ + "Unable to determine toolcache directory: RUNNER_TOOL_CACHE environment variable must be set", + ]); }, ); test.serial( - "getEnabledVersionsWithOverlayBaseDatabases match flag wins over dry-run", + "deleteToolcacheBundles uses the supplied environment rather than process.env", async (t) => { - sinon.stub(api, "getAutomationID").resolves("test/"); - sinon.stub(api, "listActionsCaches").resolves([ + await withTmpDir(async (tmpDir) => { + const ambientRoot = path.join(tmpDir, "ambient"); + const injectedRoot = path.join(tmpDir, "injected"); + setupActionsVars(tmpDir, ambientRoot); + + const ambientVersion = createToolcacheEntry( + ambientRoot, + "CodeQL", + CLEANUP_STALE_VERSION, + ); + const injectedVersion = createToolcacheEntry( + injectedRoot, + "CodeQL", + CLEANUP_STALE_VERSION, + ); + const fileEntry = path.join(injectedRoot, "CodeQL", "not-a-directory"); + fs.writeFileSync(fileEntry, "keep"); + + const result = await toolsDownload.deleteToolcacheBundles({ + env: new ReadOnlyEnv({ + [ActionsEnvVars.RUNNER_TOOL_CACHE]: injectedRoot, + }), + logger: new RecordingLogger(), + }); + + t.deepEqual(result, { + deletedVersions: [CLEANUP_STALE_VERSION], + failed: false, + }); + t.false(fs.existsSync(injectedVersion)); + t.true(fs.existsSync(ambientVersion)); + t.is(fs.readFileSync(fileEntry, "utf8"), "keep"); + }); + }, +); + +test.serial( + "deleteToolcacheBundles reports a failure when the toolcache directory cannot be read", + async (t) => { + await withTmpDir(async (tmpDir) => { + const versionDirectory = createToolcacheEntry( + tmpDir, + "CodeQL", + CLEANUP_STALE_VERSION, + ); + const messages: LoggedMessage[] = []; + const readdir = sinon + .stub(fs.promises, "readdir") + .rejects(new Error("permission denied")); + + try { + const result = await toolsDownload.deleteToolcacheBundles({ + env: new ReadOnlyEnv({ + [ActionsEnvVars.RUNNER_TOOL_CACHE]: tmpDir, + }), + logger: getRecordingLogger(messages), + }); + + t.deepEqual(result, { deletedVersions: [], failed: true }); + t.true(fs.existsSync(versionDirectory)); + checkExpectedLogMessages(t, messages, [ + `Failed to clean up the CodeQL toolcache at '${path.join(tmpDir, "CodeQL")}': permission denied`, + ]); + } finally { + readdir.restore(); + } + }); + }, +); + +test.serial( + "downloadCodeQLBundle does not follow a symlinked CodeQL toolcache directory", + async (t) => { + await withTmpDir(async (tmpDir) => { + const toolcacheRoot = path.join(tmpDir, "toolcache"); + setupActionsVars(tmpDir, toolcacheRoot); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + + // Somewhere the toolcache cleanup must never reach. + const outsideDirectory = path.join(tmpDir, "outside"); + createToolcacheEntry(outsideDirectory, "CodeQL", CLEANUP_STALE_VERSION); + createToolcacheEntry(outsideDirectory, "CodeQL", CLEANUP_CLI_VERSION); + + fs.mkdirSync(toolcacheRoot, { recursive: true }); + fs.symlinkSync( + path.join(outsideDirectory, "CodeQL"), + path.join(toolcacheRoot, "CodeQL"), + ); + + const { cleanupDiagnostic } = await runDownloadCodeQL( + toolcacheRoot, + CLEANUP_BUNDLE_VERSION, + ); + + t.true( + fs.existsSync( + path.join(outsideDirectory, "CodeQL", CLEANUP_STALE_VERSION), + ), + "Should not delete anything through a symlinked CodeQL directory.", + ); + t.deepEqual(cleanupDiagnostic, { deletedVersions: [], failed: true }); + }); + }, +); + +test.serial( + "downloadCodeQLBundle does not clean up the toolcache once a step has already set up CodeQL", + async (t) => { + // `.github/workflows/codeql.yml` sets up CodeQL twice and then runs both returned paths. If the + // second setup downloads, it must not delete the bundle the first one handed out. + await testToolcacheCleanup( + t, { - key: await fakeOverlayBaseCacheKey("javascript", "2.20.1", "abc-1-1"), + runnerEnvironment: "github-hosted", + setUp: (env) => { + env.set(EnvVar.HAS_SET_UP_CODEQL, "true"); + }, + }, + ({ cleanupDiagnostic, destinationDirectory, staleDirectory }) => { + t.true(fs.existsSync(staleDirectory)); + t.true(fs.existsSync(destinationDirectory)); + t.is(cleanupDiagnostic, undefined); }, - ]); - - const result = await setupCodeql.getEnabledVersionsWithOverlayBaseDatabases( - overlayMatchEnabledVersions, - ["javascript"], - createFeatures([ - Feature.OverlayAnalysisMatchCodeqlVersion, - Feature.OverlayAnalysisMatchCodeqlVersionDryRun, - ]), - getRunnerLogger(true), ); - t.deepEqual(result, [ - { cliVersion: "2.20.1", tagName: "codeql-bundle-v2.20.1" }, - ]); + }, +); + +test.serial( + "downloadCodeQLBundle checks the supplied environment before cleaning the toolcache", + async (t) => { + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + delete process.env[EnvVar.HAS_SET_UP_CODEQL]; + + const staleDirectory = createToolcacheEntry( + tmpDir, + "CodeQL", + CLEANUP_STALE_VERSION, + ); + const { codeqlFolder, cleanupDiagnostic } = await runDownloadCodeQL( + tmpDir, + CLEANUP_BUNDLE_VERSION, + { + env: getTestEnv({ + [ActionsEnvVars.RUNNER_ENVIRONMENT]: "github-hosted", + [EnvVar.HAS_SET_UP_CODEQL]: "true", + }), + }, + ); + + t.true(fs.existsSync(staleDirectory)); + t.true(fs.existsSync(`${codeqlFolder}.complete`)); + t.is(cleanupDiagnostic, undefined); + }); + }, +); + +test.serial( + "setupCodeQLBundle records that this job has set up CodeQL", + async (t) => { + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + delete process.env[EnvVar.HAS_SET_UP_CODEQL]; + + stubDownloadAndExtract(); + + await setupCodeql.setupCodeQLBundle( + "linked", + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + undefined, // rawLanguages + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + createFeatures([]), + new RecordingLogger(), + ); + + t.is( + process.env[EnvVar.HAS_SET_UP_CODEQL], + "true", + "A later step must be able to tell that the toolcache is in use.", + ); + }); + }, +); + +test.serial( + "setupCodeQLBundle cleans up once and propagates a failed combined download", + async (t) => { + const error = new HTTPError("Not Found", 404); + const extractStub = stubDownloadAndExtract().rejects(error); + const cleanupSpy = sinon.spy(toolsDownload, "deleteToolcacheBundles"); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + delete process.env[EnvVar.HAS_SET_UP_CODEQL]; + const staleDirectory = createToolcacheEntry( + tmpDir, + "CodeQL", + CLEANUP_STALE_VERSION, + ); + + await t.throwsAsync( + setupCodeql.setupCodeQLBundle( + "linked", + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + undefined, // rawLanguages + undefined, // otherLanguagePacksReason + false, // useOverlayAwareDefaultCliVersion + createFeatures([]), + new RecordingLogger(), + ), + { is: error }, + ); + + t.true(cleanupSpy.calledOnce); + t.true(cleanupSpy.calledBefore(extractStub)); + t.true(extractStub.calledOnce); + t.false(fs.existsSync(staleDirectory)); + t.false(fs.existsSync(`${extractStub.firstCall.args[2]}.complete`)); + t.deepEqual(toolcache.findAllVersions("CodeQL"), []); + t.is(process.env[EnvVar.HAS_SET_UP_CODEQL], undefined); + }); + }, +); + +test.serial( + "downloadCodeQLBundle cleans up the toolcache even when the download will not be cached", + async (t) => { + // A `tools` URL we can't derive a bundle version from is extracted to a temporary directory + // rather than the toolcache, but the toolcache is on the same filesystem, so emptying it still + // frees up space for the analysis. + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + + const staleDirectory = createToolcacheEntry( + tmpDir, + "CodeQL", + CLEANUP_STALE_VERSION, + ); + + const { codeqlFolder, cleanupDiagnostic } = await runDownloadCodeQL( + tmpDir, + undefined, // bundleVersion + ); + + t.is(path.dirname(codeqlFolder), tmpDir); + t.not(codeqlFolder, path.join(tmpDir, "CodeQL")); + t.true(fs.existsSync(codeqlFolder)); + t.false(fs.existsSync(`${codeqlFolder}.complete`)); + t.false(fs.existsSync(staleDirectory)); + t.deepEqual(cleanupDiagnostic, { + deletedVersions: [CLEANUP_STALE_VERSION], + failed: false, + }); + }); + }, +); + +test.serial( + "downloadCodeQLBundle reports a failure when the toolcache cannot be inspected", + async (t) => { + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + + createToolcacheEntry(tmpDir, "CodeQL", CLEANUP_STALE_VERSION); + + const lstatStub = sinon.stub(fs.promises, "lstat").rejects( + Object.assign(new Error("permission denied"), { + code: "EACCES", + }), + ); + + const { cleanupDiagnostic } = await runDownloadCodeQL( + tmpDir, + CLEANUP_BUNDLE_VERSION, + ); + + lstatStub.restore(); + + t.deepEqual( + cleanupDiagnostic, + { deletedVersions: [], failed: true }, + "An error other than the toolcache being absent must not be reported as success.", + ); + }); + }, +); + +test.serial( + "downloadCodeQLBundle does not clean up a toolcache on a different filesystem to the workspace", + async (t) => { + // Some runner images keep the toolcache on a different volume to the workspace, in which case + // deleting the tools frees up disk space that the analysis cannot use. + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + + const staleDirectory = createToolcacheEntry( + tmpDir, + "CodeQL", + CLEANUP_STALE_VERSION, + ); + + sinon + .stub(toolsDownload, "isToolcacheOnWorkspaceFilesystem") + .returns(false); + + const { cleanupDiagnostic } = await runDownloadCodeQL( + tmpDir, + CLEANUP_BUNDLE_VERSION, + ); + + t.true(fs.existsSync(staleDirectory)); + t.is(cleanupDiagnostic, undefined); + }); + }, +); + +test.serial( + "isToolcacheOnWorkspaceFilesystem assumes a different filesystem when it cannot tell", + async (t) => { + await withTmpDir(async (tmpDir) => { + const logger = new RecordingLogger(); + + setupActionsVars(tmpDir, tmpDir); + t.true(toolsDownload.isToolcacheOnWorkspaceFilesystem(logger)); + + // If we can't tell, we assume the toolcache is not somewhere we can reclaim space from. + process.env[ActionsEnvVars.RUNNER_TOOL_CACHE] = path.join( + tmpDir, + "does-not-exist", + ); + t.false(toolsDownload.isToolcacheOnWorkspaceFilesystem(logger)); + }); + }, +); + +test.serial( + "downloadCodeQLBundle does not delete through a symlinked version directory", + async (t) => { + await withTmpDir(async (tmpDir) => { + const toolcacheRoot = path.join(tmpDir, "toolcache"); + setupActionsVars(tmpDir, toolcacheRoot); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + + createToolcacheEntry(toolcacheRoot, "CodeQL", CLEANUP_STALE_VERSION); + + // Somewhere outside the toolcache that a version directory points at. + const outsideDirectory = path.join(tmpDir, "outside"); + fs.mkdirSync(outsideDirectory, { recursive: true }); + fs.writeFileSync(path.join(outsideDirectory, "contents"), "x"); + fs.symlinkSync( + outsideDirectory, + path.join(toolcacheRoot, "CodeQL", "9.9.9"), + ); + + const { cleanupDiagnostic } = await runDownloadCodeQL( + toolcacheRoot, + CLEANUP_BUNDLE_VERSION, + ); + + t.true( + fs.existsSync(path.join(outsideDirectory, "contents")), + "Should not delete anything through a symlinked version directory.", + ); + t.true( + fs + .lstatSync(path.join(toolcacheRoot, "CodeQL", "9.9.9")) + .isSymbolicLink(), + ); + t.deepEqual(cleanupDiagnostic, { + deletedVersions: [CLEANUP_STALE_VERSION], + failed: false, + }); + }); }, ); diff --git a/src/setup-codeql.ts b/src/setup-codeql.ts index 8d374585aa..d70e1f5087 100644 --- a/src/setup-codeql.ts +++ b/src/setup-codeql.ts @@ -1,24 +1,32 @@ import * as fs from "fs"; import { OutgoingHttpHeaders } from "http"; import * as path from "path"; +import { performance } from "perf_hooks"; import * as toolcache from "@actions/tool-cache"; -import { default as deepEqual } from "fast-deep-equal"; import * as semver from "semver"; import { v4 as uuidV4 } from "uuid"; +import { ActionState } from "./action-common"; import { isAnalyzingPullRequest, isDynamicWorkflow, - isRunningLocalAction, + isGitHubHostedRunner, } from "./actions-util"; import * as api from "./api-client"; +import { + CodeQLBundle, + CodeQLDownloadSource, + getCodeQLBundleFromUrl, + getCodeQLBundleName, +} from "./codeql-bundle"; import * as defaults from "./defaults.json"; import { addNoLanguageDiagnostic, makeDiagnostic, makeTelemetryDiagnostic, } from "./diagnostics"; +import { EnvVar, exportEnvVar, getEnv } from "./environment"; import { CODEQL_VERSION_ZSTD_BUNDLE, CodeQLDefaultVersionInfo, @@ -26,18 +34,29 @@ import { Feature, FeatureEnablement, } from "./feature-flags"; +import { BuiltInLanguage } from "./languages"; import { Logger } from "./logging"; import { getCodeQlVersionsForOverlayBaseDatabases } from "./overlay/caching"; +import { + getPerLanguageBundleLanguage, + logPerLanguageBundleFallback, +} from "./per-language-bundles"; +import { getBundlePlatform } from "./platform"; +import { getCodeQLAssetDownloadURL } from "./setup/repository"; import * as tar from "./tar"; import { + deleteToolcacheBundles, downloadAndExtract, getToolcacheDirectory, + isToolcacheOnWorkspaceFilesystem, ToolsDownloadStatusReport, writeToolcacheMarkerFile, } from "./tools-download"; import * as util from "./util"; import { isGoodVersion } from "./util"; +export type { CodeQLDownloadSource } from "./codeql-bundle"; + export enum ToolsSource { Unknown = "UNKNOWN", Local = "LOCAL", @@ -45,7 +64,6 @@ export enum ToolsSource { Download = "DOWNLOAD", } -const CODEQL_DEFAULT_ACTION_REPOSITORY = "github/codeql-action"; const CODEQL_NIGHTLIES_REPOSITORY_OWNER = "dsp-testing"; const CODEQL_NIGHTLIES_REPOSITORY_NAME = "codeql-cli-nightlies"; @@ -53,112 +71,11 @@ const CODEQL_BUNDLE_VERSION_ALIAS: string[] = ["linked", "latest"]; const CODEQL_NIGHTLY_TOOLS_INPUTS = ["nightly", "nightly-latest"]; const CODEQL_TOOLCACHE_INPUT = "toolcache"; -function getCodeQLBundleExtension( - compressionMethod: tar.CompressionMethod, -): string { - switch (compressionMethod) { - case "gzip": - return ".tar.gz"; - case "zstd": - return ".tar.zst"; - default: - util.assertNever(compressionMethod); - } -} - -export function getCodeQLBundleName( - compressionMethod: tar.CompressionMethod, -): string { - const extension = getCodeQLBundleExtension(compressionMethod); - - let platform: string; - if (process.platform === "win32") { - platform = "win64"; - } else if (process.platform === "linux") { - platform = "linux64"; - } else if (process.platform === "darwin") { - platform = "osx64"; - } else { - return `codeql-bundle${extension}`; - } - return `codeql-bundle-${platform}${extension}`; -} - -export function getCodeQLActionRepository(logger: Logger): string { - if (isRunningLocalAction()) { - // This handles the case where the Action does not come from an Action repository, - // e.g. our integration tests which use the Action code from the current checkout. - // In these cases, the GITHUB_ACTION_REPOSITORY environment variable is not set. - logger.info( - "The CodeQL Action is checked out locally. Using the default CodeQL Action repository.", - ); - return CODEQL_DEFAULT_ACTION_REPOSITORY; - } - - return util.getRequiredEnvParam("GITHUB_ACTION_REPOSITORY"); -} - -async function getCodeQLBundleDownloadURL( - tagName: string, - apiDetails: api.GitHubApiDetails, - compressionMethod: tar.CompressionMethod, - logger: Logger, -): Promise { - const codeQLActionRepository = getCodeQLActionRepository(logger); - const potentialDownloadSources = [ - // This GitHub instance, and this Action. - [apiDetails.url, codeQLActionRepository], - // This GitHub instance, and the canonical Action. - [apiDetails.url, CODEQL_DEFAULT_ACTION_REPOSITORY], - // GitHub.com, and the canonical Action. - [util.GITHUB_DOTCOM_URL, CODEQL_DEFAULT_ACTION_REPOSITORY], - ]; - // We now filter out any duplicates. - // Duplicates will happen either because the GitHub instance is GitHub.com, or because the Action is not a fork. - const uniqueDownloadSources = potentialDownloadSources.filter( - (source, index, self) => { - return !self.slice(0, index).some((other) => deepEqual(source, other)); - }, - ); - const codeQLBundleName = getCodeQLBundleName(compressionMethod); - for (const downloadSource of uniqueDownloadSources) { - const [apiURL, repository] = downloadSource; - // If we've reached the final case, short-circuit the API check since we know the bundle exists and is public. - if ( - apiURL === util.GITHUB_DOTCOM_URL && - repository === CODEQL_DEFAULT_ACTION_REPOSITORY - ) { - break; - } - const [repositoryOwner, repositoryName] = repository.split("/"); - try { - const release = await api.getApiClient().rest.repos.getReleaseByTag({ - owner: repositoryOwner, - repo: repositoryName, - tag: tagName, - }); - for (const asset of release.data.assets) { - if (asset.name === codeQLBundleName) { - logger.info( - `Found CodeQL bundle ${codeQLBundleName} in ${repository} on ${apiURL} with URL ${asset.url}.`, - ); - return asset.url; - } - } - } catch (e) { - logger.info( - `Looked for CodeQL bundle ${codeQLBundleName} in ${repository} on ${apiURL} but got error ${e}.`, - ); - } - } - return `https://github.com/${CODEQL_DEFAULT_ACTION_REPOSITORY}/releases/download/${tagName}/${codeQLBundleName}`; -} - function tryGetBundleVersionFromTagName( tagName: string, logger: Logger, ): string | undefined { - const match = tagName.match(/^codeql-bundle-(.*)$/); + const match = tagName.match(/^codeql-bundle-(.+)$/); if (match === null || match.length < 2) { logger.debug(`Could not determine bundle version from tag ${tagName}.`); return undefined; @@ -223,17 +140,7 @@ export type CodeQLToolsSource = /** Human-readable description of the source of the tools for telemetry purposes. */ toolsVersion: string; } - | { - /** Bundle version of the tools, if known. */ - bundleVersion?: string; - /** CLI version of the tools, if known. */ - cliVersion?: string; - compressionMethod: tar.CompressionMethod; - codeqlURL: string; - sourceType: "download"; - /** Human-readable description of the source of the tools for telemetry purposes. */ - toolsVersion: string; - }; + | CodeQLDownloadSource; /** * Look for a version of the CodeQL tools in the cache which could override the requested CLI version. @@ -276,29 +183,16 @@ async function findOverridingToolsInCache( /** * Returns the sorted set of enabled versions that have cached overlay-base databases for the - * given languages, or an empty list if neither the `OverlayAnalysisMatchCodeqlVersion` nor the - * `OverlayAnalysisMatchCodeqlVersionDryRun` feature flag is enabled. When only the dry-run flag - * is enabled, this performs the lookup and emits a telemetry diagnostic with the version that - * would have been chosen, but still returns an empty list so the caller falls back. + * given languages. */ export async function getEnabledVersionsWithOverlayBaseDatabases( defaultCliVersion: CodeQLDefaultVersionInfo, rawLanguages: string[] | undefined, - features: FeatureEnablement, logger: Logger, ): Promise { if (rawLanguages === undefined || rawLanguages.length === 0) { return []; } - const isEnabled = await features.getValue( - Feature.OverlayAnalysisMatchCodeqlVersion, - ); - const isDryRun = - !isEnabled && - (await features.getValue(Feature.OverlayAnalysisMatchCodeqlVersionDryRun)); - if (!isEnabled && !isDryRun) { - return []; - } let cachedVersions: string[] | undefined; try { @@ -319,66 +213,35 @@ export async function getEnabledVersionsWithOverlayBaseDatabases( } const cachedVersionsSet = new Set(cachedVersions); - const overlayVersions = defaultCliVersion.enabledVersions.filter((v) => + return defaultCliVersion.enabledVersions.filter((v) => cachedVersionsSet.has(v.cliVersion), ); - - if (overlayVersions.length === 0) { - return []; - } - - const isCachedVersionDifferent = - overlayVersions[0].cliVersion !== - defaultCliVersion.enabledVersions[0].cliVersion; - - if (isCachedVersionDifferent) { - addNoLanguageDiagnostic( - undefined, - makeTelemetryDiagnostic( - "codeql-action/overlay-aware-default-codeql-version", - "Overlay-aware default CodeQL version selection", - { - cachedVersions, - enabledVersions: defaultCliVersion.enabledVersions.map( - (v) => v.cliVersion, - ), - isDryRun, - overlayAwareVersion: overlayVersions[0].cliVersion, - }, - ), - ); - } - - if (isDryRun) { - logger.debug( - `Overlay-aware default CodeQL version selection is running in dry-run mode. Would have used version ${overlayVersions[0].cliVersion}.`, - ); - return []; - } - - return overlayVersions; } /** * Resolves the newest enabled default CLI version that has a cached overlay-base database for the - * relevant languages, if running a Code Scanning analysis for a pull request and one exists. - * Otherwise, falls back to the newest enabled default CLI version. + * relevant languages, if this is a Code Scanning analysis of a pull request, multiple default + * versions are enabled, and such a version exists. Otherwise, falls back to the newest enabled + * default CLI version. */ async function resolveDefaultCliVersion( defaultCliVersion: CodeQLDefaultVersionInfo, rawLanguages: string[] | undefined, useOverlayAwareDefaultCliVersion: boolean, - features: FeatureEnablement, logger: Logger, ): Promise { - if (!useOverlayAwareDefaultCliVersion || !isAnalyzingPullRequest()) { + if ( + !useOverlayAwareDefaultCliVersion || + // Listing the Actions cache can't change which version we use if only one version is enabled. + defaultCliVersion.enabledVersions.length === 1 || + !isAnalyzingPullRequest() + ) { return defaultCliVersion.enabledVersions[0]; } const overlayVersions = await getEnabledVersionsWithOverlayBaseDatabases( defaultCliVersion, rawLanguages, - features, logger, ); if (overlayVersions.length > 0) { @@ -398,6 +261,9 @@ async function resolveDefaultCliVersion( * @param toolsInput The argument provided for the `tools` input, if any. * @param defaultCliVersion The default CLI version that's linked to the CodeQL Action. * @param rawLanguages Raw set of languages. + * @param otherLanguagePacksReason Why the CodeQL CLI may need packs for languages other than + * `rawLanguages`, or `undefined` if it won't. If defined, the combined bundle is used. See + * `PerLanguageBundleOptions.otherLanguagePacksReason`. * @param useOverlayAwareDefaultCliVersion Whether to select an overlay-aware default CLI version. * @param apiDetails Information about the GitHub API. * @param variant The GitHub variant we are running on. @@ -411,6 +277,7 @@ export async function getCodeQLSource( toolsInput: string | undefined, defaultCliVersion: CodeQLDefaultVersionInfo, rawLanguages: string[] | undefined, + otherLanguagePacksReason: string | undefined, useOverlayAwareDefaultCliVersion: boolean, apiDetails: api.GitHubApiDetails, variant: util.GitHubVariant, @@ -442,7 +309,7 @@ export async function getCodeQLSource( }; } - /** CLI version number, for example 2.12.6. */ + /** Requested CLI version number, for example 2.12.6. */ let cliVersion: string | undefined; /** Tag name of the CodeQL bundle, for example `codeql-bundle-20230120`. */ let tagName: string | undefined; @@ -452,6 +319,7 @@ export async function getCodeQLSource( * This does not always include a tag name. */ let url: string | undefined; + let bundle: CodeQLBundle | undefined; // We allow forcing the nightly CLI via the FF for `dynamic` events (or in test mode) where the // `tools` input cannot be adjusted to explicitly request it. @@ -460,7 +328,8 @@ export async function getCodeQLSource( const forceNightly = forceNightlyValueFF && canForceNightlyWithFF; // For advanced workflows, a value from `CODEQL_NIGHTLY_TOOLS_INPUTS` can be specified explicitly - // for the `tools` input in the workflow file. + // for the `tools` input. This is the computed input, so it may come from the repository property + // rather than the workflow file. const nightlyRequestedByToolsInput = toolsInput !== undefined && CODEQL_NIGHTLY_TOOLS_INPUTS.includes(toolsInput); @@ -494,7 +363,13 @@ export async function getCodeQLSource( `Using the latest CodeQL CLI nightly, as requested by 'tools: ${toolsInput}'.`, ); } - toolsInput = await getNightlyToolsUrl(logger); + bundle = await getLatestNightlyBundle( + { env: getEnv(), logger }, + rawLanguages, + otherLanguagePacksReason, + variant, + ); + toolsInput = bundle.url; } /** @@ -563,7 +438,6 @@ export async function getCodeQLSource( defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, - features, logger, ); cliVersion = version.cliVersion; @@ -577,7 +451,7 @@ export async function getCodeQLSource( if (tagName) { const bundleVersion = tryGetBundleVersionFromTagName(tagName, logger); // If the bundle version is a semantic version, it is a CLI version number. - if (bundleVersion && semver.valid(bundleVersion)) { + if (bundleVersion !== undefined && semver.valid(bundleVersion)) { cliVersion = convertToSemVer(bundleVersion, logger); } } @@ -586,7 +460,6 @@ export async function getCodeQLSource( defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, - features, logger, ); cliVersion = version.cliVersion; @@ -594,13 +467,15 @@ export async function getCodeQLSource( } const bundleVersion = - tagName && tryGetBundleVersionFromTagName(tagName, logger); - const humanReadableVersion = + tagName !== undefined + ? tryGetBundleVersionFromTagName(tagName, logger) + : undefined; + const resolvedVersion = cliVersion ?? - (bundleVersion && convertToSemVer(bundleVersion, logger)) ?? - tagName ?? - url ?? - "unknown"; + (bundleVersion !== undefined + ? convertToSemVer(bundleVersion, logger) + : undefined); + const humanReadableVersion = resolvedVersion ?? tagName ?? url ?? "unknown"; logger.debug( "Attempting to obtain CodeQL tools. " + @@ -715,18 +590,55 @@ export async function getCodeQLSource( let compressionMethod: tar.CompressionMethod; if (!url) { + const bundleTagName = tagName; + if (bundleTagName === undefined) { + throw new Error( + "Could not determine a release tag for the requested CodeQL bundle.", + ); + } + compressionMethod = cliVersion !== undefined && (await useZstdBundle(cliVersion, tarSupportsZstd)) ? "zstd" : "gzip"; - url = await getCodeQLBundleDownloadURL( - tagName!, - apiDetails, + const action = { env: getEnv(), logger }; + const platform = getBundlePlatform(); + const perLanguageBundleLanguage = getPerLanguageBundleLanguage(action, { + rawLanguages, + otherLanguagePacksReason, + cliVersion, compressionMethod, - logger, - ); + platform, + variant, + }); + + // Resolves the combined or per-language bundle URL for the requested release. + const resolveBundleURL = (language?: BuiltInLanguage) => + getCodeQLAssetDownloadURL( + action, + apiDetails, + bundleTagName, + getCodeQLBundleName(compressionMethod, platform, language), + ); + + const combinedBundleURL = await resolveBundleURL(); + if (perLanguageBundleLanguage !== undefined) { + logger.info( + `Selected the per-language CodeQL bundle for '${perLanguageBundleLanguage}'.`, + ); + url = await resolveBundleURL(perLanguageBundleLanguage); + bundle = { + kind: "per-language", + url, + language: perLanguageBundleLanguage, + combinedBundleURL, + }; + } else { + url = combinedBundleURL; + bundle = { kind: "combined", url }; + } } else { const method = tar.inferCompressionMethod(url); if (method === undefined) { @@ -736,6 +648,13 @@ export async function getCodeQLSource( ); } compressionMethod = method; + + bundle ??= getCodeQLBundleFromUrl(url); + if (bundle.kind === "per-language") { + logger.info( + `${url} appears to be a CodeQL bundle that contains only ${bundle.language}.`, + ); + } } if (cliVersion) { @@ -744,12 +663,12 @@ export async function getCodeQLSource( logger.info(`Using CodeQL CLI sourced from ${url} .`); } return { - bundleVersion: tagName && tryGetBundleVersionFromTagName(tagName, logger), + bundle, + bundleVersion, cliVersion, - codeqlURL: url, compressionMethod, sourceType: "download", - toolsVersion: cliVersion ?? humanReadableVersion, + toolsVersion: resolvedVersion ?? "unknown", }; } @@ -763,7 +682,7 @@ async function tryGetFallbackToolcacheVersion( logger: Logger, ): Promise { const bundleVersion = tryGetBundleVersionFromTagName(tagName, logger); - if (!bundleVersion) { + if (bundleVersion === undefined) { return undefined; } const fallbackVersion = convertToSemVer(bundleVersion, logger); @@ -777,10 +696,7 @@ async function tryGetFallbackToolcacheVersion( // Exported using `export const` for testing purposes. Specifically, we want to // be able to stub this function and have other functions in this file use that stub. export const downloadCodeQL = async function ( - codeqlURL: string, - compressionMethod: tar.CompressionMethod, - maybeBundleVersion: string | undefined, - maybeCliVersion: string | undefined, + source: CodeQLDownloadSource, apiDetails: api.GitHubApiDetails, tarVersion: tar.TarVersion | undefined, tempDir: string, @@ -788,8 +704,9 @@ export const downloadCodeQL = async function ( ): Promise<{ codeqlFolder: string; statusReport: ToolsDownloadStatusReport; - toolsVersion: string; }> { + const { bundle, compressionMethod } = source; + const codeqlURL = bundle.url; const parsedCodeQLURL = new URL(codeqlURL); const searchParams = new URLSearchParams(parsedCodeQLURL.search); const headers: OutgoingHttpHeaders = { @@ -808,15 +725,11 @@ export const downloadCodeQL = async function ( ); } - const toolcacheInfo = getToolcacheDestinationInfo( - maybeBundleVersion, - maybeCliVersion, - logger, + const toolcacheDestination = getToolcacheDestination({ logger }, source); + const extractedBundlePath = toolcacheDestination.orElse( + getTempExtractionDir(tempDir), ); - const extractedBundlePath = - toolcacheInfo?.path ?? getTempExtractionDir(tempDir); - const statusReport = await downloadAndExtract( codeqlURL, compressionMethod, @@ -827,46 +740,90 @@ export const downloadCodeQL = async function ( logger, ); - if (!toolcacheInfo) { - logger.debug( - "Could not cache CodeQL tools because we could not determine the bundle version from the " + - `URL ${codeqlURL}.`, - ); - return { - codeqlFolder: extractedBundlePath, - statusReport, - toolsVersion: maybeCliVersion ?? "unknown", - }; + if (toolcacheDestination.isSuccess()) { + writeToolcacheMarkerFile(toolcacheDestination.value, logger); + } else { + logger.debug(toolcacheDestination.value); } - writeToolcacheMarkerFile(toolcacheInfo.path, logger); - return { codeqlFolder: extractedBundlePath, - statusReport, - toolsVersion: maybeCliVersion ?? toolcacheInfo.version, + statusReport: + bundle.kind === "per-language" + ? { + ...statusReport, + perLanguage: { tools_bundle_language: bundle.language }, + } + : statusReport, }; }; -function getToolcacheDestinationInfo( - maybeBundleVersion: string | undefined, - maybeCliVersion: string | undefined, - logger: Logger, -): { path: string; version: string } | undefined { - if (maybeBundleVersion) { - const version = getCanonicalToolcacheVersion( - maybeCliVersion, - maybeBundleVersion, - logger, +/** + * Returns the canonical toolcache directory, or the reason the bundle cannot be cached. + */ +function getToolcacheDestination( + { logger }: ActionState<["Logger"]>, + source: CodeQLDownloadSource, +): util.Result { + if (source.bundle.kind !== "combined") { + return new util.Failure( + "Not caching the CodeQL tools because they came from a bundle that contains only a " + + "single language.", + ); + } + if (!source.bundleVersion) { + return new util.Failure( + "Could not cache CodeQL tools because we could not determine the bundle version from the " + + `URL ${source.bundle.url}.`, ); + } - return { - path: getToolcacheDirectory(version), - version, - }; + return new util.Success( + getToolcacheDirectory( + getCanonicalToolcacheVersion( + source.cliVersion, + source.bundleVersion, + logger, + ), + ), + ); +} + +/** + * Reclaims disk space by deleting the CodeQL tools from the toolcache on GitHub-hosted runners. + * + * On GitHub-hosted runners the toolcache shares a filesystem with the workspace, so tools left in + * the toolcache take up space that the analysis could use instead. This holds wherever we extract + * the tools we are obtaining, since the toolcache is on that filesystem either way. + */ +async function tryDeleteToolcacheBundles({ + env, + logger, +}: ActionState<["Logger", "ReadOnlyEnv"]>): Promise { + // A step that has already set up CodeQL may hand out a path into the toolcache that a later step + // runs, so only the first step to set it up can know that nothing else relies on the toolcache. + if (env.getOptional(EnvVar.HAS_SET_UP_CODEQL) !== undefined) { + logger.debug( + "Not deleting the CodeQL tools from the toolcache since a previous step in this job has " + + "already set up CodeQL.", + ); + return; } - return undefined; + if (!isGitHubHostedRunner(env) || !isToolcacheOnWorkspaceFilesystem(logger)) { + return; + } + + const result = await deleteToolcacheBundles({ env, logger }); + + addNoLanguageDiagnostic( + undefined, + makeTelemetryDiagnostic( + "codeql-action/toolcache-bundle-cleanup", + "Toolcache CodeQL bundle cleanup", + { ...result }, + ), + ); } export function getCodeQLURLVersion(url: string): string { @@ -925,6 +882,7 @@ export async function setupCodeQLBundle( variant: util.GitHubVariant, defaultCliVersion: CodeQLDefaultVersionInfo, rawLanguages: string[] | undefined, + otherLanguagePacksReason: string | undefined, useOverlayAwareDefaultCliVersion: boolean, features: FeatureEnablement, logger: Logger, @@ -940,6 +898,7 @@ export async function setupCodeQLBundle( toolsInput, defaultCliVersion, rawLanguages, + otherLanguagePacksReason, useOverlayAwareDefaultCliVersion, apiDetails, variant, @@ -949,7 +908,6 @@ export async function setupCodeQLBundle( ); let codeqlFolder: string; - let toolsVersion = source.toolsVersion; let toolsDownloadStatusReport: ToolsDownloadStatusReport | undefined; let toolsSource: ToolsSource; switch (source.sourceType) { @@ -970,17 +928,13 @@ export async function setupCodeQLBundle( toolsSource = ToolsSource.Toolcache; break; case "download": { - const result = await downloadCodeQL( - source.codeqlURL, - source.compressionMethod, - source.bundleVersion, - source.cliVersion, + const result = await downloadCodeQLBundle( + { env: getEnv(), logger }, + source, apiDetails, zstdAvailability.version, tempDir, - logger, ); - toolsVersion = result.toolsVersion; codeqlFolder = result.codeqlFolder; toolsDownloadStatusReport = result.statusReport; toolsSource = ToolsSource.Download; @@ -989,14 +943,82 @@ export async function setupCodeQLBundle( default: util.assertNever(source); } + + // Record that this job now has a copy of the CodeQL tools, so that a later step doesn't delete + // the toolcache out from under the path we are about to return. + exportEnvVar(EnvVar.HAS_SET_UP_CODEQL, "true"); + return { codeqlFolder, toolsDownloadStatusReport, toolsSource, - toolsVersion, + toolsVersion: source.toolsVersion, }; } +/** + * Performs eligible toolcache cleanup once, then downloads and extracts the resolved bundle. + * + * If an automatically selected per-language bundle is missing, downloads the combined bundle + * from the same release instead. Explicit bundle URLs are not substituted. + * + * @returns The extraction directory and download timings. + */ +export async function downloadCodeQLBundle( + action: ActionState<["Logger", "ReadOnlyEnv"]>, + source: CodeQLDownloadSource, + apiDetails: api.GitHubApiDetails, + tarVersion: tar.TarVersion | undefined, + tempDir: string, +): Promise<{ + codeqlFolder: string; + statusReport: ToolsDownloadStatusReport; +}> { + const { bundle } = source; + const { logger } = action; + + await tryDeleteToolcacheBundles(action); + + const startTime = performance.now(); + try { + return await downloadCodeQL( + source, + apiDetails, + tarVersion, + tempDir, + logger, + ); + } catch (e) { + if ( + bundle.kind !== "per-language" || + bundle.combinedBundleURL === undefined || + util.asHTTPError(e)?.status !== 404 + ) { + throw e; + } + logPerLanguageBundleFallback(action, bundle.language, bundle.url); + + const result = await downloadCodeQL( + { + ...source, + bundle: { kind: "combined", url: bundle.combinedBundleURL }, + }, + apiDetails, + tarVersion, + tempDir, + logger, + ); + return { + ...result, + statusReport: { + ...result.statusReport, + totalDurationMs: util.durationMsSince(startTime), + perLanguage: { tools_per_language_bundle_fallback: true }, + }, + }; + } +} + async function useZstdBundle( cliVersion: string, tarSupportsZstd: boolean, @@ -1014,9 +1036,16 @@ function getTempExtractionDir(tempDir: string) { } /** - * Get the URL of the latest nightly CodeQL bundle. + * Selects a bundle from the latest nightly release, preferring a per-language bundle when eligible. + * Records the combined bundle URL from that release for use if the selected asset is missing. */ -async function getNightlyToolsUrl(logger: Logger) { +async function getLatestNightlyBundle( + action: ActionState<["Logger", "ReadOnlyEnv"]>, + rawLanguages: string[] | undefined, + otherLanguagePacksReason: string | undefined, + variant: util.GitHubVariant, +): Promise { + const { logger } = action; const zstdAvailability = await tar.isZstdAvailable(logger); // The nightly is guaranteed to have a zstd bundle const compressionMethod = (await useZstdBundle( @@ -1026,6 +1055,17 @@ async function getNightlyToolsUrl(logger: Logger) { ? "zstd" : "gzip"; + const platform = getBundlePlatform(); + const language = getPerLanguageBundleLanguage(action, { + rawLanguages, + otherLanguagePacksReason, + cliVersion: undefined, + compressionMethod, + platform, + variant, + isLatestNightly: true, + }); + try { // Since nightlies are prereleases, we can't just download the latest release // on the repository. So instead we need to find the latest pre-release @@ -1041,7 +1081,21 @@ async function getNightlyToolsUrl(logger: Logger) { if (!latestRelease) { throw new Error("Could not find the latest nightly release."); } - return `https://github.com/${CODEQL_NIGHTLIES_REPOSITORY_OWNER}/${CODEQL_NIGHTLIES_REPOSITORY_NAME}/releases/download/${latestRelease.tag_name}/${getCodeQLBundleName(compressionMethod)}`; + const assetUrl = (name: string) => + `https://github.com/${CODEQL_NIGHTLIES_REPOSITORY_OWNER}/${CODEQL_NIGHTLIES_REPOSITORY_NAME}/releases/download/${latestRelease.tag_name}/${name}`; + const url = assetUrl( + getCodeQLBundleName(compressionMethod, platform, language), + ); + return language === undefined + ? { kind: "combined", url } + : { + kind: "per-language", + url, + language, + combinedBundleURL: assetUrl( + getCodeQLBundleName(compressionMethod, platform), + ), + }; } catch (e) { throw new Error( `Failed to retrieve the latest nightly release: ${util.wrapError(e)}`, diff --git a/src/setup/repository.test.ts b/src/setup/repository.test.ts new file mode 100644 index 0000000000..9fabd84884 --- /dev/null +++ b/src/setup/repository.test.ts @@ -0,0 +1,34 @@ +import * as path from "path"; + +import test from "ava"; +import * as sinon from "sinon"; + +import * as actionsUtil from "../actions-util"; +import { ActionsEnvVars } from "../environment"; +import { callee, getTestEnv, setupTests } from "../testing-utils"; + +import { getCodeQLActionRepository } from "./repository"; + +setupTests(test); + +test.serial("getCodeQLActionRepository", async (t) => { + const initialEnv = getTestEnv({ + [ActionsEnvVars.RUNNER_TEMP]: path.dirname(__dirname), + }); + initialEnv.initialise("1.2.3"); + + const target = callee(getCodeQLActionRepository) + .withArgs() + .withEnv(initialEnv); + + // isRunningLocalAction() === true + await target.passes(t.deepEqual, "github/codeql-action"); + + // isRunningLocalAction() === false + sinon.stub(actionsUtil, "isRunningLocalAction").returns(false); + await target + .withEnv((env) => { + env.set(ActionsEnvVars.GITHUB_ACTION_REPOSITORY, "xxx/yyy"); + }) + .passes(t.deepEqual, "xxx/yyy"); +}); diff --git a/src/setup/repository.ts b/src/setup/repository.ts new file mode 100644 index 0000000000..ff02a1560b --- /dev/null +++ b/src/setup/repository.ts @@ -0,0 +1,158 @@ +import { ActionState } from "../action-common"; +import { isRunningLocalAction } from "../actions-util"; +import * as api from "../api-client"; +import { ActionsEnvVars } from "../environment"; +import { GITHUB_DOTCOM_URL, type InstanceURL } from "../github"; +import { + isRepositoryNwoStr, + parseRepositoryNwo, + type RepositoryNwoStr, +} from "../repository"; + +/** The NWO of the standard CodeQL Action repository. */ +export const CODEQL_DEFAULT_ACTION_REPOSITORY = "github/codeql-action"; + +/** + * Retrieves the NWO of the repository that the CodeQL Action is loaded from. + * Typically, this will be `github/codeql-action`, but it may be something else for + * forks of the Action or in environments other than GitHub.com. + * + * If this function detects that we are running the Action locally (e.g. in tests), + * then we default to `CODEQL_DEFAULT_ACTION_REPOSITORY`. + */ +export function getCodeQLActionRepository( + action: ActionState<["ReadOnlyEnv", "Logger"]>, +): RepositoryNwoStr { + if (isRunningLocalAction(action.env)) { + // This handles the case where the Action does not come from an Action repository, + // e.g. our integration tests which use the Action code from the current checkout. + // In these cases, the GITHUB_ACTION_REPOSITORY environment variable is not set. + action.logger.info( + "The CodeQL Action is checked out locally. Using the default CodeQL Action repository.", + ); + return CODEQL_DEFAULT_ACTION_REPOSITORY; + } + + const actionRepository = action.env.getRequired( + ActionsEnvVars.GITHUB_ACTION_REPOSITORY, + ); + + if (isRepositoryNwoStr(actionRepository)) { + return actionRepository; + } + + throw new Error( + `The value of '${ActionsEnvVars.GITHUB_ACTION_REPOSITORY}' is '${actionRepository}', which does not match the expected 'owner/repo' format.`, + ); +} + +/**A download source is a pair of strings. */ +export type DownloadSource = [InstanceURL, RepositoryNwoStr]; + +/** GitHub.com, and the canonical Action. */ +export const DEFAULT_DOWNLOAD_SOURCE: DownloadSource = [ + GITHUB_DOTCOM_URL, + CODEQL_DEFAULT_ACTION_REPOSITORY, +]; + +/** Decides if the two provided download sources are the same. */ +const isSameDownloadSource = ( + [srcUrl, srcRepo]: DownloadSource, + [otherUrl, otherRepo]: DownloadSource, +) => { + return srcUrl === otherUrl && srcRepo === otherRepo; +}; + +/** A download URL is represented as a string. */ +export type DownloadURL = string; + +/** Gets the default GitHub.com download URL for `assetName` in a release tagged `tagName`. */ +export function getDefaultDotcomDownloadURL( + tagName: string, + assetName: string, +): DownloadURL { + return `${GITHUB_DOTCOM_URL}/${CODEQL_DEFAULT_ACTION_REPOSITORY}/releases/download/${tagName}/${assetName}`; +} + +/** Enumerates log-friendly descriptions of different kinds of assets we might look for in releases. */ +export type ReleaseAssetKind = "CodeQL bundle" | "private registry proxy"; + +/** + * Tries to find a download URL for `assetName` in a release tagged with `tagName`. + * + * Depending on where and how the CodeQL Action is running, we may be using different `apiDetails` and there may be + * different options for where to source CodeQL releases from. + * + * This function either returns the download URL for the asset for the first release we find, or + * defaults to the assumed download URL for the asset on the default CodeQL Action repository on GitHub.com. + * In the latter case, this function does not guarantee that the asset actually exists. + * + * @param action The Action state. + * @param apiDetails The details of the GitHub API in use. + * @param tagName The name of the release tag we want to obtain the asset from. + * @param assetName The name of the asset we should look for in the release. + * @param [assetKind="CodeQL bundle"] The kind of asset we are looking for to show in log messages. + * @returns A URL that we can use to download the asset. + */ +export async function getCodeQLAssetDownloadURL( + action: ActionState<["ReadOnlyEnv", "Logger"]>, + apiDetails: api.GitHubApiDetails, + tagName: string, + assetName: string, + assetKind: ReleaseAssetKind = "CodeQL bundle", +): Promise { + const codeQLActionRepository = getCodeQLActionRepository(action); + + const potentialDownloadSources: DownloadSource[] = [ + // This GitHub instance, and this Action. + [apiDetails.url, codeQLActionRepository], + // This GitHub instance, and the canonical Action. + [apiDetails.url, CODEQL_DEFAULT_ACTION_REPOSITORY], + // GitHub.com, and the canonical Action. + DEFAULT_DOWNLOAD_SOURCE, + ]; + + // We now filter out any duplicates. + // Duplicates will happen either because the GitHub instance is GitHub.com, or because the Action is not a fork. + const uniqueDownloadSources = potentialDownloadSources.filter( + (source, index, self) => { + return !self + .slice(0, index) + .some((other) => isSameDownloadSource(source, other)); + }, + ); + + for (const [instanceURL, repository] of uniqueDownloadSources) { + // If we've reached the final case, short-circuit the API check since we know the asset exists and is public. + if ( + isSameDownloadSource(DEFAULT_DOWNLOAD_SOURCE, [instanceURL, repository]) + ) { + break; + } + + const { owner: repositoryOwner, repo: repositoryName } = + parseRepositoryNwo(repository); + try { + const release = await api.getApiClient().rest.repos.getReleaseByTag({ + owner: repositoryOwner, + repo: repositoryName, + tag: tagName, + }); + + for (const asset of release.data.assets) { + if (asset.name === assetName) { + action.logger.info( + `Found ${assetKind} ${assetName} in ${repository} on ${instanceURL} with URL ${asset.url}.`, + ); + return asset.url; + } + } + } catch (e) { + action.logger.info( + `Looked for ${assetKind} ${assetName} in ${repository} on ${instanceURL} but got error ${e}.`, + ); + } + } + + return getDefaultDotcomDownloadURL(tagName, assetName); +} diff --git a/src/start-proxy-action-post.ts b/src/start-proxy-action-post.ts index 6b59052c6e..c872207ac0 100644 --- a/src/start-proxy-action-post.ts +++ b/src/start-proxy-action-post.ts @@ -20,7 +20,7 @@ export async function runWrapper() { try { // Restore inputs from `start-proxy` Action. - actionsUtil.restoreInputs(); + actionsUtil.restoreInputs(logger); // Kill the running proxy const pid = core.getState("proxy-process-pid"); @@ -38,12 +38,6 @@ export async function runWrapper() { logger.info( "Debug mode is on. Uploading proxy log as Actions debugging artifact...", ); - if (config?.gitHubVersion.type === undefined) { - logger.warning( - `Did not upload debug artifacts because cannot determine the GitHub variant running.`, - ); - return; - } const gitHubVersion = await getGitHubVersion(); checkGitHubVersionInRange(gitHubVersion, logger); diff --git a/src/start-proxy-action.ts b/src/start-proxy-action.ts index e8b89732f7..ad1a2e1433 100644 --- a/src/start-proxy-action.ts +++ b/src/start-proxy-action.ts @@ -3,9 +3,14 @@ import * as path from "path"; import * as core from "@actions/core"; -import { Action, ActionState, runInActions } from "./action-common"; +import { + Action, + ActionState, + extendActionState, + runInActions, +} from "./action-common"; import * as actionsUtil from "./actions-util"; -import { getGitHubVersion } from "./api-client"; +import { getApiDetails, getGitHubVersion } from "./api-client"; import { FeatureEnablement, initFeatures } from "./feature-flags"; import { BuiltInLanguage, parseBuiltInLanguage } from "./languages"; import { Logger } from "./logging"; @@ -98,9 +103,13 @@ async function run(action: ActionState<["Base", "Logger", "Env", "Actions"]>) { }; // Start the Proxy - const proxyBin = await getProxyBinaryPath(logger, features); + const actionWithFeatures = extendActionState(action, { features }); + const proxyBin = await getProxyBinaryPath( + actionWithFeatures, + getApiDetails(action.env), + ); const proxyInfo = await startProxy( - proxyBin, + proxyBin.path, proxyConfig, proxyLogFilePath, logger, @@ -116,6 +125,7 @@ async function run(action: ActionState<["Base", "Logger", "Env", "Actions"]>) { languages: language === undefined ? undefined : [language], }, proxyConfig.all_credentials.map((c) => c.type), + { proxy_version: proxyBin.version }, logger, ); } catch (unwrappedError) { diff --git a/src/start-proxy.test.ts b/src/start-proxy.test.ts index ee953798b8..2446c994c7 100644 --- a/src/start-proxy.test.ts +++ b/src/start-proxy.test.ts @@ -1,117 +1,39 @@ import * as filepath from "path"; -import * as core from "@actions/core"; import * as toolcache from "@actions/tool-cache"; import test, { ExecutionContext } from "ava"; import sinon from "sinon"; +import { ActionState } from "./action-common"; +import * as actionsUtil from "./actions-util"; import * as apiClient from "./api-client"; import * as defaults from "./defaults.json"; +import { ActionsEnvVars } from "./environment"; import { setUpFeatureFlagTests } from "./feature-flags/testing-util"; import { UnvalidatedObject, validateSchema } from "./json"; import { makeFromSchema } from "./json/testing-util"; import { BuiltInLanguage } from "./languages"; -import { getRunnerLogger, Logger } from "./logging"; +import { Logger } from "./logging"; +import { BundlePlatform, getBundlePlatform } from "./platform"; +import * as repository from "./setup/repository"; import * as startProxyExports from "./start-proxy"; -import * as statusReport from "./status-report"; import { + addSinonAssertions, assertNotLogged, checkExpectedLogMessages, createFeatures, + initAllState, makeMacro, makeTestToken, RecordingLogger, + SAMPLE_DOTCOM_API_DETAILS, setupTests, withRecordingLoggerAsync, } from "./testing-utils"; -import { - ConfigurationError, - GitHubVariant, - GitHubVersion, - withTmpDir, -} from "./util"; +import { GitHubVariant, GitHubVersion, withTmpDir } from "./util"; setupTests(test); -const sendFailedStatusReportTest = makeMacro({ - exec: async ( - t: ExecutionContext, - err: Error, - expectedMessage: string, - expectedStatus: statusReport.ActionStatus = "failure", - ) => { - const now = new Date(); - - // Override core.setFailed to avoid it setting the program's exit code - sinon.stub(core, "setFailed").returns(); - - const createStatusReportBase = sinon.stub( - statusReport, - "createStatusReportBase", - ); - createStatusReportBase.resolves(undefined); - - await withRecordingLoggerAsync(async (logger) => { - await startProxyExports.sendFailedStatusReport( - logger, - now, - undefined, - err, - ); - - // Check that the stub has been called exactly once, with the expected arguments, - // but not with the message from the error. - sinon.assert.calledOnceWithExactly( - createStatusReportBase, - statusReport.ActionName.StartProxy, - expectedStatus, - now, - sinon.match.any, - sinon.match.any, - sinon.match.any, - expectedMessage, - ); - t.false( - createStatusReportBase.calledWith( - statusReport.ActionName.StartProxy, - expectedStatus, - now, - sinon.match.any, - sinon.match.any, - sinon.match.any, - sinon.match((msg: string) => msg.includes(err.message)), - ), - "createStatusReportBase was called with the error message", - ); - }); - }, - - title: (providedTitle = "") => `sendFailedStatusReport - ${providedTitle}`, -}); - -sendFailedStatusReportTest.serial( - "reports generic error message for non-StartProxyError error", - new Error("Something went wrong today"), - "Error from start-proxy Action omitted (Error).", -); - -sendFailedStatusReportTest.serial( - "reports generic error message for non-StartProxyError error with safe error message", - new Error( - startProxyExports.getStartProxyErrorMessage( - startProxyExports.StartProxyErrorType.DownloadFailed, - ), - ), - "Error from start-proxy Action omitted (Error).", -); - -sendFailedStatusReportTest.serial( - "reports generic error message for ConfigurationError error", - new ConfigurationError("Something went wrong today"), - "Error from start-proxy Action omitted (ConfigurationError).", - "user-error", -); - const toEncodedJSON = (data: any) => Buffer.from(JSON.stringify(data)).toString("base64"); @@ -145,7 +67,7 @@ test("getCredentials prefers registriesCredentials over registrySecrets", async ]); const credentials = startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), registrySecrets, registryCredentials, undefined, @@ -162,7 +84,7 @@ test("getCredentials throws an error when configurations are not an array", asyn t.throws( () => startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, registryCredentials, undefined, @@ -181,7 +103,7 @@ test("getCredentials throws error when credential is not an object", async (t) = t.throws( () => startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, testCredential, undefined, @@ -202,7 +124,7 @@ test("getCredentials throws error when credential is missing type", async (t) => t.throws( () => startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, testCredential, undefined, @@ -225,7 +147,7 @@ test("getCredentials throws error when credential missing host and url", async ( t.throws( () => startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, testCredential, undefined, @@ -239,7 +161,7 @@ test("getCredentials throws error when credential missing host and url", async ( test("getCredentials filters by language when specified", async (t) => { const credentials = startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, toEncodedJSON(mixedCredentials), BuiltInLanguage.java, @@ -250,7 +172,7 @@ test("getCredentials filters by language when specified", async (t) => { test("getCredentials returns all for a language when specified", async (t) => { const credentials = startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, toEncodedJSON([...mixedCredentials, gitSourceCredential]), BuiltInLanguage.go, @@ -270,7 +192,7 @@ test("getCredentials returns all goproxy_servers for Go when specified", async ( ]; const credentials = startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, toEncodedJSON(multipleGoproxyServers), BuiltInLanguage.go, @@ -299,7 +221,7 @@ test("getCredentials returns all maven_repositories for Java when specified", as ]; const credentials = startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, toEncodedJSON(multipleMavenRepositories), BuiltInLanguage.java, @@ -317,7 +239,7 @@ test("getCredentials returns all credentials when no language specified", async const credentialsInput = toEncodedJSON(mixedCredentials); const credentials = startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, credentialsInput, undefined, @@ -347,7 +269,7 @@ test("getCredentials throws an error when non-printable characters are used", as t.throws( () => startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, credentialsInput, undefined, @@ -378,7 +300,7 @@ for (const oidcSchemaInfo of startProxyExports.oidcSchemas) { t.throws( () => startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, credentialsInput, undefined, @@ -402,7 +324,7 @@ test("getCredentials accepts OIDC configurations", (t) => { ); const credentials = startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, toEncodedJSON(oidcConfigurations), BuiltInLanguage.csharp, @@ -592,7 +514,7 @@ test("getCredentials validates 'replaces-base' correctly", async (t) => { ]); const credentials = startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, credentialsInput, BuiltInLanguage.java, @@ -611,7 +533,7 @@ test("getCredentials validates 'replaces-base' correctly", async (t) => { }; t.throws(() => startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, toEncodedJSON([{ ...baseInvalid, "replaces-base": null }]), BuiltInLanguage.java, @@ -619,7 +541,7 @@ test("getCredentials validates 'replaces-base' correctly", async (t) => { ); t.throws(() => startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, toEncodedJSON([{ ...baseInvalid, "replaces-base": 123 }]), BuiltInLanguage.java, @@ -627,7 +549,7 @@ test("getCredentials validates 'replaces-base' correctly", async (t) => { ); t.throws(() => startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, toEncodedJSON([{ ...baseInvalid, "replaces-base": "true" }]), BuiltInLanguage.java, @@ -643,7 +565,7 @@ test("getCredentials returns only ALWAYS_ENABLED_REGISTRY_TYPE credentials for A ]); const credentials = startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, credentialsInput, BuiltInLanguage.actions, @@ -675,7 +597,7 @@ test("getCredentials always returns ALWAYS_ENABLED_REGISTRY_TYPE credentials for // Test all languages. for (const language of Object.values(BuiltInLanguage)) { const credentials = startProxyExports.getCredentials( - getRunnerLogger(true), + new RecordingLogger(), undefined, credentialsInput, language, @@ -685,6 +607,12 @@ test("getCredentials always returns ALWAYS_ENABLED_REGISTRY_TYPE credentials for } }); +test("getProxyPackage - includes platform in name", (t) => { + for (const platform of Object.values(BundlePlatform)) { + t.true(startProxyExports.getProxyPackage(platform).includes(platform)); + } +}); + function mockGetApiClient(endpoints: any) { return ( sinon @@ -696,18 +624,29 @@ function mockGetApiClient(endpoints: any) { type ReleaseAssets = Array<{ name: string; url?: string }>; -function mockGetReleaseByTag(assets?: ReleaseAssets) { +function mockGetReleaseByTag(expectedTag?: string, assets?: ReleaseAssets) { const getReleaseByTag = assets === undefined ? sinon.stub().rejects() - : sinon.stub().resolves({ - status: 200, - data: { assets }, - headers: {}, - url: "GET /repos/:owner/:repo/releases/tags/:tag", + : sinon.stub().callsFake(({ tag }) => { + if (tag === expectedTag) { + return { + status: 200, + data: { assets }, + headers: {}, + url: "GET /repos/:owner/:repo/releases/tags/:tag", + }; + } else { + return { + status: 404, + }; + } }); - return mockGetApiClient({ repos: { getReleaseByTag } }); + return { + getReleaseByTag, + getApiClient: mockGetApiClient({ repos: { getReleaseByTag } }), + }; } function mockOfflineFeatures(tempDir: string, logger: Logger) { @@ -721,51 +660,114 @@ function mockOfflineFeatures(tempDir: string, logger: Logger) { return setUpFeatureFlagTests(tempDir, logger, gitHubVersion); } +/** Gets the `BundlePlatform` based on the `action` state, but defaults to `Linux64` if undefined. */ +function getTestPlatform(action: ActionState<["Base"]>) { + return ( + getBundlePlatform(action.platform, action.arch) ?? BundlePlatform.Linux64 + ); +} + test.serial( - "getDownloadUrl returns fallback when `getReleaseByVersion` rejects", + "getDownloadUrl logs unknown platforms/arch and defaults to linux64", async (t) => { const logger = new RecordingLogger(); mockGetReleaseByTag(); await withTmpDir(async (tempDir) => { const features = mockOfflineFeatures(tempDir, logger); - const info = await startProxyExports.getDownloadUrl( - getRunnerLogger(true), + const state = initAllState({ + platform: "android", + arch: "ppc", + logger, features, + }); + + // Stub this to always return `true` so we get the default repo for the tests. + sinon.stub(actionsUtil, "isRunningLocalAction").returns(true); + + const info = await startProxyExports.getDownloadUrl( + state, + SAMPLE_DOTCOM_API_DETAILS, + ); + + t.true( + logger.hasMessage(`Unsupported platform android on architecture ppc`), ); - t.is(info.version, startProxyExports.UPDATEJOB_PROXY_VERSION); + t.is(info.version, defaults.cliVersion); t.is( info.url, - startProxyExports.getFallbackUrl(startProxyExports.getProxyPackage()), + repository.getDefaultDotcomDownloadURL( + defaults.bundleVersion, + startProxyExports.getProxyPackage(BundlePlatform.Linux64), + ), ); }); }, ); test.serial( - "getDownloadUrl returns fallback when there's no matching release asset", + "getDownloadUrl returns default bundle URL for linked version", + async (t) => { + const logger = new RecordingLogger(); + mockGetReleaseByTag(); + + await withTmpDir(async (tempDir) => { + const features = mockOfflineFeatures(tempDir, logger); + const state = initAllState({ logger, features }); + + // Stub this to always return `true` so we get the default repo for the tests. + sinon.stub(actionsUtil, "isRunningLocalAction").returns(true); + + const info = await startProxyExports.getDownloadUrl( + state, + SAMPLE_DOTCOM_API_DETAILS, + ); + + t.is(info.version, defaults.cliVersion); + t.is( + info.url, + repository.getDefaultDotcomDownloadURL( + defaults.bundleVersion, + startProxyExports.getProxyPackage(getTestPlatform(state)), + ), + ); + }); + }, +); + +test.serial( + "getDownloadUrl doesn't check that the default asset exists", async (t) => { const logger = new RecordingLogger(); const testAssets = [[], [{ name: "foo" }]]; await withTmpDir(async (tempDir) => { const features = mockOfflineFeatures(tempDir, logger); + const state = initAllState({ logger, features }); + + // Stub this to always return `true` so we get the default repo for the tests. + sinon.stub(actionsUtil, "isRunningLocalAction").returns(true); for (const assets of testAssets) { - const stub = mockGetReleaseByTag(assets); + const stubs = mockGetReleaseByTag(defaults.bundleVersion, assets); const info = await startProxyExports.getDownloadUrl( - getRunnerLogger(true), - features, + state, + SAMPLE_DOTCOM_API_DETAILS, ); - t.is(info.version, startProxyExports.UPDATEJOB_PROXY_VERSION); + t.is(info.version, defaults.cliVersion); t.is( info.url, - startProxyExports.getFallbackUrl(startProxyExports.getProxyPackage()), + repository.getDefaultDotcomDownloadURL( + defaults.bundleVersion, + startProxyExports.getProxyPackage(getTestPlatform(state)), + ), ); - stub.restore(); + // mockGetReleaseByTag stubs the global getApiClient; since we are calling + // that in a loop, we need to manually restore it here + stubs.getApiClient.restore(); } }); }, @@ -773,19 +775,31 @@ test.serial( test.serial("getDownloadUrl returns matching release asset", async (t) => { const logger = new RecordingLogger(); + const state = initAllState({ logger }); const assets = [ { name: "foo", url: "other-url" }, - { name: startProxyExports.getProxyPackage(), url: "url-we-want" }, + { + name: startProxyExports.getProxyPackage(getTestPlatform(state)), + url: "url-we-want", + }, ]; - mockGetReleaseByTag(assets); + const stubs = mockGetReleaseByTag(defaults.bundleVersion, assets); await withTmpDir(async (tempDir) => { + state.env.set(ActionsEnvVars.RUNNER_TEMP, tempDir); const features = mockOfflineFeatures(tempDir, logger); + + // Stub this to always return `false` so we force `getCodeQLAssetDownloadURL` to use the (mocked) API. + sinon.stub(actionsUtil, "isRunningLocalAction").returns(false); + state.env.set(ActionsEnvVars.GITHUB_ACTION_REPOSITORY, "test/repo"); + const info = await startProxyExports.getDownloadUrl( - getRunnerLogger(true), - features, + { ...state, features }, + SAMPLE_DOTCOM_API_DETAILS, ); + t.is(stubs.getReleaseByTag.callCount, 1); + t.is(info.version, defaults.cliVersion); t.is(info.url, "url-we-want"); }); @@ -917,14 +931,21 @@ test.serial( const toolcachePath = "/path/to/proxy/dir"; sinon.stub(toolcache, "find").returns(toolcachePath); + // Stub this to always return `true` so we get the default repo for the tests. + sinon.stub(actionsUtil, "isRunningLocalAction").returns(true); + const features = mockOfflineFeatures(tempDir, logger); - const path = await startProxyExports.getProxyBinaryPath(logger, features); + const result = await startProxyExports.getProxyBinaryPath( + initAllState({ logger, features }), + SAMPLE_DOTCOM_API_DETAILS, + ); - t.assert(path); + t.assert(result); t.is( - path, + result.path, filepath.join(toolcachePath, startProxyExports.getProxyFilename()), ); + t.is(result.version, defaults.cliVersion); }); }, ); @@ -933,18 +954,17 @@ test.serial( "getProxyBinaryPath - downloads proxy if not in cache", async (t) => { const logger = new RecordingLogger(); + const state = initAllState({ logger }); const downloadUrl = "url-we-want"; - mockGetReleaseByTag([ - { name: startProxyExports.getProxyPackage(), url: downloadUrl }, + const stubs = mockGetReleaseByTag(defaults.bundleVersion, [ + { + name: startProxyExports.getProxyPackage(getTestPlatform(state)), + url: downloadUrl, + }, ]); const toolcachePath = "/path/to/proxy/dir"; const find = sinon.stub(toolcache, "find").returns(""); - const getApiDetails = sinon.stub(apiClient, "getApiDetails").returns({ - auth: "", - url: "", - apiURL: "", - }); const getAuthorizationHeaderFor = sinon .stub(apiClient, "getAuthorizationHeaderFor") .returns(undefined); @@ -958,25 +978,36 @@ test.serial( .resolves(extractedPath); const cacheDir = sinon.stub(toolcache, "cacheDir").resolves(toolcachePath); - const path = await startProxyExports.getProxyBinaryPath( - logger, - createFeatures([]), + // Stub this to always return `false` so we force `getCodeQLAssetDownloadURL` to use the (mocked) API. + sinon.stub(actionsUtil, "isRunningLocalAction").returns(false); + state.env.set(ActionsEnvVars.GITHUB_ACTION_REPOSITORY, "test/repo"); + + const result = await startProxyExports.getProxyBinaryPath( + { + ...state, + features: createFeatures([]), + }, + SAMPLE_DOTCOM_API_DETAILS, ); + t.is(stubs.getReleaseByTag.callCount, 1); t.assert(find.calledOnce); - t.assert(getApiDetails.calledOnce); t.assert(getAuthorizationHeaderFor.calledOnce); - t.assert(downloadTool.calledOnceWith(downloadUrl)); - t.assert(extractTar.calledOnceWith(archivePath)); - t.assert(cacheDir.calledOnceWith(extractedPath)); - t.assert(path); + + const st = addSinonAssertions(t); + st.onceWith(downloadTool, downloadUrl); + st.onceWith(extractTar, archivePath); + st.onceWith(cacheDir, extractedPath); + + t.assert(result); t.is( - path, + result.path, filepath.join(toolcachePath, startProxyExports.getProxyFilename()), ); + t.is(result.version, defaults.cliVersion); checkExpectedLogMessages(t, logger.messages, [ - `Found '${startProxyExports.getProxyPackage()}' in release '${defaults.bundleVersion}' at '${downloadUrl}'`, + `Found private registry proxy ${startProxyExports.getProxyPackage(getTestPlatform(state))} in test/repo on https://github.com with URL ${downloadUrl}`, ]); }, ); @@ -985,16 +1016,18 @@ test.serial( "getProxyBinaryPath - downloads proxy based on features if not in cache", async (t) => { const logger = new RecordingLogger(); - const expectedTag = "codeql-bundle-v2.20.1"; + const state = initAllState({ logger }); + const expectedVersion = "2.20.1"; + const expectedTag = `codeql-bundle-v${expectedVersion}`; const expectedParams = { - owner: "github", - repo: "codeql-action", + owner: "test", + repo: "repo", tag: expectedTag, }; const downloadUrl = "url-we-want"; const assets = [ { - name: startProxyExports.getProxyPackage(), + name: startProxyExports.getProxyPackage(getTestPlatform(state)), url: downloadUrl, }, ]; @@ -1011,11 +1044,6 @@ test.serial( await withTmpDir(async (tempDir) => { const toolcachePath = "/path/to/proxy/dir"; const find = sinon.stub(toolcache, "find").returns(""); - const getApiDetails = sinon.stub(apiClient, "getApiDetails").returns({ - auth: "", - url: "", - apiURL: "", - }); const getAuthorizationHeaderFor = sinon .stub(apiClient, "getAuthorizationHeaderFor") .returns(undefined); @@ -1043,31 +1071,43 @@ test.serial( const getDefaultCliVersion = sinon .stub(features, "getEnabledDefaultCliVersions") .resolves({ - enabledVersions: [{ cliVersion: "2.20.1", tagName: expectedTag }], + enabledVersions: [ + { cliVersion: expectedVersion, tagName: expectedTag }, + ], }); - const path = await startProxyExports.getProxyBinaryPath(logger, features); - t.assert(getDefaultCliVersion.calledOnce); - sinon.assert.calledOnceWithMatch( - getReleaseByTag, - sinon.match(expectedParams), + // Stub this to always return `false` so we force `getCodeQLAssetDownloadURL` to use the (mocked) API. + sinon.stub(actionsUtil, "isRunningLocalAction").returns(false); + state.env.set(ActionsEnvVars.GITHUB_ACTION_REPOSITORY, "test/repo"); + + const result = await startProxyExports.getProxyBinaryPath( + { + ...state, + features, + }, + SAMPLE_DOTCOM_API_DETAILS, ); + + t.assert(getDefaultCliVersion.calledOnce); + + const st = addSinonAssertions(t); + st.onceWith(getReleaseByTag, expectedParams); t.assert(find.calledOnce); - t.assert(getApiDetails.calledOnce); t.assert(getAuthorizationHeaderFor.calledOnce); - t.assert(downloadTool.calledOnceWith(downloadUrl)); - t.assert(extractTar.calledOnceWith(archivePath)); - t.assert(cacheDir.calledOnceWith(extractedPath)); + st.onceWith(downloadTool, downloadUrl); + st.onceWith(extractTar, archivePath); + st.onceWith(cacheDir, extractedPath); - t.assert(path); + t.assert(result); t.is( - path, + result.path, filepath.join(toolcachePath, startProxyExports.getProxyFilename()), ); + t.is(result.version, expectedVersion); }); checkExpectedLogMessages(t, logger.messages, [ - `Found '${startProxyExports.getProxyPackage()}' in release '${expectedTag}' at '${downloadUrl}'`, + `Found private registry proxy ${startProxyExports.getProxyPackage(getTestPlatform(state))} in test/repo on https://github.com with URL url-we-want.`, ]); }, ); diff --git a/src/start-proxy.ts b/src/start-proxy.ts index caa1b3054a..f7b427e74d 100644 --- a/src/start-proxy.ts +++ b/src/start-proxy.ts @@ -1,16 +1,14 @@ import * as path from "path"; -import * as core from "@actions/core"; import * as toolcache from "@actions/tool-cache"; +import { ActionState } from "./action-common"; import { - getApiClient, - getApiDetails, getAuthorizationHeaderFor, getGitHubVersion, + GitHubApiDetails, } from "./api-client"; import * as artifactScanner from "./artifact-scanner"; -import { Config } from "./config-utils"; import * as defaults from "./defaults.json"; import { CodeQLDefaultVersionInfo, @@ -20,6 +18,12 @@ import { import * as json from "./json"; import { BuiltInLanguage } from "./languages"; import { Logger } from "./logging"; +import { BundlePlatform, getBundlePlatform } from "./platform"; +import { getCodeQLAssetDownloadURL } from "./setup/repository"; +import { + StartProxyError, + StartProxyErrorType, +} from "./start-proxy/status-report"; import { Address, Registry, @@ -30,149 +34,13 @@ import { RawCredential, } from "./start-proxy/types"; import { getAuthConfig } from "./start-proxy/validation"; -import { - ActionName, - createStatusReportBase, - getActionsStatus, - sendStatusReport, - StatusReportBase, -} from "./status-report"; -import * as util from "./util"; import { ConfigurationError, getErrorMessage, isDefined } from "./util"; export * from "./start-proxy/types"; +export * from "./start-proxy/status-report"; -/** - * Enumerates specific error types for which we have corresponding error messages that - * are safe to include in status reports. - */ -export enum StartProxyErrorType { - DownloadFailed, - ExtractionFailed, - CacheFailed, -} - -/** - * @returns The error message corresponding to the error type. - */ -export function getStartProxyErrorMessage( - errorType: StartProxyErrorType, -): string { - switch (errorType) { - case StartProxyErrorType.DownloadFailed: - return "Failed to download proxy archive."; - case StartProxyErrorType.ExtractionFailed: - return "Failed to extract proxy archive."; - case StartProxyErrorType.CacheFailed: - return "Failed to add proxy to toolcache"; - } -} - -/** - * We want to avoid accidentally leaking secrets that may be contained in exception - * messages in the `start-proxy` action. Consequently, we don't report the messages - * of arbitrary exceptions. This type of error ensures that the message is one from - * `StartProxyErrorType` and therefore safe to include in a status report. - */ -export class StartProxyError extends Error { - public readonly errorType: StartProxyErrorType; - - constructor(errorType: StartProxyErrorType) { - super(); - this.errorType = errorType; - } -} - -/** - * Sends a status report for the `start-proxy` action indicating a successful outcome. - * - * @param startedAt When the action was started. - * @param config The configuration used. - * @param registry_types The types of registries that are configured. - * @param logger The logger to use. - */ -export async function sendSuccessStatusReport( - startedAt: Date, - config: Partial, - registry_types: string[], - logger: Logger, -) { - const statusReportBase = await createStatusReportBase( - ActionName.StartProxy, - "success", - startedAt, - config, - await util.checkDiskUsage(logger), - logger, - ); - if (statusReportBase !== undefined) { - const statusReport: StatusReportBase = { - ...statusReportBase, - registry_types: registry_types.join(","), - }; - await sendStatusReport(statusReport); - } -} - -/** - * Returns an error message for `error` that can safely be reported in a status report, - * i.e. that does not contain sensitive information. - * - * @param error The error for which to get an error message. - */ -export function getSafeErrorMessage(error: Error): string { - // If the error is a `StartProxyError`, resolve the error type to the corresponding - // error message. - if (error instanceof StartProxyError) { - return getStartProxyErrorMessage(error.errorType); - } - - // Otherwise, omit the actual error message. - return `Error from start-proxy Action omitted (${error.constructor.name}).`; -} - -/** - * Sends a status report for the `start-proxy` action indicating a failure. - * - * @param logger The logger to use. - * @param startedAt When the action was started. - * @param language The language provided as input, if any. - * @param unwrappedError The exception that was thrown. - */ -export async function sendFailedStatusReport( - logger: Logger, - startedAt: Date, - language: BuiltInLanguage | undefined, - unwrappedError: unknown, -) { - const error = util.wrapError(unwrappedError); - core.setFailed(`start-proxy action failed: ${error.message}`); - - // To avoid the possibility of leaking sensitive information into the telemetry, - // we don't include arbitrary error messages. Instead, `getSafeErrorMessage` will - // return a generic message that includes the type of the error, unless it can decide - // that the message is safe to include. - const statusReportMessage = getSafeErrorMessage(error); - const errorStatusReportBase = await createStatusReportBase( - ActionName.StartProxy, - getActionsStatus(error), - startedAt, - { - languages: language === undefined ? undefined : [language], - }, - await util.checkDiskUsage(logger), - logger, - statusReportMessage, - ); - if (errorStatusReportBase !== undefined) { - await sendStatusReport(errorStatusReportBase); - } -} - +/** The basename of the proxy artifacts. */ export const UPDATEJOB_PROXY = "update-job-proxy"; -export const UPDATEJOB_PROXY_VERSION = "v2.0.20250624110901"; -const UPDATEJOB_PROXY_URL_PREFIX = - "https://github.com/github/codeql-action/releases/download/codeql-bundle-v2.22.0/"; function isPAT(value: string) { return artifactScanner.isAuthToken(value, [ @@ -370,39 +238,11 @@ export function getCredentials( /** * Gets the name of the proxy release asset for the current platform. - */ -export function getProxyPackage(): string { - const platform = - process.platform === "win32" - ? "win64" - : process.platform === "darwin" - ? "osx64" - : "linux64"; - return `${UPDATEJOB_PROXY}-${platform}.tar.gz`; -} - -/** - * Gets the fallback URL for downloading the proxy release asset. - * - * @param proxyPackage The asset name. - * @returns The full URL to download the specified asset from the fallback release. - */ -export function getFallbackUrl(proxyPackage: string): string { - return `${UPDATEJOB_PROXY_URL_PREFIX}${proxyPackage}`; -} - -/** - * Uses the GitHub API to obtain information about the CodeQL CLI bundle release - * that is tagged by `version`. * - * @returns The response from the GitHub API. + * @param platform The platform to get the asset name for. */ -async function getReleaseByVersion(version: string) { - return getApiClient().rest.repos.getReleaseByTag({ - owner: "github", - repo: "codeql-action", - tag: version, - }); +export function getProxyPackage(platform: BundlePlatform): string { + return `${UPDATEJOB_PROXY}-${platform}.tar.gz`; } /** Uses `features` to determine the default CLI version. */ @@ -417,62 +257,60 @@ async function getCliVersionFromFeatures( * Determines the URL of the proxy release asset that we should download if its not * already in the toolcache, and its version. * - * @param logger The logger to use. - * @param features Information about enabled features. + * @param action The action state. * @returns Returns the download URL and version of the proxy package we plan to use. */ export async function getDownloadUrl( - logger: Logger, - features: FeatureEnablement, + action: ActionState<["Base", "ReadOnlyEnv", "Logger", "FeatureFlags"]>, + apiDetails: GitHubApiDetails, ): Promise<{ url: string; version: string }> { - const proxyPackage = getProxyPackage(); + // Default to linux64 if we don't recognise the platform+arch pair. + // This maintains the behaviour we had before switching to `getBundlePlatform` here. + let platform = getBundlePlatform(action.platform, action.arch); + if (platform === undefined) { + action.logger.warning( + `Unsupported platform ${action.platform} on architecture ${action.arch}, defaulting to ${BundlePlatform.Linux64}`, + ); + platform = BundlePlatform.Linux64; + } + + const proxyPackage = getProxyPackage(platform); try { - const useFeaturesToDetermineCLI = await features.getValue( + const useFeaturesToDetermineCLI = await action.features.getValue( Feature.StartProxyUseFeaturesRelease, ); // Retrieve information about the CLI version we should use. This will be either the linked // version, or the one enabled by FFs. const versionInfo = useFeaturesToDetermineCLI - ? (await getCliVersionFromFeatures(features)).enabledVersions[0] + ? (await getCliVersionFromFeatures(action.features)).enabledVersions[0] : { cliVersion: defaults.cliVersion, tagName: defaults.bundleVersion, }; // Try to retrieve information about the CLI bundle release identified by `versionInfo`. - const cliRelease = await getReleaseByVersion(versionInfo.tagName); + const proxyAssetUrl = await getCodeQLAssetDownloadURL( + action, + apiDetails, + versionInfo.tagName, + proxyPackage, + "private registry proxy", + ); - // Search the release's assets to find the one we are looking for. - for (const asset of cliRelease.data.assets) { - if (asset.name === proxyPackage) { - logger.info( - `Found '${proxyPackage}' in release '${versionInfo.tagName}' at '${asset.url}'`, - ); - return { - url: asset.url, - // The `update-job-proxy` doesn't have a version as such. Since we now bundle it - // with CodeQL CLI bundle releases, we use the corresponding CLI version to - // differentiate between (potentially) different versions of `update-job-proxy`. - version: versionInfo.cliVersion, - }; - } - } + return { + url: proxyAssetUrl, + // The `update-job-proxy` doesn't have a version as such. Since we now bundle it + // with CodeQL CLI bundle releases, we use the corresponding CLI version to + // differentiate between (potentially) different versions of `update-job-proxy`. + version: versionInfo.cliVersion, + }; } catch (ex) { - logger.warning( + throw new Error( `Failed to retrieve information about the linked release: ${getErrorMessage(ex)}`, ); } - - // Fallback to the hard-coded URL. - logger.info( - `Did not find '${proxyPackage}' in the linked release, falling back to hard-coded version.`, - ); - return { - url: getFallbackUrl(proxyPackage), - version: UPDATEJOB_PROXY_VERSION, - }; } /** @@ -491,9 +329,14 @@ export async function downloadProxy( try { // Download the proxy archive from `url`. We let `downloadTool` choose where // to store it. The path to the downloaded file will be returned if successful. - return toolcache.downloadTool(url, /* dest: */ undefined, authorization, { - accept: "application/octet-stream", - }); + return await toolcache.downloadTool( + url, + /* dest: */ undefined, + authorization, + { + accept: "application/octet-stream", + }, + ); } catch (error) { logger.error( `Failed to download proxy archive from ${url}: ${getErrorMessage(error)}`, @@ -554,37 +397,70 @@ export function getProxyFilename() { : UPDATEJOB_PROXY; } +export type ProxyBinary = { + /** The path to the proxy binary to run. */ + path: string; + /** + * The version associated with the proxy binary. + * This usually corresponds to the CodeQL CLI release that the binary was obtained from. + */ + version: string; +}; + /** * Gets a path to the proxy binary. If possible, this function will find the proxy in the * runner's tool cache. Otherwise, it downloads and extracts the proxy binary, * and stores it in the tool cache. * - * @param logger The logger to use. - * @returns The path to the proxy binary. + * @param action The action state. + * @returns The path to the proxy binary and its version. */ export async function getProxyBinaryPath( - logger: Logger, - features: FeatureEnablement, -): Promise { - const proxyFileName = getProxyFilename(); - const proxyInfo = await getDownloadUrl(logger, features); - - let proxyBin = toolcache.find(proxyFileName, proxyInfo.version); - if (!proxyBin) { - const apiDetails = getApiDetails(); - const authorization = getAuthorizationHeaderFor( - logger, - apiDetails, - proxyInfo.url, - ); - const temp = await downloadProxy(logger, proxyInfo.url, authorization); - const extracted = await extractProxy(logger, temp); - proxyBin = await cacheProxy( - logger, - extracted, - proxyFileName, - proxyInfo.version, + action: ActionState<["Base", "ReadOnlyEnv", "Logger", "FeatureFlags"]>, + apiDetails: GitHubApiDetails, +): Promise { + const logger = action.logger; + logger.startGroup("Setting up authentication proxy"); + + try { + const proxyFileName = getProxyFilename(); + const proxyInfo = await getDownloadUrl(action, apiDetails); + + logger.info( + `Using authentication proxy from CodeQL release ${proxyInfo.version}.`, ); + + let proxyDir = toolcache.find(proxyFileName, proxyInfo.version); + + if (!proxyDir) { + logger.info( + `Authentication proxy is not in the toolcache. Will try to download it from '${proxyInfo.url}'.`, + ); + + const authorization = getAuthorizationHeaderFor( + logger, + apiDetails, + proxyInfo.url, + ); + const temp = await downloadProxy(logger, proxyInfo.url, authorization); + + logger.info(`Downloaded the authentication proxy asset to '${temp}'.`); + + const extracted = await extractProxy(logger, temp); + proxyDir = await cacheProxy( + logger, + extracted, + proxyFileName, + proxyInfo.version, + ); + + logger.info(`Extracted the authentication proxy to '${proxyDir}'.`); + } + return { + path: path.join(proxyDir, proxyFileName), + version: proxyInfo.version, + }; + } finally { + logger.endGroup(); } - return path.join(proxyBin, proxyFileName); } diff --git a/src/start-proxy/status-report.test.ts b/src/start-proxy/status-report.test.ts new file mode 100644 index 0000000000..c734783964 --- /dev/null +++ b/src/start-proxy/status-report.test.ts @@ -0,0 +1,136 @@ +import * as core from "@actions/core"; +import test, { ExecutionContext } from "ava"; +import sinon from "sinon"; + +import * as statusReport from "../status-report"; +import { + createTestConfig, + makeMacro, + RecordingLogger, + setupTests, + withRecordingLoggerAsync, +} from "../testing-utils"; +import { ConfigurationError } from "../util"; + +import * as startProxyExports from "./status-report"; + +setupTests(test); + +test.serial("sendSuccessStatusReport", async (t) => { + const logger = new RecordingLogger(); + const now = new Date(); + const config = createTestConfig({}); + const proxy_version = "1.2.3"; + const registry_types = ["git_source", "docker_registry"]; + + const createStatusReportBase = sinon.stub( + statusReport, + "createStatusReportBase", + ); + createStatusReportBase.resolves({ + action_name: statusReport.ActionName.StartProxy, + } as statusReport.StatusReportBase); + + const sendStatusReport = sinon + .stub(statusReport, "sendStatusReport") + .resolves(); + + await startProxyExports.sendSuccessStatusReport( + now, + config, + registry_types, + { proxy_version }, + logger, + ); + + t.is(createStatusReportBase.callCount, 1); + + t.is(sendStatusReport.callCount, 1); + t.is(sendStatusReport.args[0].length, 1); + + const arg = sendStatusReport.args[0][0]; + t.like(arg, { + action_name: statusReport.ActionName.StartProxy, + registry_types: "docker_registry,git_source", + start_proxy: { proxy_version }, + }); +}); + +const sendFailedStatusReportTest = makeMacro({ + exec: async ( + t: ExecutionContext, + err: Error, + expectedMessage: string, + expectedStatus: statusReport.ActionStatus = "failure", + ) => { + const now = new Date(); + + // Override core.setFailed to avoid it setting the program's exit code + sinon.stub(core, "setFailed").returns(); + + const createStatusReportBase = sinon.stub( + statusReport, + "createStatusReportBase", + ); + createStatusReportBase.resolves(undefined); + + await withRecordingLoggerAsync(async (logger) => { + await startProxyExports.sendFailedStatusReport( + logger, + now, + undefined, + err, + ); + + // Check that the stub has been called exactly once, with the expected arguments, + // but not with the message from the error. + sinon.assert.calledOnceWithExactly( + createStatusReportBase, + statusReport.ActionName.StartProxy, + expectedStatus, + now, + sinon.match.any, + sinon.match.any, + sinon.match.any, + expectedMessage, + ); + t.false( + createStatusReportBase.calledWith( + statusReport.ActionName.StartProxy, + expectedStatus, + now, + sinon.match.any, + sinon.match.any, + sinon.match.any, + sinon.match((msg: string) => msg.includes(err.message)), + ), + "createStatusReportBase was called with the error message", + ); + }); + }, + + title: (providedTitle = "") => `sendFailedStatusReport - ${providedTitle}`, +}); + +sendFailedStatusReportTest.serial( + "reports generic error message for non-StartProxyError error", + new Error("Something went wrong today"), + "Error from start-proxy Action omitted (Error).", +); + +sendFailedStatusReportTest.serial( + "reports generic error message for non-StartProxyError error with safe error message", + new Error( + startProxyExports.getStartProxyErrorMessage( + startProxyExports.StartProxyErrorType.DownloadFailed, + ), + ), + "Error from start-proxy Action omitted (Error).", +); + +sendFailedStatusReportTest.serial( + "reports generic error message for ConfigurationError error", + new ConfigurationError("Something went wrong today"), + "Error from start-proxy Action omitted (ConfigurationError).", + "user-error", +); diff --git a/src/start-proxy/status-report.ts b/src/start-proxy/status-report.ts new file mode 100644 index 0000000000..76ad3c8da3 --- /dev/null +++ b/src/start-proxy/status-report.ts @@ -0,0 +1,153 @@ +import * as core from "@actions/core"; + +import type { Config } from "../config-utils"; +import type { BuiltInLanguage } from "../languages"; +import type { Logger } from "../logging"; +import { + ActionName, + createStatusReportBase, + getActionsStatus, + sendStatusReport, + type StatusReportBase, +} from "../status-report"; +import * as util from "../util"; + +/** Additional status report data from `start-proxy`. */ +export interface StartProxyStatus { + proxy_version: string; +} + +/** The type of successful status reports from `start-proxy`. */ +type StartProxySuccessReport = StatusReportBase & { + start_proxy: StartProxyStatus; +}; + +/** + * Sends a status report for the `start-proxy` action indicating a successful outcome. + * + * @param startedAt When the action was started. + * @param config The configuration used. + * @param registry_types The types of registries that are configured. + * @param status Status information. + * @param logger The logger to use. + */ +export async function sendSuccessStatusReport( + startedAt: Date, + config: Partial, + registry_types: string[], + status: StartProxyStatus, + logger: Logger, +) { + const statusReportBase = await createStatusReportBase( + ActionName.StartProxy, + "success", + startedAt, + config, + await util.checkDiskUsage(logger), + logger, + ); + if (statusReportBase !== undefined) { + const statusReport: StartProxySuccessReport = { + ...statusReportBase, + registry_types: registry_types.sort().join(","), + start_proxy: status, + }; + await sendStatusReport(statusReport); + } +} + +/** + * Enumerates specific error types for which we have corresponding error messages that + * are safe to include in status reports. + */ +export enum StartProxyErrorType { + DownloadFailed, + ExtractionFailed, + CacheFailed, +} + +/** + * @returns The error message corresponding to the error type. + */ +export function getStartProxyErrorMessage( + errorType: StartProxyErrorType, +): string { + switch (errorType) { + case StartProxyErrorType.DownloadFailed: + return "Failed to download proxy archive."; + case StartProxyErrorType.ExtractionFailed: + return "Failed to extract proxy archive."; + case StartProxyErrorType.CacheFailed: + return "Failed to add proxy to toolcache"; + } +} + +/** + * We want to avoid accidentally leaking secrets that may be contained in exception + * messages in the `start-proxy` action. Consequently, we don't report the messages + * of arbitrary exceptions. This type of error ensures that the message is one from + * `StartProxyErrorType` and therefore safe to include in a status report. + */ +export class StartProxyError extends Error { + public readonly errorType: StartProxyErrorType; + + constructor(errorType: StartProxyErrorType) { + super(); + this.errorType = errorType; + } +} + +/** + * Returns an error message for `error` that can safely be reported in a status report, + * i.e. that does not contain sensitive information. + * + * @param error The error for which to get an error message. + */ +export function getSafeErrorMessage(error: Error): string { + // If the error is a `StartProxyError`, resolve the error type to the corresponding + // error message. + if (error instanceof StartProxyError) { + return getStartProxyErrorMessage(error.errorType); + } + + // Otherwise, omit the actual error message. + return `Error from start-proxy Action omitted (${error.constructor.name}).`; +} + +/** + * Sends a status report for the `start-proxy` action indicating a failure. + * + * @param logger The logger to use. + * @param startedAt When the action was started. + * @param language The language provided as input, if any. + * @param unwrappedError The exception that was thrown. + */ +export async function sendFailedStatusReport( + logger: Logger, + startedAt: Date, + language: BuiltInLanguage | undefined, + unwrappedError: unknown, +) { + const error = util.wrapError(unwrappedError); + core.setFailed(`start-proxy action failed: ${error.message}`); + + // To avoid the possibility of leaking sensitive information into the telemetry, + // we don't include arbitrary error messages. Instead, `getSafeErrorMessage` will + // return a generic message that includes the type of the error, unless it can decide + // that the message is safe to include. + const statusReportMessage = getSafeErrorMessage(error); + const errorStatusReportBase = await createStatusReportBase( + ActionName.StartProxy, + getActionsStatus(error), + startedAt, + { + languages: language === undefined ? undefined : [language], + }, + await util.checkDiskUsage(logger), + logger, + statusReportMessage, + ); + if (errorStatusReportBase !== undefined) { + await sendStatusReport(errorStatusReportBase); + } +} diff --git a/src/start-proxy/types.ts b/src/start-proxy/types.ts index 17803e9126..68bde2b4bb 100644 --- a/src/start-proxy/types.ts +++ b/src/start-proxy/types.ts @@ -175,11 +175,7 @@ export const oidcSchemas = [ /** Represents all supported OIDC configurations. */ export type OIDC = - | AzureConfig - | AWSConfig - | JFrogConfig - | CloudsmithConfig - | GCPConfig; + AzureConfig | AWSConfig | JFrogConfig | CloudsmithConfig | GCPConfig; /** All authentication-related fields. */ export type AuthConfig = UsernamePassword | Token | OIDC; diff --git a/src/status-report.test.ts b/src/status-report.test.ts index 2b763da700..004161efac 100644 --- a/src/status-report.test.ts +++ b/src/status-report.test.ts @@ -6,7 +6,6 @@ import * as actionsUtil from "./actions-util"; import { Config } from "./config-utils"; import { EnvVar, RegistryProxyVars } from "./environment"; import { BuiltInLanguage } from "./languages"; -import { getRunnerLogger } from "./logging"; import { ToolsSource } from "./setup-codeql"; import type { Registry } from "./start-proxy"; import { @@ -154,7 +153,7 @@ test.serial("createStatusReportBase", async (t) => { languages: [BuiltInLanguage.java, BuiltInLanguage.swift], }), { numAvailableBytes: 100, numTotalBytes: 500 }, - getRunnerLogger(false), + new RecordingLogger(), "failure cause", "exception stack trace", ); @@ -203,7 +202,7 @@ test.serial("createStatusReportBase - empty configuration", async (t) => { new Date("May 19, 2023 05:19:00"), {}, { numAvailableBytes: 100, numTotalBytes: 500 }, - getRunnerLogger(false), + new RecordingLogger(), ); if (t.truthy(statusReport)) { @@ -225,7 +224,7 @@ test.serial("createStatusReportBase - partial configuration", async (t) => { languages: ["go"], }, { numAvailableBytes: 100, numTotalBytes: 500 }, - getRunnerLogger(false), + new RecordingLogger(), ); if (t.truthy(statusReport)) { @@ -248,7 +247,7 @@ test.serial("createStatusReportBase_firstParty", async (t) => { new Date("May 19, 2023 05:19:00"), createTestConfig({}), { numAvailableBytes: 100, numTotalBytes: 500 }, - getRunnerLogger(false), + new RecordingLogger(), "failure cause", "exception stack trace", ) @@ -264,7 +263,7 @@ test.serial("createStatusReportBase_firstParty", async (t) => { new Date("May 19, 2023 05:19:00"), createTestConfig({}), { numAvailableBytes: 100, numTotalBytes: 500 }, - getRunnerLogger(false), + new RecordingLogger(), "failure cause", "exception stack trace", ) @@ -281,7 +280,7 @@ test.serial("createStatusReportBase_firstParty", async (t) => { new Date("May 19, 2023 05:19:00"), createTestConfig({}), { numAvailableBytes: 100, numTotalBytes: 500 }, - getRunnerLogger(false), + new RecordingLogger(), "failure cause", "exception stack trace", ) @@ -297,7 +296,7 @@ test.serial("createStatusReportBase_firstParty", async (t) => { new Date("May 19, 2023 05:19:00"), createTestConfig({}), { numAvailableBytes: 100, numTotalBytes: 500 }, - getRunnerLogger(false), + new RecordingLogger(), "failure cause", "exception stack trace", ) @@ -314,7 +313,7 @@ test.serial("createStatusReportBase_firstParty", async (t) => { new Date("May 19, 2023 05:19:00"), createTestConfig({}), { numAvailableBytes: 100, numTotalBytes: 500 }, - getRunnerLogger(false), + new RecordingLogger(), "failure cause", "exception stack trace", ) @@ -330,7 +329,7 @@ test.serial("createStatusReportBase_firstParty", async (t) => { new Date("May 19, 2023 05:19:00"), createTestConfig({}), { numAvailableBytes: 100, numTotalBytes: 500 }, - getRunnerLogger(false), + new RecordingLogger(), "failure cause", "exception stack trace", ) @@ -411,7 +410,7 @@ const testCreateInitWithConfigStatusReport = makeMacro({ new Date("May 19, 2023 05:19:00"), config, { numAvailableBytes: 100, numTotalBytes: 500 }, - getRunnerLogger(false), + new RecordingLogger(), "failure cause", "exception stack trace", ); diff --git a/src/status-report.ts b/src/status-report.ts index e61b04f9dd..9420aa2a10 100644 --- a/src/status-report.ts +++ b/src/status-report.ts @@ -14,14 +14,24 @@ import { isSelfHostedRunner, } from "./actions-util"; import { getAnalysisKey, getApiClient } from "./api-client"; -import { getCachedCodeQlVersion } from "./cli/output-cache"; +import { + getCachedCodeQlVersion, + getCommandCacheFilePath, +} from "./cli/output-cache"; import type { Config } from "./config/action-config"; import type { ComputedInput, InputName } from "./config/inputs"; import { parseRegistriesWithoutCredentials } from "./config/pack-registries"; import type { DependencyCacheRestoreStatusReport } from "./dependency-caching"; import { DocUrl } from "./doc-url"; -import { EnvVar, getEnv, ReadOnlyEnv, RegistryProxyVars } from "./environment"; +import { + EnvVar, + getEnv, + ReadOnlyEnv, + RegistryProxyVars, + exportEnvVar, +} from "./environment"; import { getRef } from "./git-utils"; +import { GITHUB_DOTCOM_URL } from "./github"; import * as json from "./json"; import type { Logger } from "./logging"; import type { OverlayBaseDatabaseDownloadStats } from "./overlay/caching"; @@ -32,7 +42,6 @@ import { ConfigurationError, getRequiredEnvParam, isInTestMode, - GITHUB_DOTCOM_URL, DiskUsage, assertNever, BuildMode, @@ -52,13 +61,21 @@ export enum ActionName { UploadSarif = "upload-sarif", } +/** A partial mapping from `ActionName` to names for actions whose display name is not the `ActionName` value. */ +export const ACTION_DISPLAY_NAMES: Partial> = { + [ActionName.Analyze]: "analyze", + [ActionName.InitPost]: "init post", +}; + /** - * Maps an `ActionName` to its display name. Usually that is the same, except - * for `ActionName.Analyze` where it is `"analyze"` instead of `"finish"`. + * Maps an {@link ActionName} to its display name. Usually that is the same, except + * for actions which have a different display name in {@link ACTION_DISPLAY_NAMES}. */ export function getDisplayActionName(actionName: ActionName): string { - if (actionName === ActionName.Analyze) { - return "analyze"; + const displayName = ACTION_DISPLAY_NAMES[actionName]; + + if (displayName !== undefined) { + return displayName; } return actionName; } @@ -68,9 +85,7 @@ export function getDisplayActionName(actionName: ActionName): string { * environment and returns it. * If a new UUID is generated, it is also exported as an environment variable. */ -export function getJobUUID( - action: ActionState<["Logger", "ReadOnlyEnv", "Actions"]>, -) { +export function getJobUUID(action: ActionState<["Logger", "Env", "Actions"]>) { // Check if we already have a UUID for the analysis and return it if so. const existingJobRunUuid = action.env.getOptional(EnvVar.JOB_RUN_UUID); @@ -83,7 +98,7 @@ export function getJobUUID( const jobRunUuid = uuid.v4(); action.logger.info(`Job run UUID is ${jobRunUuid}.`); - action.actions.exportVariable(EnvVar.JOB_RUN_UUID, jobRunUuid); + action.env.export(EnvVar.JOB_RUN_UUID, jobRunUuid); return jobRunUuid; } @@ -265,12 +280,12 @@ export function getJobStatusDisplayName(status: JobStatus): string { */ function setJobStatusIfUnsuccessful(actionStatus: ActionStatus) { if (actionStatus === "user-error") { - core.exportVariable( + exportEnvVar( EnvVar.JOB_STATUS, process.env[EnvVar.JOB_STATUS] ?? JobStatus.ConfigErrorStatus, ); } else if (actionStatus === "failure" || actionStatus === "aborted") { - core.exportVariable( + exportEnvVar( EnvVar.JOB_STATUS, process.env[EnvVar.JOB_STATUS] ?? JobStatus.FailureStatus, ); @@ -363,7 +378,7 @@ export async function createStatusReportBase( try { const commitOid = getOptionalInput("sha") || process.env["GITHUB_SHA"] || ""; - const ref = await getRef(); + const ref = await getRef(getEnv(), config?.repositoryRoot); const jobRunUUID = process.env[EnvVar.JOB_RUN_UUID] || ""; const workflowRunID = getWorkflowRunID(); const workflowRunAttempt = getWorkflowRunAttempt(); @@ -373,16 +388,19 @@ export async function createStatusReportBase( let workflowStartedAt = process.env[EnvVar.WORKFLOW_STARTED_AT]; if (workflowStartedAt === undefined) { workflowStartedAt = actionStartedAt.toISOString(); - core.exportVariable(EnvVar.WORKFLOW_STARTED_AT, workflowStartedAt); + exportEnvVar(EnvVar.WORKFLOW_STARTED_AT, workflowStartedAt); } const runnerOs = getRequiredEnvParam("RUNNER_OS"); - const codeQlCliVersion = getCachedCodeQlVersion(logger, getEnv()); + const codeQlCliVersion = getCachedCodeQlVersion( + logger, + getCommandCacheFilePath(getEnv()), + ); const actionRef = process.env["GITHUB_ACTION_REF"] || ""; const testingEnvironment = getTestingEnvironment(); // re-export the testing environment variable so that it is available to subsequent steps, // even if it was only set for this step if (testingEnvironment) { - core.exportVariable(EnvVar.TESTING_ENVIRONMENT, testingEnvironment); + exportEnvVar(EnvVar.TESTING_ENVIRONMENT, testingEnvironment); } const isSteadyStateDefaultSetupRun = process.env["CODE_SCANNING_IS_STEADY_STATE_DEFAULT_SETUP"] === "true"; @@ -618,16 +636,6 @@ export interface InitWithConfigStatusReport extends InitStatusReport { config_file: string; } -/** Fields of the init status report populated when the tools source is `download`. */ -export interface InitToolsDownloadFields { - /** Time taken to download the bundle, in milliseconds. */ - tools_download_duration_ms?: number; - /** - * Whether the relevant tools dotcom feature flags have been misconfigured. - * Only populated if we attempt to determine the default version based on the dotcom feature flags. */ - tools_feature_flags_valid?: boolean; -} - /** * Composes a `InitWithConfigStatusReport` from the given values. * diff --git a/src/status-report/tools-download.test.ts b/src/status-report/tools-download.test.ts new file mode 100644 index 0000000000..856bf882f6 --- /dev/null +++ b/src/status-report/tools-download.test.ts @@ -0,0 +1,80 @@ +import test from "ava"; + +import { BuiltInLanguage } from "../languages"; + +import { createInitToolsDownloadFields } from "./tools-download"; + +test("createInitToolsDownloadFields omits absent download data", (t) => { + t.deepEqual(createInitToolsDownloadFields(undefined, undefined), {}); +}); + +test("createInitToolsDownloadFields reports feature flags without a download", (t) => { + t.deepEqual(createInitToolsDownloadFields(undefined, false), { + tools_feature_flags_valid: false, + }); +}); + +test("createInitToolsDownloadFields reports only the total for a streaming download", (t) => { + t.deepEqual( + createInitToolsDownloadFields({ totalDurationMs: 300 }, undefined), + { tools_total_duration_ms: 300 }, + ); +}); + +test("createInitToolsDownloadFields preserves per-language metadata", (t) => { + t.deepEqual( + createInitToolsDownloadFields( + { + totalDurationMs: 300, + perLanguage: { tools_bundle_language: BuiltInLanguage.java }, + }, + true, + ), + { + tools_total_duration_ms: 300, + tools_bundle_language: BuiltInLanguage.java, + tools_feature_flags_valid: true, + }, + ); +}); + +test("createInitToolsDownloadFields preserves fallback and per-attempt timings", (t) => { + t.deepEqual( + createInitToolsDownloadFields( + { + downloadDurationMs: 200, + extractionDurationMs: 100, + totalDurationMs: 1000, + perLanguage: { tools_per_language_bundle_fallback: true }, + }, + undefined, + ), + { + tools_download_duration_ms: 200, + tools_extraction_duration_ms: 100, + tools_total_duration_ms: 1000, + tools_per_language_bundle_fallback: true, + }, + ); +}); + +test("createInitToolsDownloadFields preserves zero durations and false flags", (t) => { + t.deepEqual( + createInitToolsDownloadFields( + { + downloadDurationMs: 0, + extractionDurationMs: 0, + totalDurationMs: 0, + perLanguage: { tools_per_language_bundle_fallback: false }, + }, + false, + ), + { + tools_download_duration_ms: 0, + tools_extraction_duration_ms: 0, + tools_total_duration_ms: 0, + tools_per_language_bundle_fallback: false, + tools_feature_flags_valid: false, + }, + ); +}); diff --git a/src/status-report/tools-download.ts b/src/status-report/tools-download.ts new file mode 100644 index 0000000000..a5f7dffbf8 --- /dev/null +++ b/src/status-report/tools-download.ts @@ -0,0 +1,56 @@ +import type { ToolsDownloadStatusReport } from "../tools-download"; + +/** Telemetry describing per-language bundle downloads. */ +export interface PerLanguageToolsStatusReport { + /** The language of the single-language bundle that was downloaded, if any. */ + tools_bundle_language?: string; + /** + * Whether we tried to download a single-language bundle, but it did not exist and we fell back to + * the combined bundle. + */ + tools_per_language_bundle_fallback?: boolean; +} + +/** Fields of the init status report populated when the tools source is `download`. */ +export interface InitToolsDownloadFields extends PerLanguageToolsStatusReport { + /** + * Time taken to download the bundle, in milliseconds. Not populated when the bundle is downloaded + * and extracted concurrently. + */ + tools_download_duration_ms?: number; + /** + * Time taken to extract the bundle, in milliseconds. Not populated when the bundle is downloaded + * and extracted concurrently. + */ + tools_extraction_duration_ms?: number; + /** + * Total time taken to make the bundle available on disk, including failed download attempts + * before a fallback, in milliseconds. + */ + tools_total_duration_ms?: number; + /** + * Whether the relevant tools dotcom feature flags have been misconfigured. + * Only populated if we attempt to determine the default version based on the dotcom feature flags. */ + tools_feature_flags_valid?: boolean; +} + +/** Converts download results to telemetry fields shared by the init and setup-codeql Actions. */ +export function createInitToolsDownloadFields( + report: ToolsDownloadStatusReport | undefined, + toolsFeatureFlagsValid: boolean | undefined, +): InitToolsDownloadFields { + const fields: InitToolsDownloadFields = { ...report?.perLanguage }; + if (report?.downloadDurationMs !== undefined) { + fields.tools_download_duration_ms = report.downloadDurationMs; + } + if (report?.extractionDurationMs !== undefined) { + fields.tools_extraction_duration_ms = report.extractionDurationMs; + } + if (report?.totalDurationMs !== undefined) { + fields.tools_total_duration_ms = report.totalDurationMs; + } + if (toolsFeatureFlagsValid !== undefined) { + fields.tools_feature_flags_valid = toolsFeatureFlagsValid; + } + return fields; +} diff --git a/src/tar.test.ts b/src/tar.test.ts index 48f4e866d3..e193b2df44 100644 --- a/src/tar.test.ts +++ b/src/tar.test.ts @@ -3,9 +3,8 @@ import * as stream from "stream"; import test from "ava"; -import { getRunnerLogger } from "./logging"; import { extractTarZst } from "./tar"; -import { setupTests } from "./testing-utils"; +import { RecordingLogger, setupTests } from "./testing-utils"; import { withTmpDir } from "./util"; setupTests(test); @@ -16,8 +15,8 @@ test("extractTarZst rejects if the input stream errors", async (t) => { const promise = extractTarZst( archive, path.join(tmpDir, "dest"), - { type: "gnu", version: "1.34" }, - getRunnerLogger(true), + { type: "gnu", version: "1.34", path: "tar" }, + new RecordingLogger(), ); archive.destroy( diff --git a/src/tar.ts b/src/tar.ts index 3a0d79cc64..3497da5e5e 100644 --- a/src/tar.ts +++ b/src/tar.ts @@ -17,6 +17,8 @@ const MIN_REQUIRED_GNU_TAR_VERSION = "1.31"; export type TarVersion = { type: "gnu" | "bsd"; version: string; + /** Path to the `tar` executable that reported this version. */ + path: string; }; async function getTarVersion(): Promise { @@ -39,14 +41,14 @@ async function getTarVersion(): Promise { throw new Error("Failed to parse output of tar --version."); } - return { type: "gnu", version: match[1] }; + return { type: "gnu", version: match[1], path: tar }; } else if (stdout.includes("bsdtar")) { const match = stdout.match(/bsdtar ([0-9.]+)/); if (!match?.[1]) { throw new Error("Failed to parse output of tar --version."); } - return { type: "bsd", version: match[1] }; + return { type: "bsd", version: match[1], path: tar }; } else { throw new Error("Unknown tar version"); } @@ -171,10 +173,10 @@ export async function extractTarZst( args.push("-f", tar instanceof stream.Readable ? "-" : tar, "-C", dest); - process.stdout.write(`[command]tar ${args.join(" ")}\n`); + process.stdout.write(`[command]${tarVersion.path} ${args.join(" ")}\n`); await new Promise((resolve, reject) => { - const tarProcess = spawn("tar", args, { stdio: "pipe" }); + const tarProcess = spawn(tarVersion.path, args, { stdio: "pipe" }); let stdout = ""; tarProcess.stdout?.on("data", (data: Buffer) => { @@ -210,11 +212,11 @@ export async function extractTarZst( if (code !== 0) { reject( new CommandInvocationError( - "tar", + tarVersion.path, args, code ?? undefined, - stdout, stderr, + stdout, ), ); } diff --git a/src/testdata/pr-diff-range.yml b/src/testdata/pr-diff-range.yml index 073b83198a..24f02fbe3f 100644 --- a/src/testdata/pr-diff-range.yml +++ b/src/testdata/pr-diff-range.yml @@ -1,8 +1,7 @@ - extensions: - addsTo: pack: codeql/util extensible: restrictAlertsTo checkPresence: false data: - - ['/checkout/path/main.js', 10, 20] + - ["/checkout/path/main.js", 10, 20] diff --git a/src/testing-utils.ts b/src/testing-utils.ts index e4f26daa0f..d3b495363a 100644 --- a/src/testing-utils.ts +++ b/src/testing-utils.ts @@ -1,4 +1,5 @@ import { TextDecoder } from "node:util"; +import * as os from "os"; import path from "path"; import * as github from "@actions/github"; @@ -30,9 +31,11 @@ import { featureConfig, FeatureEnablement, } from "./feature-flags"; -import { Logger } from "./logging"; +import { joinMessageStrings, Loggable, LoggableError, Logger } from "./logging"; import { OverlayDatabaseMode } from "./overlay/overlay-database-mode"; +import { getBundlePlatform } from "./platform"; import { ActionName } from "./status-report"; +import { ToolsFeature } from "./tools-features"; import { DEFAULT_DEBUG_ARTIFACT_NAME, DEFAULT_DEBUG_DATABASE_NAME, @@ -162,6 +165,46 @@ export function setupTests(testFn: TestFn) { }); } +export interface AvaSinonAssertions { + /** + * Asserts that `stub` must have been called once with at least the `expected` arguments. + */ + onceWith: ( + stub: sinon.SinonStub, + ...expected: sinon.MatchPartialArguments + ) => boolean; +} + +/** Adds additional assertions for use with `sinon` to `t`. */ +export function addSinonAssertions( + t: ExecutionContext, +): ExecutionContext & AvaSinonAssertions { + return { + ...t, + onceWith: ( + stub: sinon.SinonStub, + ...expected: sinon.MatchPartialArguments + ) => { + // Fail if the stub hasn't been called at all so that we can safely compare + // the arguments of the first call in the else branch. + if (stub.callCount === 0) { + t.fail("The stub wasn't called."); + } else { + // Reduce the arguments of each to the same number that was provided, + // so that extra arguments don't lead to a failure. + const actual = stub.args.map>( + (args: TArgs) => + args.slice( + 0, + expected.length, + ) as sinon.MatchPartialArguments, + ); + return t.deepEqual(actual, [expected]); + } + }, + }; +} + /** * Declare a reusable test implementation, with better type safety than `test.macro`. */ @@ -201,10 +244,6 @@ class TestActionsEnv implements ActionsEnv { public getOptionalInput(_name: string): string | undefined { return undefined; } - - public exportVariable(name: string, value: string): void { - this.env.set(name, value); - } } /** @@ -233,6 +272,9 @@ export function initAllState( return { name: ActionName.Init, startedAt: new Date(), + platform: process.platform, + arch: process.arch, + osRelease: os.release(), logger: new RecordingLogger(), env, actions: getTestActionsEnv(env), @@ -446,10 +488,10 @@ export interface AssertableTarget { } class CallableEnvBuilder< - Args extends readonly any[], - R, - Fs extends ReadonlyArray, - > + Args extends readonly any[], + R, + Fs extends ReadonlyArray, +> extends BaseEnvBuilder implements AssertableTarget { @@ -619,12 +661,13 @@ export class RecordingLogger implements Logger { constructor(private readonly logToConsole: boolean = true) {} - private addMessage(level: LogLevel, message: string | Error): void { - this.messages.push({ type: level, message }); + private addMessage(level: LogLevel, message: LoggableError): void { + const joinedMessage = joinMessageStrings(message); + this.messages.push({ type: level, message: joinedMessage }); if (this.logToConsole) { // eslint-disable-next-line no-console - console.debug(message); + console.debug(joinedMessage); } } @@ -645,19 +688,19 @@ export class RecordingLogger implements Logger { return true; } - debug(message: string) { + debug(message: Loggable) { this.addMessage("debug", message); } - info(message: string) { + info(message: Loggable) { this.addMessage("info", message); } - warning(message: string | Error) { + warning(message: LoggableError) { this.addMessage("warning", message); } - error(message: string | Error) { + error(message: LoggableError) { this.addMessage("error", message); } @@ -871,7 +914,7 @@ export function mockLanguagesInRepo(languages: string[]) { */ export const makeVersionInfo = ( version: string, - features?: { [name: string]: boolean }, + features?: { [key in ToolsFeature]?: boolean }, overlayVersion?: number, ): VersionInfo => ({ version, @@ -933,19 +976,14 @@ export function mockBundleDownloadApi({ platformSpecific?: boolean; tagName: string; }): string { - const platform = - process.platform === "win32" - ? "win64" - : process.platform === "linux" - ? "linux64" - : "osx64"; + const platform = platformSpecific ? getBundlePlatform() : undefined; const baseUrl = apiDetails?.url ?? "https://example.com"; const bundleUrls = ["tar.gz", "tar.zst"].map((extension) => { const relativeUrl = apiDetails ? `/${repo}/releases/download/${tagName}/codeql-bundle${ - platformSpecific ? `-${platform}` : "" + platform !== undefined ? `-${platform}` : "" }.${extension}` : `/download/${tagName}/codeql-bundle.${extension}`; @@ -972,6 +1010,7 @@ export function createTestConfig(overrides: Partial): Config { {}, { version: getActionVersion(), + repositoryRoot: undefined, analysisKinds: [AnalysisKind.CodeScanning], languages: [], buildMode: undefined, @@ -996,6 +1035,7 @@ export function createTestConfig(overrides: Partial): Config { overlayModeSetExplicitly: false, repositoryProperties: {}, enableFileCoverageInformation: true, + successfullyInitialised: false, } satisfies Config, overrides, ); @@ -1006,3 +1046,16 @@ export function makeTestToken(length: number = 36) { "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return chars.repeat(Math.ceil(length / chars.length)).slice(0, length); } + +/** + * Get a real, newly created CodeQL instance for testing. The instance refers to + * a non-existent placeholder codeql command, so tests that use this function + * should also stub the toolrunner.ToolRunner constructor. + */ +export async function getCodeQLForTesting( + cmd = "codeql-for-testing", + logger: Logger = new RecordingLogger(), + env: Env = getEnv(), +): Promise { + return codeql.getCodeQLForCmd(logger, cmd, false, env); +} diff --git a/src/tools-download.test.ts b/src/tools-download.test.ts index 66fe0e72e4..9ba5bfd165 100644 --- a/src/tools-download.test.ts +++ b/src/tools-download.test.ts @@ -1,23 +1,27 @@ import { once } from "events"; +import * as fs from "fs"; +import { ClientRequest, IncomingMessage } from "http"; import * as path from "path"; +import * as core from "@actions/core"; import * as toolcache from "@actions/tool-cache"; import test from "ava"; +import { https } from "follow-redirects"; import nock from "nock"; import * as sinon from "sinon"; -import { getRunnerLogger } from "./logging"; +import * as errors from "./errors"; import * as tar from "./tar"; -import { setupTests } from "./testing-utils"; +import { RecordingLogger, setupTests } from "./testing-utils"; import { downloadAndExtract } from "./tools-download"; -import { withTmpDir } from "./util"; +import * as util from "./util"; setupTests(test); test.serial( - "downloadAndExtract reports the duration when downloading before extracting", + "downloadAndExtract reports the durations when downloading before extracting", async (t) => { - await withTmpDir(async (tmpDir) => { + await util.withTmpDir(async (tmpDir) => { const archivePath = path.join(tmpDir, "codeql-bundle.tar.gz"); const destination = path.join(tmpDir, "codeql"); sinon.stub(toolcache, "downloadTool").resolves(archivePath); @@ -30,10 +34,12 @@ test.serial( undefined, {}, undefined, - getRunnerLogger(true), + new RecordingLogger(), ); t.assert(Number.isInteger(statusReport.downloadDurationMs)); + t.assert(Number.isInteger(statusReport.extractionDurationMs)); + t.assert(Number.isInteger(statusReport.totalDurationMs)); }); }, ); @@ -41,13 +47,16 @@ test.serial( test.serial( "downloadAndExtract falls back to downloading before extracting if streaming fails", async (t) => { - await withTmpDir(async (tmpDir) => { + await util.withTmpDir(async (tmpDir) => { sinon.stub(process, "platform").value("linux"); const archivePath = path.join(tmpDir, "codeql-bundle.tar.zst"); const destination = path.join(tmpDir, "codeql"); const downloadTool = sinon .stub(toolcache, "downloadTool") - .resolves(archivePath); + .callsFake(async () => { + t.false(fs.existsSync(destination)); + return archivePath; + }); const extract = sinon.stub(tar, "extract").resolves(destination); const extractTarZst = sinon.stub(tar, "extractTarZst").resolves(); const request = nock("https://example.com") @@ -62,11 +71,12 @@ test.serial( destination, undefined, {}, - { type: "gnu", version: "1.34" }, - getRunnerLogger(true), + { type: "gnu", version: "1.34", path: "tar" }, + new RecordingLogger(), ); t.assert(Number.isInteger(statusReport.downloadDurationMs)); + t.assert(Number.isInteger(statusReport.totalDurationMs)); t.true(request.isDone()); t.false(extractTarZst.called); t.true(downloadTool.calledOnce); @@ -76,9 +86,133 @@ test.serial( ); test.serial( - "downloadAndExtract omits the download duration when streaming extraction", + "downloadAndExtract rethrows a 404 rather than retrying the download", + async (t) => { + await util.withTmpDir(async (tmpDir) => { + sinon.stub(process, "platform").value("linux"); + const destination = path.join(tmpDir, "codeql"); + const downloadTool = sinon.stub(toolcache, "downloadTool"); + const extractTarZst = sinon.stub(tar, "extractTarZst").resolves(); + const request = nock("https://example.com") + .get("/codeql-bundle.tar.zst") + .reply(404, "Not found"); + + const error = await t.throwsAsync( + downloadAndExtract( + "https://example.com/codeql-bundle.tar.zst", + "zstd", + destination, + undefined, + {}, + { type: "gnu", version: "1.34", path: "tar" }, + new RecordingLogger(), + ), + { + instanceOf: util.HTTPError, + message: + "Failed to download CodeQL bundle from https://example.com/codeql-bundle.tar.zst. HTTP status code: 404.", + }, + ); + + t.is(error?.status, 404); + t.true(request.isDone()); + t.false(extractTarZst.called); + t.false(downloadTool.called); + t.false(fs.existsSync(destination)); + }); + }, +); + +test.serial( + "downloadAndExtract falls back to downloading before extracting on a server error", + async (t) => { + await util.withTmpDir(async (tmpDir) => { + sinon.stub(process, "platform").value("linux"); + const archivePath = path.join(tmpDir, "codeql-bundle.tar.zst"); + const destination = path.join(tmpDir, "codeql"); + const downloadTool = sinon + .stub(toolcache, "downloadTool") + .callsFake(async () => { + t.false(fs.existsSync(destination)); + return archivePath; + }); + const extract = sinon.stub(tar, "extract").resolves(destination); + const extractTarZst = sinon.stub(tar, "extractTarZst").resolves(); + const request = nock("https://example.com") + .get("/codeql-bundle.tar.zst") + .reply(500); + + const statusReport = await downloadAndExtract( + "https://example.com/codeql-bundle.tar.zst", + "zstd", + destination, + undefined, + {}, + { type: "gnu", version: "1.34", path: "tar" }, + new RecordingLogger(), + ); + + t.assert(Number.isInteger(statusReport.downloadDurationMs)); + t.true(request.isDone()); + t.false(extractTarZst.called); + t.true(downloadTool.calledOnce); + t.true(extract.calledOnce); + }); + }, +); + +test.serial( + "downloadAndExtract handles an unknown status as a non-HTTP error", + async (t) => { + const asHTTPError = sinon.spy(errors, "asHTTPError"); + await util.withTmpDir(async (tmpDir) => { + sinon.stub(process, "platform").value("linux"); + const archivePath = path.join(tmpDir, "codeql-bundle.tar.zst"); + const destination = path.join(tmpDir, "codeql"); + const response = sinon.createStubInstance(IncomingMessage); + response.statusCode = undefined; + sinon + .stub(https, "get") + .callsArgWith(2, response) + .returns(sinon.createStubInstance(ClientRequest)); + const warning = sinon.stub(core, "warning"); + const downloadTool = sinon + .stub(toolcache, "downloadTool") + .resolves(archivePath); + const extract = sinon.stub(tar, "extract").resolves(destination); + const extractTarZst = sinon.stub(tar, "extractTarZst").resolves(); + + await downloadAndExtract( + "https://example.com/codeql-bundle.tar.zst", + "zstd", + destination, + undefined, + {}, + { type: "gnu", version: "1.34", path: "tar" }, + new RecordingLogger(), + ); + + t.is( + warning.firstCall.args[0], + "Failed to download and extract CodeQL bundle using streaming with error: Failed to download CodeQL bundle from https://example.com/codeql-bundle.tar.zst.", + ); + t.true(response.resume.calledOnce); + t.false(extractTarZst.called); + t.true(downloadTool.calledOnce); + t.true(extract.calledOnce); + }); + + t.true(asHTTPError.calledOnce); + t.true(asHTTPError.firstCall.args[0] instanceof Error); + t.false(asHTTPError.firstCall.args[0] instanceof util.HTTPError); + t.is(asHTTPError.firstCall.returnValue, undefined); + }, +); + +test.serial( + "downloadAndExtract reports only the total duration when streaming extraction", async (t) => { - await withTmpDir(async (tmpDir) => { + await util.withTmpDir(async (tmpDir) => { sinon.stub(process, "platform").value("linux"); const downloadTool = sinon.stub(toolcache, "downloadTool"); const extractTarZst = sinon @@ -102,11 +236,13 @@ test.serial( path.join(tmpDir, "codeql"), undefined, {}, - { type: "gnu", version: "1.34" }, - getRunnerLogger(true), + { type: "gnu", version: "1.34", path: "tar" }, + new RecordingLogger(), ); - t.deepEqual(statusReport, {}); + t.assert(Number.isInteger(statusReport.totalDurationMs)); + t.is(statusReport.downloadDurationMs, undefined); + t.is(statusReport.extractionDurationMs, undefined); t.false(downloadTool.called); t.true(extractTarZst.calledOnce); t.true(request.isDone()); diff --git a/src/tools-download.ts b/src/tools-download.ts index 9b2fa8723a..a92dad0acf 100644 --- a/src/tools-download.ts +++ b/src/tools-download.ts @@ -10,9 +10,19 @@ import * as toolcache from "@actions/tool-cache"; import { https } from "follow-redirects"; import * as semver from "semver"; +import { ActionState } from "./action-common"; +import { ActionsEnvVars, getEnv, ReadOnlyEnv } from "./environment"; import { formatDuration, Logger } from "./logging"; +import type { PerLanguageToolsStatusReport } from "./status-report/tools-download"; import * as tar from "./tar"; -import { cleanUpPath, getErrorMessage, getRequiredEnvParam } from "./util"; +import { + asHTTPError, + cleanUpPath, + durationMsSince, + getErrorMessage, + getRequiredEnvParam, + HTTPError, +} from "./util"; /** * High watermark to use when streaming the download and extraction of the CodeQL tools. @@ -31,7 +41,22 @@ const STREAMING_STALL_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes const TOOLCACHE_TOOL_NAME = "CodeQL"; export type ToolsDownloadStatusReport = { + /** + * Time spent downloading the bundle, in milliseconds. Not populated when the bundle is downloaded + * and extracted concurrently, since the two cannot be told apart. + */ downloadDurationMs?: number; + /** + * Time spent extracting the bundle, in milliseconds. Not populated when the bundle is downloaded + * and extracted concurrently, since the two cannot be told apart. + */ + extractionDurationMs?: number; + /** + * Total time taken to make the bundle available on disk, including failed download attempts + * before a fallback, in milliseconds. + */ + totalDurationMs: number; + perLanguage?: PerLanguageToolsStatusReport; }; export async function downloadAndExtract( @@ -47,11 +72,12 @@ export async function downloadAndExtract( `Downloading CodeQL tools from ${codeqlURL} . This may take a while.`, ); + const startTime = performance.now(); + try { if (compressionMethod === "zstd" && process.platform === "linux") { logger.info(`Streaming the extraction of the CodeQL bundle.`); - const toolsInstallStart = performance.now(); await downloadAndExtractZstdWithStreaming( codeqlURL, dest, @@ -61,26 +87,30 @@ export async function downloadAndExtract( logger, ); - const combinedDurationMs = Math.round( - performance.now() - toolsInstallStart, - ); + const totalDurationMs = durationMsSince(startTime); logger.info( `Finished downloading and extracting CodeQL bundle to ${dest} (${formatDuration( - combinedDurationMs, + totalDurationMs, )}).`, ); - return {}; + return { totalDurationMs }; } } catch (e) { + // If we failed during processing, we want to clean up the destination directory + // before we either try again or give up. + await cleanUpPath(dest, "CodeQL bundle", logger); + + // Retrying a 404 is pointless: the asset does not exist, so downloading it a different way + // will fail in the same way. + if (asHTTPError(e)?.status === 404) { + throw e; + } + core.warning( `Failed to download and extract CodeQL bundle using streaming with error: ${getErrorMessage(e)}`, ); core.warning(`Falling back to downloading the bundle before extracting.`); - - // If we failed during processing, we want to clean up the destination directory - // before we try again. - await cleanUpPath(dest, "CodeQL bundle", logger); } const toolsDownloadStart = performance.now(); @@ -90,7 +120,7 @@ export async function downloadAndExtract( authorization, headers, ); - const downloadDurationMs = Math.round(performance.now() - toolsDownloadStart); + const downloadDurationMs = durationMsSince(toolsDownloadStart); logger.info( `Finished downloading CodeQL bundle to ${archivedBundlePath} (${formatDuration( @@ -98,7 +128,7 @@ export async function downloadAndExtract( )}).`, ); - let extractionDurationMs: number; + let extractionDurationMs: number | undefined; try { logger.info("Extracting CodeQL bundle."); @@ -110,7 +140,7 @@ export async function downloadAndExtract( tarVersion, logger, ); - extractionDurationMs = Math.round(performance.now() - extractionStart); + extractionDurationMs = durationMsSince(extractionStart); logger.info( `Finished extracting CodeQL bundle to ${dest} (${formatDuration( extractionDurationMs, @@ -120,7 +150,11 @@ export async function downloadAndExtract( await cleanUpPath(archivedBundlePath, "CodeQL bundle archive", logger); } - return { downloadDurationMs }; + return { + downloadDurationMs, + extractionDurationMs, + totalDurationMs: durationMsSince(startTime), + }; } async function downloadAndExtractZstdWithStreaming( @@ -172,24 +206,167 @@ async function downloadAndExtractZstdWithStreaming( if (response.statusCode !== 200) { // Discard the response body so that the connection can be released. response.resume(); - throw new Error( - `Failed to download CodeQL bundle from ${codeqlURL}. HTTP status code: ${response.statusCode}.`, - ); + const baseMessage = `Failed to download CodeQL bundle from ${codeqlURL}.`; + if (response.statusCode !== undefined) { + throw new HTTPError( + `${baseMessage} HTTP status code: ${response.statusCode}.`, + response.statusCode, + ); + } + throw new Error(baseMessage); } await tar.extractTarZst(response, dest, tarVersion, logger); } +/** Gets the path to the toolcache directory that holds all versions of the CodeQL tools. */ +function getToolcacheToolDirectory(env: ReadOnlyEnv): string { + return path.join( + env.getRequired(ActionsEnvVars.RUNNER_TOOL_CACHE), + TOOLCACHE_TOOL_NAME, + ); +} + +/** Gets the name of the toolcache directory that holds the given version of the CodeQL tools. */ +function getToolcacheVersionDirectoryName(version: string): string { + return semver.clean(version) || version; +} + /** Gets the path to the toolcache directory for the specified version of the CodeQL tools. */ export function getToolcacheDirectory(version: string): string { return path.join( - getRequiredEnvParam("RUNNER_TOOL_CACHE"), - TOOLCACHE_TOOL_NAME, - semver.clean(version) || version, + getToolcacheToolDirectory(getEnv()), + getToolcacheVersionDirectoryName(version), os.arch() || "", ); } +/** + * Whether the toolcache is on the same filesystem as the workspace, and so whether deleting the + * tools frees up disk space that the analysis can use. + * + * These are separate volumes on some runner images. Windows runners, for example, keep the + * toolcache on `C:` while the workspace is on `D:`. + */ +export function isToolcacheOnWorkspaceFilesystem(logger: Logger): boolean { + try { + return ( + fs.statSync(getRequiredEnvParam("RUNNER_TOOL_CACHE")).dev === + fs.statSync(getRequiredEnvParam("GITHUB_WORKSPACE")).dev + ); + } catch (e) { + logger.debug( + `Could not determine whether the toolcache is on the same filesystem as the workspace: ${getErrorMessage(e)}`, + ); + return false; + } +} + +/** The outcome of trying to reclaim disk space by deleting the CodeQL tools from the toolcache. */ +export interface ToolcacheCleanupResult { + /** The versions of the CodeQL tools that were deleted. */ + deletedVersions: string[]; + /** + * Whether we hit an error while trying to delete the tools. Distinguishes a toolcache that had + * nothing to reclaim from one we failed to clean up. + */ + failed: boolean; +} + +/** + * Deletes every version of the CodeQL tools from the toolcache. + * + * Only safe to call when we are about to download the tools, since that means we did not resolve + * them from the toolcache and so nothing in there is in use by this job. + * + * This only ever touches the CodeQL directory of the toolcache. Cleanup errors are logged and + * returned as `failed: true` rather than thrown. + * + * @returns the versions that were deleted, and whether we hit an error while trying. + */ +export async function deleteToolcacheBundles({ + env, + logger, +}: ActionState<["Logger", "ReadOnlyEnv"]>): Promise { + let toolDirectory: string; + + try { + toolDirectory = getToolcacheToolDirectory(env); + } catch (e) { + logger.info( + `Unable to determine toolcache directory: ${getErrorMessage(e)}`, + ); + return { deletedVersions: [], failed: true }; + } + + try { + // Refuse to follow a symlinked CodeQL directory, so that we can only ever delete paths that are + // really inside the toolcache. + if ((await fs.promises.lstat(toolDirectory)).isSymbolicLink()) { + logger.info( + `Not deleting the CodeQL tools from the toolcache since '${toolDirectory}' is a symlink.`, + ); + return { deletedVersions: [], failed: true }; + } + } catch (e: any) { + if (e?.code === "ENOENT") { + logger.debug( + `There are no CodeQL tools at '${toolDirectory}' to delete from the toolcache.`, + ); + return { deletedVersions: [], failed: false }; + } + logger.info( + `Failed to inspect the CodeQL tools at '${toolDirectory}': ${getErrorMessage(e)}`, + ); + return { deletedVersions: [], failed: true }; + } + + try { + const entries = await fs.promises.readdir(toolDirectory, { + withFileTypes: true, + }); + + const deletedVersions: string[] = []; + let failed = false; + + for (const entry of entries) { + // `isDirectory` is false for a symlink, so we never delete a version directory that is + // really somewhere else. + if (!entry.isDirectory()) { + logger.debug( + `Not deleting '${entry.name}' from the CodeQL toolcache since it is not a directory.`, + ); + continue; + } + + const versionDirectory = path.join(toolDirectory, entry.name); + + try { + await fs.promises.rm(versionDirectory, { + force: true, + recursive: true, + }); + deletedVersions.push(entry.name); + logger.info( + `Deleted the CodeQL tools at '${versionDirectory}' from the toolcache to free up disk space.`, + ); + } catch (e) { + failed = true; + logger.info( + `Failed to delete the CodeQL tools at '${versionDirectory}' from the toolcache: ${getErrorMessage(e)}`, + ); + } + } + + return { deletedVersions: deletedVersions.sort(), failed }; + } catch (e) { + logger.info( + `Failed to clean up the CodeQL toolcache at '${toolDirectory}': ${getErrorMessage(e)}`, + ); + return { deletedVersions: [], failed: true }; + } +} + export function writeToolcacheMarkerFile( extractedPath: string, logger: Logger, diff --git a/src/tools-features.ts b/src/tools-features.ts index 4931be65ba..84dc1d0f44 100644 --- a/src/tools-features.ts +++ b/src/tools-features.ts @@ -1,5 +1,3 @@ -import * as semver from "semver"; - import type { VersionInfo } from "./cli/types"; export enum ToolsFeature { @@ -8,6 +6,7 @@ export enum ToolsFeature { BundleSupportsOverlay = "bundleSupportsOverlay", IndirectTracingSupportsStaticBinaries = "indirectTracingSupportsStaticBinaries", SuppressesMissingFileBaselineWarning = "suppressesMissingFileBaselineWarning", + SwiftSupportsAllPlatforms = "swiftSupportsAllPlatforms", } /** @@ -23,21 +22,3 @@ export function isSupportedToolsFeature( ): boolean { return !!versionInfo.features && versionInfo.features[feature]; } - -export const SafeArtifactUploadVersion = "2.20.3"; - -/** - * The first version of the CodeQL CLI where artifact upload is safe to use - * for failed runs. This is not really a feature flag, but it is easiest to - * model the behavior as a feature flag. - * - * This was not captured in a tools feature, so we need to use semver. - * - * @param codeQlVersion The version of the CodeQL CLI to check. If not provided, it is assumed to be safe. - * @returns True if artifact upload is safe to use for failed runs or false otherwise. - */ -export function isSafeArtifactUpload(codeQlVersion?: string): boolean { - return !codeQlVersion - ? true - : semver.gte(codeQlVersion, SafeArtifactUploadVersion); -} diff --git a/src/tracer-config.test.ts b/src/tracer-config.test.ts index 58f844b8e7..f410d47c16 100644 --- a/src/tracer-config.test.ts +++ b/src/tracer-config.test.ts @@ -4,10 +4,16 @@ import * as path from "path"; import test from "ava"; import * as sinon from "sinon"; -import { CodeQL, getCodeQLForTesting } from "./codeql"; +import type { CodeQL } from "./codeql"; import * as configUtils from "./config-utils"; import { BuiltInLanguage } from "./languages"; -import { createTestConfig, makeVersionInfo, setupTests } from "./testing-utils"; +import { + createTestConfig, + getCodeQLForTesting, + makeVersionInfo, + RecordingLogger, + setupTests, +} from "./testing-utils"; import { ToolsFeature } from "./tools-features"; import { getCombinedTracerConfig } from "./tracer-config"; import * as util from "./util"; @@ -42,18 +48,20 @@ async function stubCodeql( } test("getCombinedTracerConfig - return undefined when no languages are traced languages", async (t) => { + const logger = new RecordingLogger(); await util.withTmpDir(async (tmpDir) => { const config = getTestConfig(tmpDir); // No traced languages config.languages = [BuiltInLanguage.javascript, BuiltInLanguage.python]; t.deepEqual( - await getCombinedTracerConfig(await stubCodeql(), config), + await getCombinedTracerConfig(logger, await stubCodeql(), config), undefined, ); }); }); test("getCombinedTracerConfig", async (t) => { + const logger = new RecordingLogger(); await util.withTmpDir(async (tmpDir) => { const config = getTestConfig(tmpDir); @@ -82,7 +90,11 @@ test("getCombinedTracerConfig", async (t) => { ); fs.writeFileSync(startTracingJson, JSON.stringify(startTracingEnv)); - const result = await getCombinedTracerConfig(await stubCodeql(), config); + const result = await getCombinedTracerConfig( + logger, + await stubCodeql(), + config, + ); t.notDeepEqual(result, undefined); t.false(Object.prototype.hasOwnProperty.call(result?.env, "CODEQL_RUNNER")); diff --git a/src/tracer-config.ts b/src/tracer-config.ts index d786d46515..33c5b64fc6 100644 --- a/src/tracer-config.ts +++ b/src/tracer-config.ts @@ -4,7 +4,7 @@ import * as path from "path"; import { type CodeQL } from "./codeql"; import { type Config } from "./config-utils"; import { Logger } from "./logging"; -import { asyncSome, BuildMode } from "./util"; +import { asyncSome, BuildMode, getErrorMessage } from "./util"; export type TracerConfig = { env: { [key: string]: string }; @@ -77,23 +77,28 @@ export async function endTracingForCluster( } async function getTracerConfigForCluster( + logger: Logger, config: Config, ): Promise { - const tracingEnvVariables = JSON.parse( - fs.readFileSync( - path.resolve( - config.dbLocation, - "temp/tracingEnvironment/start-tracing.json", - ), - "utf8", - ), + const filePath = path.resolve( + config.dbLocation, + "temp/tracingEnvironment/start-tracing.json", ); - return { - env: tracingEnvVariables, - }; + try { + const tracingEnvVariables = JSON.parse(fs.readFileSync(filePath, "utf8")); + return { + env: tracingEnvVariables, + }; + } catch (err) { + logger.error( + `Failed to parse tracing environment from '${filePath}': ${getErrorMessage(err)}`, + ); + throw new Error(`Failed to parse tracing environment from '${filePath}'.`); + } } export async function getCombinedTracerConfig( + logger: Logger, codeql: CodeQL, config: Config, ): Promise { @@ -101,5 +106,5 @@ export async function getCombinedTracerConfig( return undefined; } - return await getTracerConfigForCluster(config); + return await getTracerConfigForCluster(logger, config); } diff --git a/src/trap-caching.test.ts b/src/trap-caching.test.ts index 478305e577..99dc59706e 100644 --- a/src/trap-caching.test.ts +++ b/src/trap-caching.test.ts @@ -6,29 +6,26 @@ import test from "ava"; import * as sinon from "sinon"; import * as actionsUtil from "./actions-util"; -import * as apiClient from "./api-client"; import { getTrapCachingExtractorConfigArgs, getTrapCachingExtractorConfigArgsForLang, createStubCodeQL, } from "./codeql"; import * as configUtils from "./config-utils"; -import { Feature } from "./feature-flags"; import * as gitUtils from "./git-utils"; import { BuiltInLanguage } from "./languages"; -import { getRunnerLogger } from "./logging"; import { - createFeatures, + callee, createTestConfig, getRecordingLogger, makeVersionInfo, setupTests, } from "./testing-utils"; import { - cleanupTrapCaches, downloadTrapCaches, getLanguagesSupportingCaching, uploadTrapCaches, + warnIfTrapCacheCleanupEnvVarIsSet, } from "./trap-caching"; import * as util from "./util"; @@ -182,6 +179,7 @@ test.serial( stubCodeql, [BuiltInLanguage.javascript, BuiltInLanguage.cpp], logger, + undefined, ); t.assert( stubRestore.calledOnceWith( @@ -199,83 +197,27 @@ test.serial( }, ); -test.serial("cleanup removes only old CodeQL TRAP caches", async (t) => { - await util.withTmpDir(async (tmpDir) => { - // This config specifies that we are analyzing JavaScript and Ruby, but not Swift. - const config = getTestConfigWithTempDir(tmpDir); - - sinon.stub(gitUtils, "getRef").resolves("refs/heads/main"); - sinon.stub(gitUtils, "isAnalyzingDefaultBranch").resolves(true); - const listStub = sinon.stub(apiClient, "listActionsCaches").resolves([ - // Should be kept, since it's not relevant to CodeQL. In reality, the API shouldn't return - // this in the first place, but this is a defensive check. - { - id: 1, - key: "some-other-key", - created_at: "2024-05-23T14:25:00Z", - size_in_bytes: 100 * 1024 * 1024, - }, - // Should be kept, since it's the newest TRAP cache for JavaScript - { - id: 2, - key: "codeql-trap-1-2.0.0-javascript-newest", - created_at: "2024-04-23T14:25:00Z", - size_in_bytes: 50 * 1024 * 1024, - }, - // Should be cleaned up - { - id: 3, - key: "codeql-trap-1-2.0.0-javascript-older", - created_at: "2024-03-22T14:25:00Z", - size_in_bytes: 200 * 1024 * 1024, - }, - // Should be cleaned up - { - id: 4, - key: "codeql-trap-1-2.0.0-javascript-oldest", - created_at: "2024-02-21T14:25:00Z", - size_in_bytes: 300 * 1024 * 1024, - }, - // Should be kept, since it's the newest TRAP cache for Ruby - { - id: 5, - key: "codeql-trap-1-2.0.0-ruby-newest", - created_at: "2024-02-20T14:25:00Z", - size_in_bytes: 300 * 1024 * 1024, - }, - // Should be kept, since we aren't analyzing Swift - { - id: 6, - key: "codeql-trap-1-2.0.0-swift-newest", - created_at: "2024-02-22T14:25:00Z", - size_in_bytes: 300 * 1024 * 1024, - }, - // Should be kept, since we aren't analyzing Swift - { - id: 7, - key: "codeql-trap-1-2.0.0-swift-older", - created_at: "2024-02-21T14:25:00Z", - size_in_bytes: 300 * 1024 * 1024, - }, - ]); - - const deleteStub = sinon.stub(apiClient, "deleteActionsCache").resolves(); - - const statusReport = await cleanupTrapCaches( - config, - createFeatures([Feature.CleanupTrapCaches]), - getRunnerLogger(true), +// `CODEQL_ACTION_CLEANUP_TRAP_CACHES` has no effect with either value, so we warn even when it's +// set to `false`. +for (const value of ["true", "false"]) { + test(`warnIfTrapCacheCleanupEnvVarIsSet warns when CODEQL_ACTION_CLEANUP_TRAP_CACHES is '${value}'`, async (t) => { + const target = callee(warnIfTrapCacheCleanupEnvVarIsSet) + .withEnv((env) => env.set("CODEQL_ACTION_CLEANUP_TRAP_CACHES", value)) + .withArgs() + .logs( + t, + "CODEQL_ACTION_CLEANUP_TRAP_CACHES environment variable no longer has any effect", + ); + await target.passes(t.is, undefined); + t.deepEqual( + target.getLogger().messages.map((m) => m.type), + ["warning"], ); - - t.is(listStub.callCount, 1); - t.assert(listStub.calledWithExactly("codeql-trap", "refs/heads/main")); - - t.deepEqual(statusReport, { - trap_cache_cleanup_size_bytes: 500 * 1024 * 1024, - }); - - t.is(deleteStub.callCount, 2); - t.assert(deleteStub.calledWithExactly(3)); - t.assert(deleteStub.calledWithExactly(4)); }); +} + +test("warnIfTrapCacheCleanupEnvVarIsSet doesn't warn when CODEQL_ACTION_CLEANUP_TRAP_CACHES is unset", async (t) => { + const target = callee(warnIfTrapCacheCleanupEnvVarIsSet).withArgs(); + await target.passes(t.is, undefined); + t.deepEqual(target.getLogger().messages, []); }); diff --git a/src/trap-caching.ts b/src/trap-caching.ts index a802aac892..58d96890f5 100644 --- a/src/trap-caching.ts +++ b/src/trap-caching.ts @@ -3,21 +3,14 @@ import * as path from "path"; import * as actionsCache from "@actions/cache"; +import { type ActionState } from "./action-common"; import * as actionsUtil from "./actions-util"; -import * as apiClient from "./api-client"; import { type CodeQL } from "./codeql"; import { type Config } from "./config-utils"; -import { DocUrl } from "./doc-url"; -import { Feature, FeatureEnablement } from "./feature-flags"; import * as gitUtils from "./git-utils"; import { Language } from "./languages"; import { Logger } from "./logging"; -import { - asHTTPError, - getErrorMessage, - tryGetFolderBytes, - waitForResultWithTimeLimit, -} from "./util"; +import { getEnv, tryGetFolderBytes, waitForResultWithTimeLimit } from "./util"; // This constant should be bumped if we make a breaking change // to how the CodeQL Action stores or retrieves the TRAP cache, @@ -43,6 +36,7 @@ const MAX_CACHE_OPERATION_MS = 120_000; // Two minutes * @param codeql The CodeQL instance to use. * @param languages The languages being analyzed. * @param logger A logger to record some informational messages to. + * @param repositoryRoot The path at which the repository is checked out at. * @returns A partial map from languages to TRAP cache paths on disk, with * languages for which we shouldn't use TRAP caching omitted. */ @@ -50,6 +44,7 @@ export async function downloadTrapCaches( codeql: CodeQL, languages: Language[], logger: Logger, + repositoryRoot: string | undefined, ): Promise<{ [language: string]: string }> { const result: { [language: string]: string } = {}; const languagesSupportingCaching = await getLanguagesSupportingCaching( @@ -72,7 +67,7 @@ export async function downloadTrapCaches( result[language] = cacheDir; } - if (await gitUtils.isAnalyzingDefaultBranch()) { + if (await gitUtils.isAnalyzingDefaultBranch(getEnv(), repositoryRoot)) { logger.info( "Analyzing default branch. Skipping downloading of TRAP caches.", ); @@ -99,6 +94,7 @@ export async function downloadTrapCaches( const found = await waitForResultWithTimeLimit( MAX_CACHE_OPERATION_MS, actionsCache.restoreCache([cacheDir], preferredKey, [ + preferredKey, // Fall back to any cache with the right key prefix await cachePrefix(codeql, language), ]), @@ -132,7 +128,12 @@ export async function uploadTrapCaches( config: Config, logger: Logger, ): Promise { - if (!(await gitUtils.isAnalyzingDefaultBranch())) return false; // Only upload caches from the default branch + // Only upload caches from the default branch + if ( + !(await gitUtils.isAnalyzingDefaultBranch(getEnv(), config.repositoryRoot)) + ) { + return false; + } for (const language of config.languages) { const cacheDir = config.trapCaches[language]; @@ -169,111 +170,25 @@ export async function uploadTrapCaches( return true; } -export interface TrapCacheCleanupStatusReport { - trap_cache_cleanup_error?: string; - trap_cache_cleanup_size_bytes?: number; - trap_cache_cleanup_skipped_because?: string; -} - -export async function cleanupTrapCaches( - config: Config, - features: FeatureEnablement, - logger: Logger, -): Promise { - if (!(await features.getValue(Feature.CleanupTrapCaches))) { - return { - trap_cache_cleanup_skipped_because: "feature disabled", - }; - } - logger.warning( - "TRAP cache cleanup is deprecated and will be removed in May 2026. " + - "We recommend instead disabling TRAP caching by passing the `trap-caching: false` input to the `init` Action.", - ); - if (!(await gitUtils.isAnalyzingDefaultBranch())) { - return { - trap_cache_cleanup_skipped_because: "not analyzing default branch", - }; - } - - try { - let totalBytesCleanedUp = 0; - - const allCaches = await apiClient.listActionsCaches( - CODEQL_TRAP_CACHE_PREFIX, - await gitUtils.getRef(), +/** + * Warns if the `CODEQL_ACTION_CLEANUP_TRAP_CACHES` environment variable is set to a non-empty + * value. That variable controlled the removed TRAP cache cleanup feature, so setting it has no + * effect. + */ +export function warnIfTrapCacheCleanupEnvVarIsSet({ + env, + logger, +}: ActionState<["Logger", "ReadOnlyEnv"]>): void { + if (env.getOptional("CODEQL_ACTION_CLEANUP_TRAP_CACHES") !== undefined) { + logger.warning( + "TRAP cache cleanup has been removed, so the CODEQL_ACTION_CLEANUP_TRAP_CACHES environment " + + "variable no longer has any effect and can be removed from your workflow. If you used TRAP " + + "cache cleanup to limit Actions cache usage, we recommend disabling TRAP caching instead by " + + "passing the `trap-caching: false` input to the `init` Action.", ); - - for (const language of config.languages) { - if (config.trapCaches[language]) { - const cachesToRemove = await getTrapCachesForLanguage( - allCaches, - language, - logger, - ); - // Dates returned by the API are in ISO 8601 format, so we can sort them lexicographically - cachesToRemove.sort((a, b) => a.created_at.localeCompare(b.created_at)); - // Keep the most recent cache - const mostRecentCache = cachesToRemove.pop(); - logger.debug( - `Keeping most recent TRAP cache (${JSON.stringify(mostRecentCache)})`, - ); - - if (cachesToRemove.length === 0) { - logger.info(`No TRAP caches to clean up for ${language}.`); - continue; - } - - for (const cache of cachesToRemove) { - logger.debug(`Cleaning up TRAP cache (${JSON.stringify(cache)})`); - await apiClient.deleteActionsCache(cache.id); - } - const bytesCleanedUp = cachesToRemove.reduce( - (acc, item) => acc + item.size_in_bytes, - 0, - ); - totalBytesCleanedUp += bytesCleanedUp; - const megabytesCleanedUp = (bytesCleanedUp / (1024 * 1024)).toFixed(2); - logger.info( - `Cleaned up ${megabytesCleanedUp} MiB of old TRAP caches for ${language}.`, - ); - } - } - return { trap_cache_cleanup_size_bytes: totalBytesCleanedUp }; - } catch (e) { - if (asHTTPError(e)?.status === 403) { - logger.warning( - "Could not cleanup TRAP caches as the token did not have the required permissions. " + - 'To clean up TRAP caches, ensure the token has the "actions:write" permission. ' + - `See ${DocUrl.ASSIGNING_PERMISSIONS_TO_JOBS} for more information.`, - ); - } else { - logger.info(`Failed to cleanup TRAP caches, continuing. Details: ${e}`); - } - return { trap_cache_cleanup_error: getErrorMessage(e) }; } } -async function getTrapCachesForLanguage( - allCaches: apiClient.ActionsCacheItem[], - language: Language, - logger: Logger, -): Promise>> { - logger.debug(`Listing TRAP caches for ${language}`); - - for (const cache of allCaches) { - if (!cache.created_at || !cache.id || !cache.key || !cache.size_in_bytes) { - throw new Error( - "An unexpected cache item was returned from the API that was missing one or " + - `more required fields: ${JSON.stringify(cache)}`, - ); - } - } - - return allCaches.filter((cache) => { - return cache.key?.includes(`-${language}-`); - }) as Array>; -} - export async function getLanguagesSupportingCaching( codeql: CodeQL, languages: Language[], diff --git a/src/upload-lib.test.ts b/src/upload-lib.test.ts index 2c27d56c1c..028cce504b 100644 --- a/src/upload-lib.test.ts +++ b/src/upload-lib.test.ts @@ -10,17 +10,22 @@ import * as analyses from "./analyses"; import { AnalysisKind, CodeQuality, CodeScanning } from "./analyses"; import * as api from "./api-client"; import * as diffUtils from "./diff-informed-analysis-utils"; -import { getRunnerLogger, Logger } from "./logging"; +import { getEnv } from "./environment"; +import { Logger } from "./logging"; import * as sarif from "./sarif"; -import { setupTests } from "./testing-utils"; +import { + checkExpectedLogMessages, + RecordingLogger, + setupTests, +} from "./testing-utils"; import * as uploadLib from "./upload-lib"; import { UploadPayload } from "./upload-lib/types"; -import { GitHubVariant, initializeEnvironment, withTmpDir } from "./util"; +import { GitHubVariant, withTmpDir } from "./util"; setupTests(test); test.beforeEach(() => { - initializeEnvironment("1.2.3"); + getEnv().initialise("1.2.3"); }); test.serial("validateSarifFileSchema - valid", (t) => { @@ -29,7 +34,7 @@ test.serial("validateSarifFileSchema - valid", (t) => { uploadLib.validateSarifFileSchema( uploadLib.readSarifFileOrThrow(inputFile), inputFile, - getRunnerLogger(true), + new RecordingLogger(), ), ); }); @@ -40,7 +45,7 @@ test.serial("validateSarifFileSchema - invalid", (t) => { uploadLib.validateSarifFileSchema( uploadLib.readSarifFileOrThrow(inputFile), inputFile, - getRunnerLogger(true), + new RecordingLogger(), ), ); }); @@ -179,7 +184,7 @@ test.serial("finding SARIF files", async (t) => { } const groupedSarifFiles = await uploadLib.getGroupedSarifFilePaths( - getRunnerLogger(true), + new RecordingLogger(), tmpDir, ); @@ -200,7 +205,7 @@ test.serial("getGroupedSarifFilePaths - Risk Assessment files", async (t) => { fs.writeFileSync(sarifPath, ""); const groupedSarifFiles = await uploadLib.getGroupedSarifFilePaths( - getRunnerLogger(true), + new RecordingLogger(), sarifPath, ); @@ -218,7 +223,7 @@ test.serial("getGroupedSarifFilePaths - Code Quality file", async (t) => { fs.writeFileSync(sarifPath, ""); const groupedSarifFiles = await uploadLib.getGroupedSarifFilePaths( - getRunnerLogger(true), + new RecordingLogger(), sarifPath, ); @@ -236,7 +241,7 @@ test.serial("getGroupedSarifFilePaths - Code Scanning file", async (t) => { fs.writeFileSync(sarifPath, ""); const groupedSarifFiles = await uploadLib.getGroupedSarifFilePaths( - getRunnerLogger(true), + new RecordingLogger(), sarifPath, ); @@ -254,7 +259,7 @@ test.serial("getGroupedSarifFilePaths - Other file", async (t) => { fs.writeFileSync(sarifPath, ""); const groupedSarifFiles = await uploadLib.getGroupedSarifFilePaths( - getRunnerLogger(true), + new RecordingLogger(), sarifPath, ); @@ -932,7 +937,7 @@ function uploadPayloadFixtures(analysis: analyses.AnalysisConfig) { owner: mockData.owner, repo: mockData.repo, }, - getRunnerLogger(true), + new RecordingLogger(), analysis, ); @@ -1014,12 +1019,62 @@ for (const analysisKind of analyses.supportedAnalysisKinds) { ); } +function createMockSarifWithResults( + results: sarif.Result[], +): Partial { + return { + version: "2.1.0", + runs: [ + { + tool: { + driver: { + name: "test tool", + }, + }, + results, + }, + ], + }; +} + +function createMockResultWithUri( + uri: string, + startLine = 2, + relatedUri?: string, +): sarif.Result { + return { + ruleId: "test-rule", + message: { text: "test message" }, + locations: [ + { + physicalLocation: { + artifactLocation: { uri }, + region: { startLine }, + }, + }, + ], + ...(relatedUri + ? { + relatedLocations: [ + { + physicalLocation: { + artifactLocation: { uri: relatedUri }, + region: { startLine }, + }, + }, + ], + } + : {}), + }; +} + function runFilterAlertsByDiffRange( input: Partial, diffRanges: diffUtils.DiffThunkRange[], + logger: Logger = new RecordingLogger(), ): Partial { sinon.stub(diffUtils, "readDiffRangesJsonFile").returns(diffRanges); - return uploadLib.filterAlertsByDiffRange(getRunnerLogger(true), input); + return uploadLib.filterAlertsByDiffRange(logger, input); } test.serial( @@ -1043,3 +1098,139 @@ test.serial( t.deepEqual(actualOutput, expectedOutput); }, ); + +for (const [filePath, uri] of [ + ["with space/board.js", "with%20space/board.js"], + ["src/[id]/board.js", "src/%5Bid%5D/board.js"], + ["src/file#1.js", "src/file%231.js"], + ["src/100%.js", "src/100%25.js"], + ["src/literal%20.js", "src/literal%2520.js"], + ["src/foo:bar.js", "src/foo%3Abar.js"], + ["src/caf\u00e9.js", "src/caf%C3%A9.js"], + ["src/caf\u00e9.js", "src/caf%c3%a9.js"], +]) { + test.serial( + `filterAlertsByDiffRange matches percent-encoded URI ${uri}`, + (t) => { + const matchingResult = createMockResultWithUri(uri); + const nonMatchingResult = createMockResultWithUri("other.js"); + const input = createMockSarifWithResults([ + matchingResult, + nonMatchingResult, + ]); + + const actualOutput = runFilterAlertsByDiffRange(input, [ + { path: filePath, startLine: 1, endLine: 3 }, + ]); + + t.deepEqual(actualOutput.runs?.[0].results, [matchingResult]); + }, + ); +} + +test.serial( + "filterAlertsByDiffRange filters out percent-encoded URI when outside diff line range", + (t) => { + const outOfRangeResult = createMockResultWithUri( + "with%20space/board.js", + 2, + ); + const inRangeResult = createMockResultWithUri("with%20space/board.js", 15); + const input = createMockSarifWithResults([outOfRangeResult, inRangeResult]); + const actualOutput = runFilterAlertsByDiffRange(input, [ + { path: "with space/board.js", startLine: 10, endLine: 20 }, + ]); + + t.deepEqual(actualOutput.runs?.[0].results, [inRangeResult]); + }, +); + +test.serial( + "filterAlertsByDiffRange filters out percent-encoded URI when path does not match", + (t) => { + const input = createMockSarifWithResults([ + createMockResultWithUri("with%20space/board.js"), + ]); + const actualOutput = runFilterAlertsByDiffRange(input, [ + { path: "other/board.js", startLine: 1, endLine: 3 }, + ]); + + t.deepEqual(actualOutput.runs?.[0].results, []); + }, +); + +test.serial( + "filterAlertsByDiffRange keeps alert when relatedLocations has a matching percent-encoded URI", + (t) => { + const matchingRelatedResult = createMockResultWithUri( + "src/promiseUtils.js", + 2, + "with%20space/ParseObject.js", + ); + const nonMatchingResult = createMockResultWithUri("other.js"); + const input = createMockSarifWithResults([ + matchingRelatedResult, + nonMatchingResult, + ]); + + const actualOutput = runFilterAlertsByDiffRange(input, [ + { path: "with space/ParseObject.js", startLine: 1, endLine: 3 }, + ]); + + t.deepEqual(actualOutput.runs?.[0].results, [matchingRelatedResult]); + }, +); + +for (const uri of ["dir%ZZ/board.js", "src/bad%.js", "src/bad%C3%28.js"]) { + test.serial( + `filterAlertsByDiffRange falls back to raw path for malformed URI ${uri}`, + (t) => { + const logger = new RecordingLogger(); + const matchingResult = createMockResultWithUri(uri); + const input = createMockSarifWithResults([matchingResult]); + const actualOutput = runFilterAlertsByDiffRange( + input, + [{ path: uri, startLine: 1, endLine: 3 }], + logger, + ); + + t.deepEqual(actualOutput.runs?.[0].results, [matchingResult]); + checkExpectedLogMessages(t, logger.messages, [ + `Failed to decode location URI "${uri}", comparing it as a raw path`, + ]); + }, + ); +} + +test.serial( + "filterAlertsByDiffRange filters out malformed URI when raw path does not match", + (t) => { + const logger = new RecordingLogger(); + const input = createMockSarifWithResults([ + createMockResultWithUri("dir%ZZ/board.js"), + ]); + const actualOutput = runFilterAlertsByDiffRange( + input, + [{ path: "src/different.js", startLine: 1, endLine: 3 }], + logger, + ); + + t.deepEqual(actualOutput.runs?.[0].results, []); + checkExpectedLogMessages(t, logger.messages, [ + 'Failed to decode location URI "dir%ZZ/board.js", comparing it as a raw path', + ]); + }, +); + +test.serial( + "filterAlertsByDiffRange matches raw unencoded path containing valid percent-encoding sequence", + (t) => { + const matchingResult = createMockResultWithUri("dir/100%20done.js"); + const input = createMockSarifWithResults([matchingResult]); + const actualOutput = runFilterAlertsByDiffRange(input, [ + { path: "dir/100%20done.js", startLine: 1, endLine: 3 }, + ]); + + t.deepEqual(actualOutput.runs?.[0].results, [matchingResult]); + }, +); diff --git a/src/upload-lib.ts b/src/upload-lib.ts index da5552cf24..52f6fdba66 100644 --- a/src/upload-lib.ts +++ b/src/upload-lib.ts @@ -12,12 +12,13 @@ import * as analyses from "./analyses"; import * as api from "./api-client"; import { getGitHubVersion, wrapApiConfigurationError } from "./api-client"; import { CodeQL, getCodeQL } from "./codeql"; -import { getConfig } from "./config-utils"; +import type { ActionConfig } from "./config/action-config"; import { readDiffRangesJsonFile } from "./diff-informed-analysis-utils"; -import { EnvVar } from "./environment"; +import { ActionsEnvVars, EnvVar, exportEnvVar } from "./environment"; import { FeatureEnablement } from "./feature-flags"; import * as fingerprints from "./fingerprints"; import * as gitUtils from "./git-utils"; +import * as github from "./github"; import { initCodeQL } from "./init"; import { Logger } from "./logging"; import { getRepositoryNwo, RepositoryNwo } from "./repository"; @@ -33,7 +34,6 @@ import * as util from "./util"; import { ConfigurationError, getErrorMessage, - getRequiredEnvParam, GitHubVariant, GitHubVersion, satisfiesGHESVersion, @@ -94,16 +94,22 @@ async function shouldDisableCombineSarifFiles( return true; } -// Takes a list of paths to sarif files and combines them together using the -// CLI `github merge-results` command when all SARIF files are produced by -// CodeQL. Otherwise, it will fall back to combining the files in the action. -// Returns the contents of the combined sarif file. +/** + * Takes a list of paths to sarif files and combines them together using the + * CLI `github merge-results` command when all SARIF files are produced by + * CodeQL. Otherwise, it will fall back to combining the files in the action. + * + * @returns The contents of the combined sarif file. + */ async function combineSarifFilesUsingCLI( sarifFiles: string[], gitHubVersion: GitHubVersion, features: FeatureEnablement, logger: Logger, + config: ActionConfig<"codeQLCmd" | "tempDir"> | undefined, ): Promise> { + const env = util.getEnv(); + logger.info("Combining SARIF files using the CodeQL CLI"); const sarifObjects = sarifFiles.map(sarif.readSarifFile); @@ -126,7 +132,7 @@ async function combineSarifFilesUsingCLI( logger.warning( `Uploading multiple SARIF runs with the same category is deprecated ${deprecationWarningMessage}. Please update your workflow to upload a single run per category. ${deprecationMoreInformationMessage}`, ); - core.exportVariable("CODEQL_MERGE_SARIF_DEPRECATION_WARNING", "true"); + exportEnvVar("CODEQL_MERGE_SARIF_DEPRECATION_WARNING", "true"); } // If not, use the naive method of combining the files. @@ -138,7 +144,6 @@ async function combineSarifFilesUsingCLI( let codeQL: CodeQL; let tempDir: string = actionsUtil.getTemporaryDirectory(); - const config = await getConfig(tempDir, logger); if (config !== undefined) { codeQL = await getCodeQL(logger, config.codeQLCmd); tempDir = config.tempDir; @@ -152,8 +157,7 @@ async function combineSarifFilesUsingCLI( externalRepoAuth: actionsUtil.getOptionalInput( "external-repository-token", ), - url: getRequiredEnvParam("GITHUB_SERVER_URL"), - apiURL: getRequiredEnvParam("GITHUB_API_URL"), + ...github.getCurrentInstance(env), }; const codeQLDefaultVersionInfo = @@ -166,6 +170,7 @@ async function combineSarifFilesUsingCLI( gitHubVersion.type, codeQLDefaultVersionInfo, undefined, // rawLanguages: upload-lib does not run analysis + undefined, // otherLanguagePacksReason: upload-lib does not run analysis false, // useOverlayAwareDefaultCliVersion: upload-lib does not run analysis features, logger, @@ -226,6 +231,14 @@ function getAutomationID( return api.computeAutomationID(analysis_key, environment); } +/** Gets the path to a saved payload file for {@link analysisKind}. */ +export function getSavedPayloadPath(analysisKind: analyses.AnalysisKind) { + return path.join( + actionsUtil.getTemporaryDirectory(), + `payload-${analysisKind}.json`, + ); +} + /** * Upload the given payload. * If the request fails then this will retry a small number of times. @@ -240,10 +253,7 @@ export async function uploadPayload( logger.info("Uploading results"); if (util.shouldSkipSarifUpload()) { - const payloadSaveFile = path.join( - actionsUtil.getTemporaryDirectory(), - `payload-${analysis.kind}.json`, - ); + const payloadSaveFile = getSavedPayloadPath(analysis.kind); logger.info( `SARIF upload disabled by an environment variable. Saving to ${payloadSaveFile}`, ); @@ -597,6 +607,7 @@ export interface PostProcessingResults { export async function postProcessSarifFiles( logger: Logger, features: FeatureEnablement, + config: ActionConfig<"codeQLCmd" | "tempDir"> | undefined, checkoutPath: string, sarifPaths: string[], category: string | undefined, @@ -621,6 +632,7 @@ export async function postProcessSarifFiles( gitHubVersion, features, logger, + config, ); } else { const sarifPath = sarifPaths[0]; @@ -681,6 +693,7 @@ export async function writePostProcessedFiles( * to. */ export async function uploadFiles( + config: ActionConfig<"codeQLCmd" | "tempDir"> | undefined, inputSarifPath: string, checkoutPath: string, category: string | undefined, @@ -695,6 +708,7 @@ export async function uploadFiles( return uploadSpecifiedFiles( sarifPaths, + config, checkoutPath, category, features, @@ -708,6 +722,7 @@ export async function uploadFiles( */ async function uploadSpecifiedFiles( sarifPaths: string[], + config: ActionConfig<"codeQLCmd" | "tempDir"> | undefined, checkoutPath: string, category: string | undefined, features: FeatureEnablement, @@ -717,6 +732,7 @@ async function uploadSpecifiedFiles( const processingResults: PostProcessingResults = await postProcessSarifFiles( logger, features, + config, checkoutPath, sarifPaths, category, @@ -761,12 +777,13 @@ export async function uploadPostProcessedFiles( const zippedSarif = zlib.gzipSync(sarifPayload).toString("base64"); const checkoutURI = url.pathToFileURL(checkoutPath).href; + const env = util.getEnv(); const payload = uploadTarget.transformPayload( buildPayload( - await gitUtils.getCommitOid(checkoutPath), - await gitUtils.getRef(), + await gitUtils.getCommitOid(env, checkoutPath), + await gitUtils.getRef(env, checkoutPath), postProcessingResults.analysisKey, - util.getRequiredEnvParam("GITHUB_WORKFLOW"), + env.getRequired(ActionsEnvVars.GITHUB_WORKFLOW), zippedSarif, actionsUtil.getWorkflowRunID(), actionsUtil.getWorkflowRunAttempt(), @@ -854,6 +871,16 @@ export async function waitForProcessing( ): Promise { logger.startGroup("Waiting for processing to finish"); try { + // If SARIF upload is disabled and we reach this point, then the file was written to disk and + // there is nothing to wait for. We still allow ourselves to get to this point so that we can + // see in the log that we would have waited for processing to finish if the upload had happened. + if (util.shouldSkipSarifUpload()) { + logger.info( + "Nothing to wait for, because SARIF upload is disabled by an environment variable and the SARIF was saved to disk.", + ); + return; + } + const client = api.getApiClient(); // Do an initial wait because processing will always take a minimum of 2-3 seconds @@ -1031,7 +1058,7 @@ export function validateUniqueCategory( `Category: (${id ? id : "none"}) Tool: (${tool ? tool : "none"})`, ); } - core.exportVariable(sentinelEnvVar, sentinelEnvVar); + exportEnvVar(sentinelEnvVar, sentinelEnvVar); } } @@ -1072,9 +1099,21 @@ export function filterAlertsByDiffRange( return locations.some((physicalLocation) => { const locationUri = physicalLocation?.artifactLocation?.uri; const locationStartLine = physicalLocation?.region?.startLine; - if (!locationUri || locationStartLine === undefined) { + if ( + typeof locationUri !== "string" || + !locationUri || + locationStartLine === undefined + ) { return false; } + let decodedLocationUri = locationUri; + try { + decodedLocationUri = decodeURIComponent(locationUri); + } catch { + logger.debug( + `Failed to decode location URI "${locationUri}", comparing it as a raw path`, + ); + } // Alert filtering here replicates the same behavior as the restrictAlertsTo // extensible predicate in CodeQL. See the restrictAlertsTo documentation // https://codeql.github.com/codeql-standard-libraries/csharp/codeql/util/AlertFiltering.qll/predicate.AlertFiltering$restrictAlertsTo.3.html @@ -1082,7 +1121,8 @@ export function filterAlertsByDiffRange( // of an alert location. return diffRanges.some( (range) => - range.path === locationUri && + (range.path === decodedLocationUri || + range.path === locationUri) && ((range.startLine <= locationStartLine && range.endLine >= locationStartLine) || (range.startLine === 0 && range.endLine === 0)), diff --git a/src/upload-sarif-action-post.ts b/src/upload-sarif-action-post.ts index a27fe1667d..82961842e8 100644 --- a/src/upload-sarif-action-post.ts +++ b/src/upload-sarif-action-post.ts @@ -17,9 +17,10 @@ export async function runWrapper() { // possible, and only use safe functions outside. try { - // Restore inputs from `upload-sarif` Action. - actionsUtil.restoreInputs(); const logger = getActionsLogger(); + + // Restore inputs from `upload-sarif` Action. + actionsUtil.restoreInputs(logger); const gitHubVersion = await getGitHubVersion(); checkGitHubVersionInRange(gitHubVersion, logger); @@ -33,13 +34,7 @@ export async function runWrapper() { return; } await withGroup("Uploading combined SARIF debug artifact", () => - debugArtifacts.uploadCombinedSarifArtifacts( - logger, - gitHubVersion.type, - // The codeqlVersion is not applicable for uploading non-codeql sarif. - // We can assume all versions are safe to upload. - undefined, - ), + debugArtifacts.uploadCombinedSarifArtifacts(logger, gitHubVersion.type), ); } } catch (error) { diff --git a/src/upload-sarif-action.ts b/src/upload-sarif-action.ts index d3437510ce..033663fb72 100644 --- a/src/upload-sarif-action.ts +++ b/src/upload-sarif-action.ts @@ -5,6 +5,7 @@ import * as actionsUtil from "./actions-util"; import { getActionVersion, getTemporaryDirectory } from "./actions-util"; import * as analyses from "./analyses"; import { getGitHubVersion } from "./api-client"; +import { getConfig } from "./config-utils"; import { initFeatures } from "./feature-flags"; import { Logger } from "./logging"; import { getRepositoryNwo } from "./repository"; @@ -23,14 +24,12 @@ import { ConfigurationError, checkActionVersion, checkDiskUsage, - initializeEnvironment, shouldSkipSarifUpload, wrapError, } from "./util"; interface UploadSarifStatusReport - extends StatusReportBase, - upload_lib.UploadStatusReport {} + extends StatusReportBase, upload_lib.UploadStatusReport {} async function sendSuccessStatusReport( startedAt: Date, @@ -54,11 +53,13 @@ async function sendSuccessStatusReport( } } -async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { +async function run(action: ActionState<["Base", "Env", "Logger"]>) { // To capture errors appropriately, keep as much code within the try-catch as // possible, and only use safe functions outside. + const logger = action.logger; + try { - initializeEnvironment(getActionVersion()); + action.env.initialise(getActionVersion()); const gitHubVersion = await getGitHubVersion(); checkActionVersion(getActionVersion(), gitHubVersion); @@ -66,18 +67,19 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { // Make inputs accessible in the `post` step. actionsUtil.persistInputs(); + const tempDir = getTemporaryDirectory(); const repositoryNwo = getRepositoryNwo(); const features = initFeatures( gitHubVersion, repositoryNwo, - getTemporaryDirectory(), + tempDir, logger, ); const startingStatusReportBase = await createStatusReportBase( ActionName.UploadSarif, "starting", - startedAt, + action.startedAt, undefined, await checkDiskUsage(logger), logger, @@ -91,9 +93,13 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { const checkoutPath = actionsUtil.getRequiredInput("checkout_path"); const category = actionsUtil.getOptionalInput("category"); + // Load the configuration from a previous step if there is one. This allows us to reuse the CLI that + // may have been installed by a previous step. + const maybeConfig = await getConfig(tempDir, logger); const uploadResults = await postProcessAndUploadSarif( logger, features, + maybeConfig, "always", checkoutPath, sarifPath, @@ -131,7 +137,7 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { // so we can't wait for that here. } await sendSuccessStatusReport( - startedAt, + action.startedAt, codeScanningResult?.statusReport || {}, logger, ); @@ -147,7 +153,7 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) { const errorStatusReportBase = await createStatusReportBase( ActionName.UploadSarif, getActionsStatus(error), - startedAt, + action.startedAt, undefined, await checkDiskUsage(logger), logger, diff --git a/src/upload-sarif.test.ts b/src/upload-sarif.test.ts index d310bce92a..a1ea5dbeef 100644 --- a/src/upload-sarif.test.ts +++ b/src/upload-sarif.test.ts @@ -5,8 +5,12 @@ import test, { ExecutionContext } from "ava"; import * as sinon from "sinon"; import { AnalysisKind, getAnalysisConfig } from "./analyses"; -import { getRunnerLogger } from "./logging"; -import { createFeatures, makeMacro, setupTests } from "./testing-utils"; +import { + createFeatures, + makeMacro, + RecordingLogger, + setupTests, +} from "./testing-utils"; import { UploadResult } from "./upload-lib"; import * as uploadLib from "./upload-lib"; import { postProcessAndUploadSarif } from "./upload-sarif"; @@ -26,6 +30,7 @@ function mockPostProcessSarifFiles() { const analysisConfig = getAnalysisConfig(analysisKind); postProcessSarifFiles .withArgs( + sinon.match.object, sinon.match.any, sinon.match.any, sinon.match.any, @@ -51,7 +56,7 @@ const postProcessAndUploadSarifMacro = makeMacro({ expectedResult: Partial>, ) => { await util.withTmpDir(async (tempDir) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const testPath = sarifPath(tempDir); const features = createFeatures([]); @@ -75,9 +80,11 @@ const postProcessAndUploadSarifMacro = makeMacro({ fs.writeFileSync(sarifFile, ""); } + const config = undefined; const actual = await postProcessAndUploadSarif( logger, features, + config, "always", "", testPath, @@ -94,6 +101,7 @@ const postProcessAndUploadSarifMacro = makeMacro({ postProcessSarifFiles.calledWith( logger, features, + config, sinon.match.any, analysisKindResult.expectedFiles?.map(toFullPath) ?? fullSarifPaths, @@ -206,7 +214,7 @@ test.serial( "postProcessAndUploadSarif doesn't upload if upload is disabled", async (t) => { await util.withTmpDir(async (tempDir) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const features = createFeatures([]); const toFullPath = (filename: string) => path.join(tempDir, filename); @@ -223,6 +231,7 @@ test.serial( const actual = await postProcessAndUploadSarif( logger, features, + undefined, "never", "", tempDir, @@ -239,7 +248,7 @@ test.serial( "postProcessAndUploadSarif writes post-processed SARIF files if output directory is provided", async (t) => { await util.withTmpDir(async (tempDir) => { - const logger = getRunnerLogger(true); + const logger = new RecordingLogger(); const features = createFeatures([]); const toFullPath = (filename: string) => path.join(tempDir, filename); @@ -253,6 +262,7 @@ test.serial( const actual = await postProcessAndUploadSarif( logger, features, + undefined, "never", "", tempDir, diff --git a/src/upload-sarif.ts b/src/upload-sarif.ts index bc2c886982..0a8d8a14a2 100644 --- a/src/upload-sarif.ts +++ b/src/upload-sarif.ts @@ -1,5 +1,6 @@ import { UploadKind } from "./actions-util"; import * as analyses from "./analyses"; +import type { ActionConfig } from "./config/action-config"; import { FeatureEnablement } from "./feature-flags"; import { Logger } from "./logging"; import * as upload_lib from "./upload-lib"; @@ -26,6 +27,7 @@ export type UploadSarifResults = Partial< export async function postProcessAndUploadSarif( logger: Logger, features: FeatureEnablement, + config: ActionConfig<"codeQLCmd" | "tempDir"> | undefined, uploadKind: UploadKind, checkoutPath: string, sarifPath: string, @@ -45,6 +47,7 @@ export async function postProcessAndUploadSarif( const postProcessingResults = await upload_lib.postProcessSarifFiles( logger, features, + config, checkoutPath, sarifFiles, category, diff --git a/src/util.test.ts b/src/util.test.ts index cca457cbe6..af69171f33 100644 --- a/src/util.test.ts +++ b/src/util.test.ts @@ -1,6 +1,7 @@ import * as fs from "fs"; import * as os from "os"; import path from "path"; +import { performance } from "perf_hooks"; import * as core from "@actions/core"; import test from "ava"; @@ -9,8 +10,7 @@ import * as sinon from "sinon"; import * as api from "./api-client"; import { EnvVar } from "./environment"; -import { getRunnerLogger } from "./logging"; -import { setupTests } from "./testing-utils"; +import { RecordingLogger, setupTests, getTestEnv } from "./testing-utils"; import * as util from "./util"; setupTests(test); @@ -91,7 +91,7 @@ for (const { test("getMemoryFlag() throws if the ram input is < 0 or NaN", async (t) => { for (const input of ["-1", "hello!"]) { - t.throws(() => util.getMemoryFlag(input, getRunnerLogger(true))); + t.throws(() => util.getMemoryFlag(input, new RecordingLogger())); } }); @@ -108,13 +108,13 @@ test("getThreadsFlag() should return the correct --threads flag", (t) => { ]; for (const [input, expectedFlag] of tests) { - const flag = util.getThreadsFlag(input, getRunnerLogger(true)); + const flag = util.getThreadsFlag(input, new RecordingLogger()); t.deepEqual(flag, expectedFlag); } }); test("getThreadsFlag() throws if the threads input is not an integer", (t) => { - t.throws(() => util.getThreadsFlag("hello!", getRunnerLogger(true))); + t.throws(() => util.getThreadsFlag("hello!", new RecordingLogger())); }); test.serial( @@ -163,66 +163,6 @@ test.serial("getExtraOptionsEnvParam() fails on invalid JSON", (t) => { process.env.CODEQL_ACTION_EXTRA_OPTIONS = origExtraOptions; }); -test("parseGitHubUrl", (t) => { - t.deepEqual(util.parseGitHubUrl("github.com"), "https://github.com"); - t.deepEqual(util.parseGitHubUrl("https://github.com"), "https://github.com"); - t.deepEqual( - util.parseGitHubUrl("https://api.github.com"), - "https://github.com", - ); - t.deepEqual( - util.parseGitHubUrl("https://github.com/foo/bar"), - "https://github.com", - ); - - t.deepEqual( - util.parseGitHubUrl("github.example.com"), - "https://github.example.com/", - ); - t.deepEqual( - util.parseGitHubUrl("https://github.example.com"), - "https://github.example.com/", - ); - t.deepEqual( - util.parseGitHubUrl("https://api.github.example.com"), - "https://github.example.com/", - ); - t.deepEqual( - util.parseGitHubUrl("https://github.example.com/api/v3"), - "https://github.example.com/", - ); - t.deepEqual( - util.parseGitHubUrl("https://github.example.com:1234"), - "https://github.example.com:1234/", - ); - t.deepEqual( - util.parseGitHubUrl("https://api.github.example.com:1234"), - "https://github.example.com:1234/", - ); - t.deepEqual( - util.parseGitHubUrl("https://github.example.com:1234/api/v3"), - "https://github.example.com:1234/", - ); - t.deepEqual( - util.parseGitHubUrl("https://github.example.com/base/path"), - "https://github.example.com/base/path/", - ); - t.deepEqual( - util.parseGitHubUrl("https://github.example.com/base/path/api/v3"), - "https://github.example.com/base/path/", - ); - - t.throws(() => util.parseGitHubUrl(""), { - message: '"" is not a valid URL', - }); - t.throws(() => util.parseGitHubUrl("ssh://github.com"), { - message: '"ssh://github.com" is not a http or https URL', - }); - t.throws(() => util.parseGitHubUrl("http:///::::433"), { - message: '"http:///::::433" is not a valid URL', - }); -}); - test("allowed API versions", async (t) => { t.is(util.apiVersionInRange("1.33.0", "1.33", "2.0"), undefined); t.is(util.apiVersionInRange("1.33.1", "1.33", "2.0"), undefined); @@ -444,7 +384,7 @@ test("getCgroupCpuCountFromCpus calculates the number of CPUs correctly", async const testCpuFile = `${tmpDir}/cpus-file`; fs.writeFileSync(testCpuFile, "1, 9-10\n", "utf-8"); t.deepEqual( - util.getCgroupCpuCountFromCpus(testCpuFile, getRunnerLogger(true)), + util.getCgroupCpuCountFromCpus(testCpuFile, new RecordingLogger()), 3, ); }); @@ -455,7 +395,7 @@ test("getCgroupCpuCountFromCpus returns undefined if the CPU file doesn't exist" const testCpuFile = `${tmpDir}/cpus-file`; t.false(fs.existsSync(testCpuFile)); t.deepEqual( - util.getCgroupCpuCountFromCpus(testCpuFile, getRunnerLogger(true)), + util.getCgroupCpuCountFromCpus(testCpuFile, new RecordingLogger()), undefined, ); }); @@ -466,7 +406,7 @@ test("getCgroupCpuCountFromCpus returns undefined if the CPU file exists but is const testCpuFile = `${tmpDir}/cpus-file`; fs.writeFileSync(testCpuFile, "\n", "utf-8"); t.deepEqual( - util.getCgroupCpuCountFromCpus(testCpuFile, getRunnerLogger(true)), + util.getCgroupCpuCountFromCpus(testCpuFile, new RecordingLogger()), undefined, ); }); @@ -476,7 +416,7 @@ test.serial( "checkDiskUsage succeeds and produces positive numbers", async (t) => { process.env["GITHUB_WORKSPACE"] = os.tmpdir(); - const diskUsage = await util.checkDiskUsage(getRunnerLogger(true)); + const diskUsage = await util.checkDiskUsage(new RecordingLogger()); if (t.truthy(diskUsage)) { t.true(diskUsage.numAvailableBytes > 0); t.true(diskUsage.numTotalBytes > 0); @@ -508,6 +448,26 @@ test("joinAtMost - truncates list if array is > than limit", (t) => { t.false(result.includes("test6")); }); +test.serial( + "durationMsSince rounds elapsed milliseconds rather than the timestamps", + (t) => { + const startTime = 1000.25; + const now = sinon.stub(performance, "now"); + for (const [endTime, expected] of [ + [1000.25, 0], + [1000.74, 0], + [1000.75, 1], + [1001.74, 1], + [1001.75, 2], + [2000.74, 1000], + [2000.75, 1001], + ]) { + now.returns(endTime); + t.is(util.durationMsSince(startTime), expected); + } + }, +); + test("Success creates a success result", (t) => { const result = new util.Success("test value"); t.true(result.isSuccess()); @@ -532,3 +492,70 @@ test("Failure.orElse returns the default value for a failure result", (t) => { const result = new util.Failure(new Error("test error")); t.is(result.orElse("default value"), "default value"); }); + +test("shouldSkipGenerateFailedSarif", (t) => { + const env = getTestEnv(); + + // Don't skip by default + t.is(util.shouldSkipGenerateFailedSarif(env), false); + + // Skip in test mode + env.setAll({ + [EnvVar.TEST_MODE]: "true", + [EnvVar.SKIP_SARIF_UPLOAD]: undefined, + [EnvVar.SKIP_GENERATE_FAILED_SARIF]: undefined, + }); + t.is(util.shouldSkipGenerateFailedSarif(env), true); + + // Skip if explicitly requested + env.setAll({ + [EnvVar.TEST_MODE]: undefined, + [EnvVar.SKIP_SARIF_UPLOAD]: undefined, + [EnvVar.SKIP_GENERATE_FAILED_SARIF]: "true", + }); + t.is(util.shouldSkipGenerateFailedSarif(env), true); + + // Skip if not uploading SARIF + env.setAll({ + [EnvVar.TEST_MODE]: undefined, + [EnvVar.SKIP_SARIF_UPLOAD]: "true", + [EnvVar.SKIP_GENERATE_FAILED_SARIF]: undefined, + }); + t.is(util.shouldSkipGenerateFailedSarif(env), true); + + // Don't skip if explicitly requested + env.setAll({ + [EnvVar.TEST_MODE]: "true", + [EnvVar.SKIP_SARIF_UPLOAD]: "true", + [EnvVar.SKIP_GENERATE_FAILED_SARIF]: "false", + }); + t.is(util.shouldSkipGenerateFailedSarif(env), false); +}); + +test("shouldSkipSarifUpload", (t) => { + const env = getTestEnv(); + + // Don't skip by default + t.is(util.shouldSkipSarifUpload(env), false); + + // Skip in test mode + env.setAll({ + [EnvVar.TEST_MODE]: "true", + [EnvVar.SKIP_SARIF_UPLOAD]: undefined, + }); + t.is(util.shouldSkipSarifUpload(env), true); + + // Skip if explicitly requested + env.setAll({ + [EnvVar.TEST_MODE]: undefined, + [EnvVar.SKIP_SARIF_UPLOAD]: "true", + }); + t.is(util.shouldSkipSarifUpload(env), true); + + // Don't skip if explicitly requested + env.setAll({ + [EnvVar.TEST_MODE]: "true", + [EnvVar.SKIP_SARIF_UPLOAD]: "false", + }); + t.is(util.shouldSkipSarifUpload(env), false); +}); diff --git a/src/util.ts b/src/util.ts index 2d910dec3b..533f40ed7f 100644 --- a/src/util.ts +++ b/src/util.ts @@ -2,6 +2,7 @@ import * as fs from "fs"; import * as fsPromises from "fs/promises"; import * as os from "os"; import * as path from "path"; +import { performance } from "perf_hooks"; import * as core from "@actions/core"; import * as io from "@actions/io"; @@ -11,15 +12,30 @@ import * as semver from "semver"; import * as apiCompatibility from "./api-compatibility.json"; import type { CodeQL } from "./codeql"; +import type { ActionConfig } from "./config/action-config"; import type { Pack } from "./config/db-config"; import type { Config } from "./config-utils"; -import { EnvVar, getRequiredEnvParam } from "./environment"; -import * as json from "./json"; -import { Language } from "./languages"; -import { Logger } from "./logging"; +import { + EnvVar, + getRequiredEnvParam, + exportEnvVar, + getEnv, + type ReadOnlyEnv, +} from "./environment"; +import { ConfigurationError, getErrorMessage, wrapError } from "./errors"; +import { GitHubVariant, type GitHubVersion } from "./github"; +import type { Language } from "./languages"; +import type { Logger } from "./logging"; // Re-export for backwards compatibility to avoid updating a lot of imports elsewhere. -export { getRequiredEnvParam, getOptionalEnvVar, getEnv } from "./environment"; +export * from "./errors"; +export { + getRequiredEnvParam, + getOptionalEnvVar, + getEnv, + isInTestMode, +} from "./environment"; +export { GitHubVariant, type GitHubVersion } from "./github"; /** * The name of the file containing the base database OIDs, as stored in the @@ -33,11 +49,6 @@ const BASE_DATABASE_OIDS_FILE_NAME = "base-database-oids.json"; */ const BROKEN_VERSIONS = ["0.0.0-20211207"]; -/** - * The URL for github.com. - */ -export const GITHUB_DOTCOM_URL = "https://github.com"; - /** * Default name of the debugging artifact. */ @@ -84,9 +95,32 @@ export async function withTmpDir( body: (tmpDir: string) => Promise, ): Promise { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "codeql-action-")); - const result = await body(tmpDir); - await fs.promises.rm(tmpDir, { force: true, recursive: true }); - return result; + try { + return await body(tmpDir); + } finally { + await fs.promises.rm(tmpDir, { force: true, recursive: true }); + } +} + +/** + * Creates a temporary file with the given contents, runs the given body, and + * then deletes the file. Note that, to create a temporary file, we first create + * a temporary directory via {@link withTmpDir} and then create the file within + * that directory. + * @param baseFileName The name to assign the temporary file. + * @param contents The contents to write to the temporary file. + * @param body The function to execute with the temporary file. + */ +export async function withTmpFile( + baseFileName: string, + contents: string, + body: (filePath: string) => Promise | T, +): Promise { + return withTmpDir(async (tmpDir) => { + const filePath = path.join(tmpDir, baseFileName); + fs.writeFileSync(filePath, contents); + return body(filePath); + }); } /** @@ -411,7 +445,10 @@ export function getThreadsFlag( /** * Get the path where the CodeQL database for the given language lives. */ -export function getCodeQLDatabasePath(config: Config, language: Language) { +export function getCodeQLDatabasePath( + config: ActionConfig<"dbLocation">, + language: Language, +) { return path.resolve(config.dbLocation, language); } @@ -427,68 +464,11 @@ export function getGeneratedSuitePath(config: Config, language: Language) { ); } -/** - * Parses user input of a github.com or GHES URL to a canonical form. - * Removes any API prefix or suffix if one is present. - */ -export function parseGitHubUrl(inputUrl: string): string { - const originalUrl = inputUrl; - if (inputUrl.indexOf("://") === -1) { - inputUrl = `https://${inputUrl}`; - } - if (!inputUrl.startsWith("http://") && !inputUrl.startsWith("https://")) { - throw new ConfigurationError(`"${originalUrl}" is not a http or https URL`); - } - - let url: URL; - try { - url = new URL(inputUrl); - } catch { - throw new ConfigurationError(`"${originalUrl}" is not a valid URL`); - } - - // If we detect this is trying to be to github.com - // then return with a fixed canonical URL. - if (url.hostname === "github.com" || url.hostname === "api.github.com") { - return GITHUB_DOTCOM_URL; - } - - // Remove the API prefix if it's present - if (url.pathname.indexOf("/api/v3") !== -1) { - url.pathname = url.pathname.substring(0, url.pathname.indexOf("/api/v3")); - } - // Also consider subdomain isolation on GHES - if (url.hostname.startsWith("api.")) { - url.hostname = url.hostname.substring(4); - } - - // Normalise path to having a trailing slash for consistency - if (!url.pathname.endsWith("/")) { - url.pathname = `${url.pathname}/`; - } - - return url.toString(); -} - const CODEQL_ACTION_WARNED_ABOUT_VERSION_ENV_VAR = "CODEQL_ACTION_WARNED_ABOUT_VERSION"; let hasBeenWarnedAboutVersion = false; -export enum GitHubVariant { - /** [GitHub.com](https://github.com) */ - DOTCOM = "GitHub.com", - /** [GitHub Enterprise Server](https://docs.github.com/en/enterprise-server@latest/admin/overview/about-github-enterprise-server) */ - GHES = "GitHub Enterprise Server", - /** [GitHub Enterprise Cloud with data residency](https://docs.github.com/en/enterprise-cloud@latest/admin/data-residency/about-github-enterprise-cloud-with-data-residency) */ - GHEC_DR = "GitHub Enterprise Cloud with data residency", -} - -export type GitHubVersion = - | { type: GitHubVariant.DOTCOM } - | { type: GitHubVariant.GHEC_DR } - | { type: GitHubVariant.GHES; version: string }; - export function checkGitHubVersionInRange( version: GitHubVersion, logger: Logger, @@ -518,7 +498,7 @@ export function checkGitHubVersionInRange( ); } hasBeenWarnedAboutVersion = true; - core.exportVariable(CODEQL_ACTION_WARNED_ABOUT_VERSION_ENV_VAR, true); + exportEnvVar(CODEQL_ACTION_WARNED_ABOUT_VERSION_ENV_VAR, true); } export enum DisallowedAPIVersionReason { @@ -557,55 +537,9 @@ export function assertNever(value: never): never { throw new ExhaustivityCheckingError(value); } -/** - * Set some initial environment variables that we can set even without - * knowing what version of CodeQL we're running. - */ -export function initializeEnvironment(version: string) { - core.exportVariable(EnvVar.FEATURE_MULTI_LANGUAGE, "false"); - core.exportVariable(EnvVar.FEATURE_SANDWICH, "false"); - core.exportVariable(EnvVar.FEATURE_SARIF_COMBINE, "true"); - core.exportVariable(EnvVar.FEATURE_WILL_UPLOAD, "true"); - core.exportVariable(EnvVar.VERSION, version); -} - -export class HTTPError extends Error { - public status: number; - - constructor(message: string, status: number) { - super(message); - this.status = status; - } -} - -/** - * An Error class that indicates an error that occurred due to - * a misconfiguration of the action or the CodeQL CLI. - */ -export class ConfigurationError extends Error {} - -export function asHTTPError(arg: any): HTTPError | undefined { - if (!json.isObject(arg) || !json.isString(arg.message)) { - return undefined; - } - if (Number.isInteger(arg.status)) { - return new HTTPError(arg.message, arg.status as number); - } - // See https://github.com/actions/toolkit/blob/acb230b99a46ed33a3f04a758cd68b47b9a82908/packages/tool-cache/src/tool-cache.ts#L19 - if (Number.isInteger(arg.httpStatusCode)) { - return new HTTPError(arg.message, arg.httpStatusCode as number); - } - return undefined; -} - -export async function codeQlVersionAtLeast( - codeql: CodeQL, - requiredVersion: string, -): Promise { - return semver.gte((await codeql.getVersion()).version, requiredVersion); -} - -export function getBaseDatabaseOidsFilePath(config: Config): string { +export function getBaseDatabaseOidsFilePath( + config: ActionConfig<"dbLocation">, +): string { return path.join(config.dbLocation, BASE_DATABASE_OIDS_FILE_NAME); } @@ -617,7 +551,7 @@ export function getBaseDatabaseOidsFilePath(config: Config): string { * given `includeDiagnostics` value. */ export async function bundleDb( - config: Config, + config: ActionConfig<"dbLocation">, language: Language, codeql: CodeQL, dbName: string, @@ -658,6 +592,11 @@ export async function bundleDb( return databaseBundlePath; } +/** Returns the elapsed milliseconds, rounded, since `startTime` was recorded with `performance.now()`. */ +export function durationMsSince(startTime: number): number { + return Math.round(performance.now() - startTime); +} + /** * @param milliseconds time to delay * @param opts options @@ -683,19 +622,29 @@ export function isGoodVersion(versionSpec: string) { } /** - * Returns whether we are in test mode. This is used by CodeQL Action PR checks. - * - * In test mode, we skip several uploads (SARIF results, status reports, DBs, ...). + * Returns whether we specifically want to skip generating a failed SARIF. */ -export function isInTestMode(): boolean { - return process.env[EnvVar.TEST_MODE] === "true"; +export function shouldSkipGenerateFailedSarif( + env: ReadOnlyEnv = getEnv(), +): boolean { + const skipGenerateFailedSarif = env.getOptional( + EnvVar.SKIP_GENERATE_FAILED_SARIF, + ); + return ( + skipGenerateFailedSarif !== "false" && + (shouldSkipSarifUpload(env) || skipGenerateFailedSarif === "true") + ); } /** * Returns whether we specifically want to skip uploading SARIF files. */ -export function shouldSkipSarifUpload(): boolean { - return isInTestMode() || process.env[EnvVar.SKIP_SARIF_UPLOAD] === "true"; +export function shouldSkipSarifUpload(env: ReadOnlyEnv = getEnv()): boolean { + const skipSarifUpload = env.getOptional(EnvVar.SKIP_SARIF_UPLOAD); + return ( + skipSarifUpload !== "false" && + (env.isSkippingUploadsInTests() || skipSarifUpload === "true") + ); } /** @@ -842,9 +791,13 @@ export async function checkForTimeout() { * directory with the name hostedtoolcache which is present on * GitHub-hosted runners. * - * @returns true iff the runner is hosted by GitHub + * Since this is a heuristic over how the runner happens to be named and laid out, it also matches + * self-hosted runners that are configured to resemble hosted ones. Prefer + * `isGitHubHostedRunner` when you need the answer the Actions service reports. + * + * @returns true iff the runner looks like it is hosted by GitHub */ -export function isHostedRunner() { +export function looksLikeHostedRunner() { return ( // Name of the runner on hosted Windows runners process.env["RUNNER_NAME"]?.includes("Hosted Agent") || @@ -861,21 +814,13 @@ export function parseMatrixInput( if (matrixInput === undefined || matrixInput === "null") { return undefined; } - return JSON.parse(matrixInput) as { [key: string]: string }; -} - -export function wrapError(error: unknown): Error { - return error instanceof Error ? error : new Error(String(error)); -} - -/** - * Returns an appropriate message for the error. - * - * If the error is an `Error` instance, this returns the error message without - * an `Error: ` prefix. - */ -export function getErrorMessage(error: unknown): string { - return error instanceof Error ? error.message : String(error); + try { + return JSON.parse(matrixInput) as { [key: string]: string }; + } catch (err) { + throw new Error( + `Failed to parse matrix input '${matrixInput}': ${getErrorMessage(err)}`, + ); + } } export function prettyPrintPack(pack: Pack) { @@ -909,7 +854,7 @@ export async function checkDiskUsage( } else { logger.debug(message); } - core.exportVariable(EnvVar.HAS_WARNED_ABOUT_DISK_SPACE, "true"); + exportEnvVar(EnvVar.HAS_WARNED_ABOUT_DISK_SPACE, "true"); } return { numAvailableBytes: diskUsage.bavail * blockSizeInBytes, @@ -958,7 +903,7 @@ export function checkActionVersion( "https://github.blog/changelog/2025-10-28-upcoming-deprecation-of-codeql-action-v3/", ); // set LOG_VERSION_DEPRECATION env var to prevent the warning from being logged multiple times - core.exportVariable(EnvVar.LOG_VERSION_DEPRECATION, "true"); + exportEnvVar(EnvVar.LOG_VERSION_DEPRECATION, "true"); } } } @@ -1004,7 +949,11 @@ export enum BuildMode { } export function cloneObject(obj: T): T { - return JSON.parse(JSON.stringify(obj)) as T; + try { + return JSON.parse(JSON.stringify(obj)) as T; + } catch (err) { + throw new Error(`Cloning object failed: ${getErrorMessage(err)}`); + } } export async function cleanUpPath(file: string, name: string, logger: Logger) { diff --git a/src/workflow.test.ts b/src/workflow.test.ts index c7f168a9dc..c7b7aebc02 100644 --- a/src/workflow.test.ts +++ b/src/workflow.test.ts @@ -3,11 +3,14 @@ import * as yaml from "js-yaml"; import * as sinon from "sinon"; import * as actionsUtil from "./actions-util"; -import { createStubCodeQL, getCodeQLForTesting } from "./codeql"; -import { EnvVar } from "./environment"; +import { createStubCodeQL } from "./codeql"; +import { ActionsEnvVars, EnvVar } from "./environment"; import { checkExpectedLogMessages, + getCodeQLForTesting, + createTestConfig, getRecordingLogger, + getTestEnv, LoggedMessage, setupTests, } from "./testing-utils"; @@ -1002,3 +1005,124 @@ test.serial( t.is(messages.length, 0); }, ); + +test("getRepositoryRootOrThrow - gets root from config", async (t) => { + const expectedRoot = "/path/to/root"; + const repositoryRoot = workflow.getRepositoryRootOrThrow( + {}, + "testJob", + {}, + createTestConfig({ repositoryRoot: expectedRoot }), + getTestEnv(), + ); + + t.is(repositoryRoot, expectedRoot); +}); + +test("getRepositoryRootOrThrow - gets root from workflow", async (t) => { + const expectedRoot = "/path/to/root"; + const repositoryRoot = workflow.getRepositoryRootOrThrow( + { + jobs: { + testJob: { + steps: [ + { + uses: "github/codeql-action/analyze", + with: { checkout_path: expectedRoot }, + }, + ], + }, + }, + }, + "testJob", + {}, + createTestConfig({}), + getTestEnv(), + ); + + t.is(repositoryRoot, expectedRoot); +}); + +test("getRepositoryRootOrThrow - gets root from environment", async (t) => { + const expectedRoot = "/path/to/root"; + const repositoryRoot = workflow.getRepositoryRootOrThrow( + { + jobs: { testJob: { steps: [{ uses: "github/codeql-action/analyze" }] } }, + }, + "testJob", + {}, + createTestConfig({}), + getTestEnv({ [ActionsEnvVars.GITHUB_WORKSPACE]: expectedRoot }), + ); + + t.is(repositoryRoot, expectedRoot); +}); + +test("getRepositoryRootOrThrow - throws if there's no matching job", async (t) => { + t.throws( + () => + workflow.getRepositoryRootOrThrow( + { + jobs: { + otherJob: { + steps: [ + { + uses: "github/codeql-action/analyze", + with: { checkout_path: "/some/path" }, + }, + ], + }, + }, + }, + "testJob", + {}, + createTestConfig({}), + getTestEnv(), + ), + { message: /since the workflow has no job named testJob./ }, + ); +}); + +test("getRepositoryRootOrThrow - throws if there's no analyze step", async (t) => { + t.throws( + () => + workflow.getRepositoryRootOrThrow( + { + jobs: { + testJob: { steps: [] }, + }, + }, + "testJob", + {}, + createTestConfig({}), + getTestEnv(), + ), + { message: /since the testJob job does not call/ }, + ); +}); + +test("getRepositoryRootOrThrow - throws if the env var is not set", async (t) => { + t.throws( + () => + workflow.getRepositoryRootOrThrow( + { + jobs: { + testJob: { + steps: [ + { + uses: "github/codeql-action/analyze", + }, + ], + }, + }, + }, + "testJob", + {}, + createTestConfig({}), + getTestEnv(), + ), + { + message: `${ActionsEnvVars.GITHUB_WORKSPACE} environment variable must be set`, + }, + ); +}); diff --git a/src/workflow.ts b/src/workflow.ts index 151cfd5c5d..fb549250be 100644 --- a/src/workflow.ts +++ b/src/workflow.ts @@ -8,7 +8,8 @@ import * as yaml from "js-yaml"; import { isDynamicWorkflow } from "./actions-util"; import * as api from "./api-client"; import { CodeQL } from "./codeql"; -import { EnvVar } from "./environment"; +import type { Config } from "./config-utils"; +import { ActionsEnvVars, EnvVar, getEnv, ReadOnlyEnv } from "./environment"; import { Logger } from "./logging"; import { getRequiredEnvParam, @@ -441,27 +442,45 @@ export function getUploadInputOrThrow( } /** - * Makes a best effort attempt to retrieve the checkout_path input for the - * particular job, given a set of matrix variables. + * Makes a best effort attempt to determine the root path of the repository that the analysis + * relates to. We need that to make paths in SARIF files relative. + * + * - If available, we take the `repositoryRoot` from the `config`. + * - If it isn't, we fall back to trying to extract a `checkout_path` input from the `workflow`. + * - Finally, we fall back to the value of `GITHUB_WORKSPACE`. * * Typically you'll want to wrap this function in a try/catch block and handle the error. * - * @returns the checkout_path input - * @throws an error if the checkout_path input could not be determined + * @param workflow The workflow specification of the currently running workflow. + * @param jobName The name of the job that is currently running. + * @param matrixVars The matrix variables, if any. + * @param config The CodeQL Action configuration state. + * @param env The environment variables. + * + * @returns The repository root path, or its best approximation. + * @throws `Error` if the repository root could not be determined. */ -export function getCheckoutPathInputOrThrow( +export function getRepositoryRootOrThrow( workflow: Workflow, jobName: string, matrixVars: { [key: string]: string } | undefined, + config: Partial, + env: ReadOnlyEnv = getEnv(), ): string { return ( + // If the CodeQL Action already has a persisted repository root, then we can just use that. + config.repositoryRoot ?? + // Otherwise, try to retrieve it from a `checkout_path` input in the workflow specification. getInputOrThrow( workflow, jobName, getAnalyzeActionName(), "checkout_path", matrixVars, - ) || getRequiredEnvParam("GITHUB_WORKSPACE") // if unspecified, checkout_path defaults to ${{ github.workspace }} + ) ?? + // Finally, if all of the above fail, just use the value of `GITHUB_WORKSPACE` since that + // is what is used by default. + env.getRequired(ActionsEnvVars.GITHUB_WORKSPACE) ); } diff --git a/tests/multi-language-repo/.github/codeql/codeql-config-query-filters1.yml b/tests/multi-language-repo/.github/codeql/codeql-config-query-filters1.yml index 91a8dce370..fbd19b7293 100644 --- a/tests/multi-language-repo/.github/codeql/codeql-config-query-filters1.yml +++ b/tests/multi-language-repo/.github/codeql/codeql-config-query-filters1.yml @@ -1,12 +1,12 @@ name: "Check SARIF for default queries with Single include, Single exclude" query-filters: -# This should run js/path-injection and js/zipslip -- include: - tags contain: + # This should run js/path-injection and js/zipslip + - include: + tags contain: - external/cwe/cwe-022 -# Removes js/path-injection -- exclude: - id: + # Removes js/path-injection + - exclude: + id: - js/path-injection diff --git a/tests/multi-language-repo/.github/codeql/codeql-config-query-filters2.yml b/tests/multi-language-repo/.github/codeql/codeql-config-query-filters2.yml index c0d6869624..0bd794eb65 100644 --- a/tests/multi-language-repo/.github/codeql/codeql-config-query-filters2.yml +++ b/tests/multi-language-repo/.github/codeql/codeql-config-query-filters2.yml @@ -8,17 +8,17 @@ packs: - codeql-testing/codeql-pack1@1.0.0 query-filters: -# This should run js/path-injection and js/zipslip -- include: - tags contain: + # This should run js/path-injection and js/zipslip + - include: + tags contain: - external/cwe/cwe-022 -# Removes js/path-injection -- exclude: - id: + # Removes js/path-injection + - exclude: + id: - js/path-injection -# Query from extra pack -- include: - id: + # Query from extra pack + - include: + id: - javascript/example/empty-or-one-block diff --git a/tests/multi-language-repo/.github/codeql/codeql-config-query-filters3.yml b/tests/multi-language-repo/.github/codeql/codeql-config-query-filters3.yml index 619442d0fd..26171f0bb6 100644 --- a/tests/multi-language-repo/.github/codeql/codeql-config-query-filters3.yml +++ b/tests/multi-language-repo/.github/codeql/codeql-config-query-filters3.yml @@ -3,37 +3,36 @@ name: "Check SARIF for query packs and local queries with Single include, Single disable-default-queries: true queries: -# Local query + # Local query - name: Run an extra local query uses: ./codeql-qlpacks/javascript-qlpack/show_ifs.ql -# These queries are ignored + # These queries are ignored - name: Ignored queries uses: ./codeql-qlpacks/complex-python-qlpack/rootAndBar.qls - packs: javascript: - codeql/javascript-queries - codeql-testing/codeql-pack1@1.0.0 query-filters: -# This should run js/path-injection and js/zipslip -- include: - tags contain: - - external/cwe/cwe-022 - -# Removes js/path-injection -- exclude: - id: - - js/path-injection - -# Query from extra pack -- include: - id: - - javascript/example/empty-or-one-block - -# Local query -- include: - id: - - inrepo-javascript-querypack/show-ifs + # This should run js/path-injection and js/zipslip + - include: + tags contain: + - external/cwe/cwe-022 + + # Removes js/path-injection + - exclude: + id: + - js/path-injection + + # Query from extra pack + - include: + id: + - javascript/example/empty-or-one-block + + # Local query + - include: + id: + - inrepo-javascript-querypack/show-ifs diff --git a/tests/multi-language-repo/.github/codeql/custom-queries.yml b/tests/multi-language-repo/.github/codeql/custom-queries.yml index fc80426f70..0e9ff0ff4e 100644 --- a/tests/multi-language-repo/.github/codeql/custom-queries.yml +++ b/tests/multi-language-repo/.github/codeql/custom-queries.yml @@ -3,22 +3,22 @@ name: Use custom queries disable-default-queries: true queries: -# Query suites + # Query suites - name: Select a query suite uses: ./codeql-qlpacks/complex-python-qlpack/rootAndBar.qls -# QL pack subset + # QL pack subset - name: Select a ql file uses: ./codeql-qlpacks/complex-javascript-qlpack/show_ifs.ql - name: Select a subfolder uses: ./codeql-qlpacks/complex-javascript-qlpack/foo - name: Select a folder with two subfolders uses: ./codeql-qlpacks/complex-javascript-qlpack/foo2 -# Inrepo QL pack + # Inrepo QL pack - name: Select an inrepo ql pack uses: ./codeql-qlpacks/csharp-qlpack - name: Java queries uses: ./codeql-qlpacks/java-qlpack -# External QL packs + # External QL packs - name: Go queries uses: codeql-testing/go-querypack@master - name: Cpp queries diff --git a/tests/multi-language-repo/codeql-qlpacks/complex-javascript-qlpack/qlpack.yml b/tests/multi-language-repo/codeql-qlpacks/complex-javascript-qlpack/qlpack.yml index 95acb04f05..2fc3910e27 100644 --- a/tests/multi-language-repo/codeql-qlpacks/complex-javascript-qlpack/qlpack.yml +++ b/tests/multi-language-repo/codeql-qlpacks/complex-javascript-qlpack/qlpack.yml @@ -1,3 +1,3 @@ name: complex-javascript-querypack version: 0.0.1 -libraryPathDependencies: codeql-javascript \ No newline at end of file +libraryPathDependencies: codeql-javascript diff --git a/tests/multi-language-repo/codeql-qlpacks/complex-python-qlpack/qlpack.yml b/tests/multi-language-repo/codeql-qlpacks/complex-python-qlpack/qlpack.yml index 349294dcfc..129bb60782 100644 --- a/tests/multi-language-repo/codeql-qlpacks/complex-python-qlpack/qlpack.yml +++ b/tests/multi-language-repo/codeql-qlpacks/complex-python-qlpack/qlpack.yml @@ -1,3 +1,3 @@ name: inrepo-python-querypack version: 0.0.1 -libraryPathDependencies: codeql-python \ No newline at end of file +libraryPathDependencies: codeql-python diff --git a/tests/multi-language-repo/codeql-qlpacks/cpp-qlpack/qlpack.yml b/tests/multi-language-repo/codeql-qlpacks/cpp-qlpack/qlpack.yml index 7c2ea26cde..5890a85433 100644 --- a/tests/multi-language-repo/codeql-qlpacks/cpp-qlpack/qlpack.yml +++ b/tests/multi-language-repo/codeql-qlpacks/cpp-qlpack/qlpack.yml @@ -1,3 +1,3 @@ name: inrepo-cpp-querypack version: 0.0.1 -libraryPathDependencies: codeql-cpp \ No newline at end of file +libraryPathDependencies: codeql-cpp diff --git a/tests/multi-language-repo/codeql-qlpacks/csharp-qlpack/qlpack.yml b/tests/multi-language-repo/codeql-qlpacks/csharp-qlpack/qlpack.yml index 9a54e7e92f..b917d2412b 100644 --- a/tests/multi-language-repo/codeql-qlpacks/csharp-qlpack/qlpack.yml +++ b/tests/multi-language-repo/codeql-qlpacks/csharp-qlpack/qlpack.yml @@ -1,3 +1,3 @@ name: inrepo-csharp-querypack version: 0.0.1 -libraryPathDependencies: codeql-csharp \ No newline at end of file +libraryPathDependencies: codeql-csharp diff --git a/tests/multi-language-repo/codeql-qlpacks/go-qlpack/qlpack.yml b/tests/multi-language-repo/codeql-qlpacks/go-qlpack/qlpack.yml index 59ccb68818..2bfd0c9a8f 100644 --- a/tests/multi-language-repo/codeql-qlpacks/go-qlpack/qlpack.yml +++ b/tests/multi-language-repo/codeql-qlpacks/go-qlpack/qlpack.yml @@ -1,3 +1,3 @@ name: inrepo-go-querypack version: 0.0.1 -libraryPathDependencies: codeql-go \ No newline at end of file +libraryPathDependencies: codeql-go diff --git a/tests/multi-language-repo/codeql-qlpacks/java-qlpack/qlpack.yml b/tests/multi-language-repo/codeql-qlpacks/java-qlpack/qlpack.yml index 06e8cae7d3..86533bde39 100644 --- a/tests/multi-language-repo/codeql-qlpacks/java-qlpack/qlpack.yml +++ b/tests/multi-language-repo/codeql-qlpacks/java-qlpack/qlpack.yml @@ -1,3 +1,3 @@ name: inrepo-java-querypack version: 0.0.1 -libraryPathDependencies: codeql-java \ No newline at end of file +libraryPathDependencies: codeql-java diff --git a/tests/multi-language-repo/codeql-qlpacks/javascript-qlpack/qlpack.yml b/tests/multi-language-repo/codeql-qlpacks/javascript-qlpack/qlpack.yml index f6d5a7b6db..0715661b48 100644 --- a/tests/multi-language-repo/codeql-qlpacks/javascript-qlpack/qlpack.yml +++ b/tests/multi-language-repo/codeql-qlpacks/javascript-qlpack/qlpack.yml @@ -1,3 +1,3 @@ name: inrepo-javascript-querypack version: 0.0.1 -libraryPathDependencies: codeql-javascript \ No newline at end of file +libraryPathDependencies: codeql-javascript diff --git a/tests/multi-language-repo/codeql-qlpacks/python-qlpack/qlpack.yml b/tests/multi-language-repo/codeql-qlpacks/python-qlpack/qlpack.yml index 349294dcfc..129bb60782 100644 --- a/tests/multi-language-repo/codeql-qlpacks/python-qlpack/qlpack.yml +++ b/tests/multi-language-repo/codeql-qlpacks/python-qlpack/qlpack.yml @@ -1,3 +1,3 @@ name: inrepo-python-querypack version: 0.0.1 -libraryPathDependencies: codeql-python \ No newline at end of file +libraryPathDependencies: codeql-python diff --git a/unreleased-change-notes/.gitkeep b/unreleased-change-notes/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/unreleased-change-notes/README.md b/unreleased-change-notes/README.md new file mode 100644 index 0000000000..3030210a7a --- /dev/null +++ b/unreleased-change-notes/README.md @@ -0,0 +1,34 @@ +## Change notes + +Change-notes are Markdown files used to document user-facing changes. When making a change that affects users, create a Markdown file here that describes the change. During the next release, the change-note files in `unreleased-change-notes/` will automatically be added to `CHANGELOG.md`. + +### What do document + +Some guidelines to help you decide whether a change needs a change note: + +- New functionality that is gated behind a feature flag should be documented when it is added, highlighting that the feature will only be rolled out later. Ideally, this should also include an estimate for when the feature is expected to become available. +- When a feature flag is removed and the gated functionality becomes the default behaviour, this does not need to be documented. +- Changes that may require users to make changes to their workflows must be documented. + +If in doubt, see `CHANGELOG.md` for what we have included previously. + +### Change-note file format + +Change-note files must follow a certain format so that they can be automatically validated and processed. Failure to follow the format will result in a failed PR check. + +You may validate your change-note file locally by running `npx tsx pr-checks/changenotes.ts validate`. This command will scan all change-note files in `unreleased-change-notes/` and report any errors. + + +#### Body + +The body of the change-note file must: + +- Be written in valid [GitHub-Flavored Markdown](https://github.github.com/gfm/). +- Be structured as a single unordered Markdown list with hyphen (`-`) bullets. Each list item should describe a single change. If there are multiple changes, use multiple list items. + +### Example change-note file + +``` +- Fixed a bug where a network error while streaming the download of the CodeQL bundle could terminate the `init` Action instead of falling back to downloading the bundle before extracting it. [#4061](https://github.com/github/codeql-action/pull/4061) +- Fix incorrect minimum required Git version for [improved incremental analysis](https://github.com/github/roadmap/issues/1158): it should have been 2.36.0, not 2.11.0. [#3781](https://github.com/github/codeql-action/pull/3781) +``` diff --git a/unreleased-change-notes/decode-diff-informed-sarif-uris.md b/unreleased-change-notes/decode-diff-informed-sarif-uris.md new file mode 100644 index 0000000000..b233ef4373 --- /dev/null +++ b/unreleased-change-notes/decode-diff-informed-sarif-uris.md @@ -0,0 +1 @@ +- Fixed diff-informed alert filtering incorrectly removing alerts in changed files whose paths contain spaces, special characters, or non-ASCII characters. [#4283](https://github.com/github/codeql-action/pull/4283) diff --git a/upload-sarif/action.yml b/upload-sarif/action.yml index dae34ec528..75c5858e2f 100644 --- a/upload-sarif/action.yml +++ b/upload-sarif/action.yml @@ -1,6 +1,6 @@ -name: 'Code Scanning : Upload SARIF' -description: 'Upload the analysis results' -author: 'GitHub' +name: "Code Scanning : Upload SARIF" +description: "Upload the analysis results" +author: "GitHub" inputs: sarif_file: description: | @@ -8,7 +8,7 @@ inputs: See https://docs.github.com/en/code-security/code-scanning/integrating-with-code-scanning/uploading-a-sarif-file-to-github#uploading-a-code-scanning-analysis-with-github-actions for information on the maximum number of results and maximum file size supported by code scanning. required: false - default: '../results' + default: "../results" checkout_path: description: "The path at which the analyzed repository was checked out. Used to relativize any absolute paths in the uploaded SARIF file." required: false @@ -42,5 +42,5 @@ outputs: { "code-scanning": "some-id", "code-quality": "some-other-id" } runs: using: node24 - main: '../lib/upload-sarif-entry.js' - post: '../lib/upload-sarif-post-entry.js' + main: "../lib/upload-sarif-entry.js" + post: "../lib/upload-sarif-post-entry.js"